cjl
2023-11-15 df67fe187fae9ce9f486ea2f14c95a14d843e4a1
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
package com.moral.api.utils;
 
 
 
 
 
import org.springframework.http.ResponseEntity;
 
import org.springframework.web.client.RestTemplate;
 
import java.util.HashMap;
import java.util.Map;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
 
 
public class WechatUtils {
 
 
    public static final String APPID = "wxf95fb77e0b1f8c09";
    public static final String SECRET = "acf3be9facf7f26bb8286c9b4eff93d0";
 
    public static JSONObject getSessionKeyOrOpenId(String code) {
 
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> requestUrlParam = new HashMap<>();
        // https://mp.weixin.qq.com/wxopen/devprofile?action=get_profile&token=164113089&lang=zh_CN
        //小程序appId
        requestUrlParam.put("appid", APPID);
        //小程序secret
        requestUrlParam.put("secret",SECRET);
        //小程序端返回的code
        requestUrlParam.put("js_code", code);
        //默认参数
        requestUrlParam.put("grant_type", "authorization_code");
        //发送post请求读取调用微信接口获取openid用户唯一标识
        JSONObject jsonObject = JSON.parseObject(HttpClientUtil.doPost(requestUrl, requestUrlParam));
 
        return jsonObject;
    }
 
    public static String getAccessToken() {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> params = new HashMap<>();
        params.put("APPID", APPID);  //
        params.put("APPSECRET", SECRET);  //
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}", String.class, params);
        String body = responseEntity.getBody();
        JSONObject object = JSON.parseObject(body);
        String Access_Token = object.getString("access_token");
//        String expires_in = object.getString("expires_in");
        return Access_Token;
    }
}