key1_beacon_api/ARW.WebApi/Controllers/Api/Wechat/WeChatLoginController.cs

113 lines
3.6 KiB
C#

using ARW.Admin.WebApi.Controllers;
using ARW.Admin.WebApi.Extensions;
using ARW.Admin.WebApi.Framework;
using ARW.Model.Dto.Business.Customers;
using ARW.Model.Models.Business.Customers;
using ARW.Model.System;
using ARW.Service.Business.IBusinessService.Customers;
using Infrastructure.WeChat.Login;
using Infrastructure;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.Net;
using Senparc.Weixin.WxOpen.AdvancedAPIs.WxApp.Business.JsonResult;
using Senparc.Weixin.WxOpen;
using Senparc.Weixin;
using Senparc.Weixin.CommonAPIs;
using Senparc.Weixin.Open.WxOpenAPIs;
using Senparc.Weixin.WxOpen.AdvancedAPIs.WxApp;
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 OptionsSetting _jwtSettings;
public WeChatLoginController(WeChatLogin weChat, ICustomerService customerService, IOptions<OptionsSetting> jwtSettings)
{
_weChat = weChat;
_customerService = customerService;
_jwtSettings = jwtSettings.Value;
}
/// <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);
var user = await _customerService.GetFirstAsync(s => s.CustomerXcxOpenid == parm.CustomerXcxOpenid);
if (user == null)
{
addModal.CustomerMobilePhoneNumber = await GetUserPhoneNumber(parm.Code);
var response = await _customerService.InsertReturnSnowflakeIdAsync(addModal);
if (response == 0)
{
throw new CustomException("添加失败!");
}
user = await _customerService.GetFirstAsync(s => s.CustomerGuid == response);
}
LoginUser loginUser = new LoginUser
{
UserId = user.CustomerGuid,
UserName = user.CustomerNickname,
UserPhone = user.CustomerMobilePhoneNumber,
IsApi = true,
};
var jwt = JwtUtil.GenerateJwtToken(JwtUtil.AddClaims(loginUser), _jwtSettings.JwtSettings);
return SUCCESS(jwt);
}
/// <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);
}
}
}
}