luodangjia
2024-12-10 ee7ce5d1cbf80bee0a15c1e5bc5eaa30858d812b
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
package com.hollywood.applet.utils;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
 
public class WeChatCodeFetcher {
 
    private static final String APP_ID = "wx7c416e2aca3d243b";
    private static final String APP_SECRET = "500b93923b55958df4596b752fde57ff";
//    private static final String REDIRECT_URI = "https://your.redirect.uri"; // 替换为你的重定向URI
    private static final String GET_CODE_API = "https://api.weixin.qq.com/sns/jscode2session";
 
    public static String fetchCode(String jsCode) throws Exception {
        URL url = new URL(GET_CODE_API);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setDoOutput(true);
 
        StringBuilder postData = new StringBuilder();
        postData.append("appid=").append(APP_ID);
        postData.append("&secret=").append(APP_SECRET);
        postData.append("&js_code=").append(jsCode);
        postData.append("&grant_type=authorization_code");
 
        byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);
        connection.getOutputStream().write(postDataBytes);
 
        StringBuilder response = new StringBuilder();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = in.readLine()) != null) {
                response.append(line);
            }
        }
 
        connection.disconnect();
 
        return response.toString(); // 返回JSON格式的响应,包含code
    }
}