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 { /// /// 小程序登录控制器 /// //[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 jwtSettings, ICustomerLoginLogService customerLoginLogService) { _weChat = weChat; _customerService = customerService; _jwtSettings = jwtSettings.Value; _CustomerLoginLogService = customerLoginLogService; } /// /// 登录/注册小程序客户 /// /// /// [HttpPost("Login")] public async Task Login([FromBody] CustomerLoginDto parm) { if (parm == null) { throw new CustomException("请求参数错误"); } var addModal = parm.Adapt().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 { { "jwt", jwt }, { "user", user } }; return SUCCESS(dic); } /// /// 退出登录 /// /// [Log(Title = "退出登录")] [HttpPost("logout")] public async Task LogOut() { var userid = HttpContext.GetUId(); var name = HttpContext.GetName(); CacheService.RemoveUserPerms(GlobalConstant.UserPermKEY + userid); return SUCCESS(new { name, id = userid }); } /// /// 获取OpenId /// /// [Log(Title = "获取OpenId")] [HttpPost("getOpenId")] public async Task 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); } /// /// 获取用户手机号 /// /// /// public async Task 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); } } /// /// 发送手机验证码 /// /// /// [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("发送成功!"); } /// /// 通过邮箱修改密码 /// /// /// [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(""); } /// /// 获取OpenId /// /// /// /// /// /// public static async Task 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); } } } } }