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
|
}
|
}
|