xiangpei
2024-03-28 0f431b52e0936456bd165d9553761bfd8a5a0517
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
package com.mindskip.xzs.utility;
 
 
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.io.IOException;
 
/**
 * @version 2.2.0
 * @description: 微信工具类
 * Copyright (C), 2020-2021, 武汉思维跳跃科技有限公司
 * @date 2021 /9/7 9:45
 */
public class WechatUtil {
    private static final Logger logger = LoggerFactory.getLogger(WechatUtil.class);
    private static final String openIdUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
 
    /**
     * 获取openId
     *
     * @param appId  the app id
     * @param secret the secret
     * @param code   the code
     * @return the open id
     */
    public static String getOpenId(String appId, String secret, String code) {
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            String requestUrl = String.format(openIdUrl, appId, secret, code);
            HttpGet httpGet = new HttpGet(requestUrl);
            HttpEntity responseEntity = httpClient.execute(httpGet).getEntity();
            if (responseEntity != null) {
                String responseStr = EntityUtils.toString(responseEntity);
                if (responseStr.contains("openid")) {
                    WechatResponse wechatResponse = JsonUtil.toJsonObject(responseStr, WechatResponse.class);
                    return wechatResponse.getOpenid();
                }
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }
}