mitao
2025-01-03 75aa42c51ae2a63d7c1e5e813c0a88fd303bdbf4
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.sinata.web.controller.tool.weChat;
 
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
 
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
import java.util.HashMap;
import java.util.Map;
 
/**
 * 微信工具类
 */
@Slf4j
@Component
public class WeChatUtil {
 
    @Value("456")
    private String wxAppletsAppid;
 
    @Value("123")
    private String wxAppletsAppSecret;
 
//    @Value("${wx.appid}")
    private String webAppId;
 
//    @Value("${wx.appSecret}")
    private String webAppSecret;
 
    
    
 
 
    /**
     * 小程序使用jscode获取openid
     * @param jscode
     * @return
     */
    public Map<String, Object> code2Session(String jscode) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxAppletsAppid + "&secret=" + wxAppletsAppSecret
                + "&js_code=" + jscode + "&grant_type=authorization_code";
        HttpRequest get = HttpUtil.createGet(url);
        HttpResponse response = get.execute();
        int status = response.getStatus();
        if(200 != status){
            throw new RuntimeException(response.body());
        }
        JSONObject jsonObject = JSON.parseObject(response.body());
        int errcode = jsonObject.getIntValue("errcode");
        Map<String, Object> map = new HashMap<>();
        map.put("errcode", errcode);
        if(errcode == 0){//成功
            map.put("openid", jsonObject.getString("openid"));
            map.put("sessionKey", jsonObject.getString("session_key"));
            map.put("unionid", jsonObject.getString("unionid"));
            return map;
        }
        if(errcode == -1){//系统繁忙,此时请开发者稍候再试
            map.put("msg", jsonObject.getString("errmsg"));
            return map;
        }
        if(errcode == 40029){//code 无效
            map.put("msg", jsonObject.getString("errmsg"));
            return map;
        }
        if(errcode == 45011){//频率限制,每个用户每分钟100次
            map.put("msg", jsonObject.getString("errmsg"));
            return map;
        }
        return null;
    }
    
    
 
}