key1_beacon_api/ARW.WebApi/Controllers/Api/Wechat/WeChatLoginController.cs
2023-11-22 12:17:14 +08:00

283 lines
10 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using ARW.Admin.WebApi.Controllers;
using ARW.Admin.WebApi.Extensions;
using ARW.Admin.WebApi.Framework;
using ARW.Model.System;
using Infrastructure.WeChat.Login;
using Infrastructure;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Senparc.Weixin.WxOpen.AdvancedAPIs.WxApp;
using ARW.Common;
using ARW.Model.System.Dto;
using SixLabors.Shapes;
using ARW.Model.Dto.Business.Custom.Customers;
using ARW.Model.Models.Business.Custom.Customers;
using ARW.Service.System;
using Infrastructure.Attribute;
using ARW.Service.Business.IBusinessService.Custom.Customers;
using Newtonsoft.Json.Linq;
using Aliyun.OSS;
using ARW.Service.Business.IBusinessService.Custom.CustomerLoginLogs;
using ARW.Model.Models.Business.Custom.CustomerLoginLogs;
namespace ARW.WebApi.Controllers.Api.Wechat
{
/// <summary>
/// 小程序登录控制器
/// </summary>
//[Verify]
[Route("api/[controller]")]
public class WeChatLoginController : BaseController
{
private readonly WeChatLogin _weChat;
private readonly ICustomerService _customerService;
private readonly ICustomerLoginLogService _CustomerLoginLogService;
private readonly OptionsSetting _jwtSettings;
public WeChatLoginController(WeChatLogin weChat, ICustomerService customerService, IOptions<OptionsSetting> jwtSettings, ICustomerLoginLogService customerLoginLogService)
{
_weChat = weChat;
_customerService = customerService;
_jwtSettings = jwtSettings.Value;
_CustomerLoginLogService = customerLoginLogService;
}
/// <summary>
/// 登录/注册小程序客户
/// </summary>
/// <param name="parm"></param>
/// <returns></returns>
[HttpPost("Login")]
public async Task<IActionResult> Login([FromBody] CustomerLoginDto parm)
{
if (parm == null)
{
throw new CustomException("请求参数错误");
}
var addModal = parm.Adapt<Customer>().ToCreate(HttpContext);
addModal.CustomerPassword = NETCore.Encrypt.EncryptProvider.Md5(addModal.CustomerPassword);
var user = new Customer();
/* 用户名密码登录 */
if (!string.IsNullOrEmpty(addModal.CustomerNickname) && !string.IsNullOrEmpty(addModal.CustomerPassword))
{
user = await _customerService.GetFirstAsync(s => s.CustomerNickname == addModal.CustomerNickname && s.CustomerPassword == addModal.CustomerPassword);
if (user == null) throw new CustomException("用户名或者密码错误");
}
/* 手机号登录(微信一键登录) */
if (!string.IsNullOrEmpty(parm.Code))
{
addModal.CustomerMobilePhoneNumber = await GetUserPhoneNumber(parm.Code);
user = await _customerService.GetFirstAsync(s => s.CustomerMobilePhoneNumber == addModal.CustomerMobilePhoneNumber);
}
#region
/* 注册 */
//if (user == null)
//{
// string appId = AppSettings.GetConfig("SenparcWeixinSetting:TenPayV3_AppId");
// string appSecret = AppSettings.GetConfig("SenparcWeixinSetting:TenPayV3_AppSecret");
// //string openid = await GetOpenIDAsync(parm.CustomerXcxOpenidCode, appId, appSecret);
// // 客户默认头像
// addModal.CustomerAvatar = "https://cdn-we-retail.ym.tencent.com/miniapp/usercenter/icon-user-center-avatar@2x.png";
// addModal.CustomerNickname = "用户" + addModal.CustomerMobilePhoneNumber.Substring(addModal.CustomerMobilePhoneNumber.Length - 4); ;
// addModal.CustomerGender = 1;
// addModal.CustomerType = 1;
// addModal.CustomerLastLoginTime = DateTime.Now;
// addModal.CustomerXcxOpenid = parm.CustomerXcxOpenid;
// var response = await _customerService.InsertReturnSnowflakeIdAsync(addModal);
// if (response == 0)
// {
// throw new CustomException("添加失败!");
// }
// user = await _customerService.GetFirstAsync(s => s.CustomerGuid == response);
//}
//else
//{
// user.CustomerLastLoginTime = DateTime.Now;
//}
#endregion
var time = DateTime.Now;
// 记录最后登录时间
user.CustomerLastLoginTime = time;
await _customerService.UpdateAsync(user);
// 添加访问记录
var model = new CustomerLoginLog
{
CustomerGuid = user.CustomerGuid,
Create_time = time,
Create_by = user.CustomerNickname,
};
await _CustomerLoginLogService.AddOrUpdateCustomerLoginLog(model);
LoginUser loginUser = new LoginUser
{
UserId = user.CustomerGuid,
UserName = user.CustomerNickname,
UserPhone = user.CustomerMobilePhoneNumber,
IsApi = true,
};
var jwt = JwtUtil.GenerateJwtToken(JwtUtil.AddClaims(loginUser), _jwtSettings.JwtSettings);
var dic = new Dictionary<string, object>
{
{ "jwt", jwt },
{ "user", user }
};
return SUCCESS(dic);
}
/// <summary>
/// 退出登录
/// </summary>
/// <returns></returns>
[Log(Title = "退出登录")]
[HttpPost("logout")]
public async Task<IActionResult> LogOut()
{
var userid = HttpContext.GetUId();
var name = HttpContext.GetName();
CacheService.RemoveUserPerms(GlobalConstant.UserPermKEY + userid);
return SUCCESS(new { name, id = userid });
}
/// <summary>
/// 获取OpenId
/// </summary>
/// <returns></returns>
[Log(Title = "获取OpenId")]
[HttpPost("getOpenId")]
public async Task<IActionResult> GetOpenId([FromBody] CustomerLoginDto parm)
{
string appId = AppSettings.GetConfig("SenparcWeixinSetting:TenPayV3_AppId");
string appSecret = AppSettings.GetConfig("SenparcWeixinSetting:TenPayV3_AppSecret");
string openid = await GetOpenIDAsync(parm.Code, appId, appSecret);
return SUCCESS(openid);
}
/// <summary>
/// 获取用户手机号
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
public async Task<string> GetUserPhoneNumber(string code)
{
try
{
var Appid = AppSettings.GetConfig("SenparcWeixinSetting:TenPayV3_AppId");
var result = await BusinessApi.GetUserPhoneNumberAsync(Appid, code);
if (result.phone_info != null)
{
return result.phone_info.phoneNumber;
}
else
{
throw new Exception("获取手机号报错:" + result);
}
}
catch (Exception ex)
{
throw new Exception("获取手机号报错:" + ex);
}
}
/// <summary>
/// 发送手机验证码
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
[HttpPost("sendPhoneCode")]
public IActionResult PostEmailCode([FromBody] SendPhoneDto dto)
{
//var code = Tools.GetNumCode(4);
AliyunMsgHelper.SendPhoneMsgCode(dto.PhoneNumber);
//CacheHelper.SetCache(user.UserId.ToString() + "emailCode", code, 5);
//var emailCode = CacheHelper.GetCache(user.UserId.ToString() + "emailCode");
//Console.WriteLine(user.UserId.ToString() + ":" + emailCode);
return SUCCESS("发送成功!");
}
/// <summary>
/// 通过邮箱修改密码
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
[HttpPost("changePwByEmail")]
public IActionResult ChangePwByEmail([FromBody] ChangePwByEmailDto dto)
{
//var user = sysUserService.SelectUserByEmail(dto.Email);
//var emailCode = (string)CacheHelper.GetCache(user.UserId.ToString() + "emailCode");
//if (emailCode == null)
//{
// throw new CustomException("验证码已过期,请重新获取!");
//}
//if (dto.code == emailCode)
//{
// sysUserService.ResetPwd(user.UserId, dto.Password);
// return SUCCESS("密码重置成功");
//}
//else
//{
// throw new CustomException("验证码错误,请重试!");
//}
return SUCCESS("");
}
/// <summary>
/// 获取OpenId
/// </summary>
/// <param name="code"></param>
/// <param name="appId"></param>
/// <param name="appSecret"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static async Task<string> GetOpenIDAsync(string code, string appId, string appSecret)
{
string url = $"https://api.weixin.qq.com/sns/jscode2session?appid={appId}&secret={appSecret}&js_code={code}&grant_type=authorization_code";
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
JObject json = JObject.Parse(responseBody);
if (json.ContainsKey("openid"))
{
string openid = json["openid"].ToString();
return openid;
}
else
{
throw new Exception("无法获取OpenID" + json);
}
}
}
}
}