using Furion.FriendlyException;
using Furion.HttpRemote;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace FlexJobApi.Core
{
///
/// 微信小程序工具
///
public class WxmpUtils
{
private readonly IOptions options;
private readonly IHttpRemoteService httpRemoteService;
public WxmpUtils(
IOptions options,
IHttpRemoteService httpRemoteService)
{
this.options = options;
this.httpRemoteService = httpRemoteService;
}
public async Task SnsJscode2sessionAsync(EnumUserType userType, string code, CancellationToken cancellationToken = default)
{
var option = options.Value.Items.FirstOrDefault(it => it.Code == userType.ToString());
if (option == null || option.AppId.IsNull() || option.AppSecret.IsNull())
throw Oops.Oh(EnumErrorCodeType.s400, "登录失败,缺失配置:WxmpOptions");
if (code.IsNull())
throw Oops.Oh(EnumErrorCodeType.s400, "请填写WxmpCode");
var callback = await httpRemoteService.GetAsAsync("https://api.weixin.qq.com/sns/jscode2session",
builder => builder.WithQueryParameters(new Dictionary
{
{ "appid", option.AppId },
{ "secret", option.AppSecret },
{ "js_code", code },
{ "grant_type", "authorization_code" }
}));
if (callback == null || callback.errcode != 0)
throw Oops.Oh(EnumErrorCodeType.s510, $"登录失败:{callback.errmsg},请联系管理员");
return callback;
}
}
}