sunpengfei
2025-08-14 57a7538deedd5201f69c431e8d11553b0e14ab81
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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
{
    /// <summary>
    /// 微信小程序工具
    /// </summary>
    public class WxmpUtils
    {
        private readonly IOptions<WxmpOptions> options;
        private readonly IHttpRemoteService httpRemoteService;
 
        public WxmpUtils(
            IOptions<WxmpOptions> options,
            IHttpRemoteService httpRemoteService)
        {
            this.options = options;
            this.httpRemoteService = httpRemoteService;
        }
 
        public async Task<WxmpSnsJscode2sessionCallback> 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<WxmpSnsJscode2sessionCallback>("https://api.weixin.qq.com/sns/jscode2session",
                builder => builder.WithQueryParameters(new Dictionary<string, string>
                {
                    { "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;
        }
    }
}