WeChatService.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using Hotline.Share.Dtos.Snapshot;
  2. using Hotline.Users;
  3. using Microsoft.Extensions.Logging;
  4. using Senparc.CO2NET.Extensions;
  5. using Senparc.Weixin;
  6. using Senparc.Weixin.WxOpen.AdvancedAPIs.Sns;
  7. using Senparc.Weixin.WxOpen.AdvancedAPIs.WxApp;
  8. using Senparc.Weixin.WxOpen.Containers;
  9. using XF.Domain.Exceptions;
  10. namespace Hotline.WeChat;
  11. public class WeChatService : IThirdIdentiyService
  12. {
  13. private readonly ILogger<WeChatService> _logger;
  14. public WeChatService(ILogger<WeChatService> logger)
  15. {
  16. _logger = logger;
  17. }
  18. public async Task<ThirdTokenOutDto> GetTokenAsync(ThirdTokenDto dto)
  19. {
  20. try
  21. {
  22. var result = await SnsApi.JsCode2JsonAsync(dto.AppId, dto.Secret, dto.LoginCode);
  23. if (result.errcode != ReturnCode.请求成功) throw UserFriendlyException.SameMessage("获取微信用户信息失败");
  24. return new ThirdTokenOutDto() { SessionKey = result.session_key, OpenId = result.openid };
  25. }
  26. catch (Exception e)
  27. {
  28. _logger.LogError("微信登录失败:" + e.Message + "\r\n" + e.StackTrace);
  29. throw UserFriendlyException.SameMessage("微信登录失败:" + e.Message);
  30. }
  31. }
  32. /// <summary>
  33. /// 获取手机号码
  34. /// </summary>
  35. /// <param name="dto"></param>
  36. /// <returns></returns>
  37. public async Task<ThirdPhoneOutDto> GetPhoneNumberAsync(ThirdTokenDto dto)
  38. {
  39. await AccessTokenContainer.RegisterAsync(dto.AppId, dto.Secret);
  40. _logger.LogInformation($"GetPhoneNumberAsync: {dto.ToJson()}");
  41. var result = await BusinessApi.GetUserPhoneNumberAsync(dto.AppId, dto.TelCode);
  42. if (result.errcode != ReturnCode.请求成功)
  43. _logger.LogError($"GetPhoneNumberAsync: {result.ToJson()}");
  44. return new ThirdPhoneOutDto()
  45. {
  46. ErrorCode = (int)result.errcode,
  47. IsError = result.errcode != ReturnCode.请求成功,
  48. ErrorMessage = result.errmsg + " " + result.errcode,
  49. PhoneNumber = result.phone_info?.phoneNumber
  50. };
  51. }
  52. }