81 lines
2.8 KiB
C#
81 lines
2.8 KiB
C#
|
using Cysharp.Threading.Tasks;
|
||
|
using Microsoft.Extensions.Logging;
|
||
|
using Newtonsoft.Json;
|
||
|
using Newtonsoft.Json.Linq;
|
||
|
|
||
|
namespace WeChatSharp.Services;
|
||
|
|
||
|
public class WeChatMobileService
|
||
|
{
|
||
|
private readonly ILogger<WeChatMobileService> _logger;
|
||
|
|
||
|
|
||
|
public string AppId { get; set; } = string.Empty;
|
||
|
public string AppSecret { get; set; } = string.Empty;
|
||
|
|
||
|
private readonly HttpClient _httpClient=new();
|
||
|
|
||
|
public WeChatMobileService(ILogger<WeChatMobileService> logger)
|
||
|
{
|
||
|
_logger = logger;
|
||
|
}
|
||
|
|
||
|
public async UniTask<WeChatUserInfo> GetUserInfoAsync(string code,string openId)
|
||
|
{
|
||
|
var uri = new UriBuilder("https://api.weixin.qq.com/sns/userinfo")
|
||
|
{
|
||
|
Query = $"access_token={code}&openid={code}"
|
||
|
};
|
||
|
|
||
|
_logger.LogInformation($"请求地址:{uri.Uri}");
|
||
|
|
||
|
var response = await _httpClient.GetAsync(uri.Uri);
|
||
|
|
||
|
var json = await response.Content.ReadAsStringAsync();
|
||
|
var jObject = JsonConvert.DeserializeObject<JObject>(json);
|
||
|
if (jObject is null)
|
||
|
{
|
||
|
throw new NullReferenceException("json为空值");
|
||
|
}
|
||
|
|
||
|
if (jObject.TryGetValue("errcode", out var errcode) && jObject.TryGetValue("errmsg", out var errmsg))
|
||
|
{
|
||
|
throw new Exception(errmsg.ToObject<string>());
|
||
|
}
|
||
|
|
||
|
if (!jObject.TryGetValue("openid", out var openid))
|
||
|
throw new InvalidOperationException("获取OpenId失败")
|
||
|
{
|
||
|
Source = json
|
||
|
};
|
||
|
_logger.LogInformation($"获取OpenId成功:{openid.ToObject<string>()}");
|
||
|
return jObject.ToObject<WeChatUserInfo>() ?? new WeChatUserInfo();
|
||
|
}
|
||
|
public async UniTask<WeChatAccessToken> GetAccessCodeAsync(string code)
|
||
|
{
|
||
|
var uri = new UriBuilder("https://api.weixin.qq.com/sns/oauth2/access_token")
|
||
|
{
|
||
|
Query = $"appid={AppId}&secret={AppSecret}&code={code}&grant_type=authorization_code"
|
||
|
};
|
||
|
var response = await _httpClient.GetAsync(uri.Uri);
|
||
|
var json = await response.Content.ReadAsStringAsync();
|
||
|
var jObject = JsonConvert.DeserializeObject<JObject>(json);
|
||
|
if (jObject is null)
|
||
|
{
|
||
|
throw new NullReferenceException("json为空值");
|
||
|
}
|
||
|
if (jObject.TryGetValue("errcode", out var errcode) && jObject.TryGetValue("errmsg", out var errmsg))
|
||
|
{
|
||
|
throw new Exception(errmsg.ToObject<string>());
|
||
|
}
|
||
|
|
||
|
if (!jObject.TryGetValue("access_token", out var token))
|
||
|
throw new InvalidOperationException("获取AccessToken失败")
|
||
|
{
|
||
|
Source = json
|
||
|
};
|
||
|
_logger.LogInformation($"获取AccessToken成功:{token.ToObject<string>()}");
|
||
|
|
||
|
return jObject.ToObject<WeChatAccessToken>() ?? new WeChatAccessToken();
|
||
|
}
|
||
|
}
|