添加获取jsapitoken接口

This commit is contained in:
yangjun 2025-06-04 09:47:38 +08:00
parent 31ee24918e
commit 2704de678c
1 changed files with 65 additions and 0 deletions

View File

@ -32,8 +32,11 @@ import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import com.wechat.pay.java.core.notification.RequestParam;
import org.apache.http.HttpEntity;
@ -294,4 +297,66 @@ public class WechatPayController {
System.out.println("---------jsonObject-------"+jsonObject);
return jsonObject;
}
@PostMapping("/getJsApiInfo")
public static Map<String,String> getJsApiInfo(@RequestBody Map<String,String> params) throws Exception {
// String accessToken = getToken(GET_TOKEN_URL, "wx8fc3e4305d2fbf0b", "3bf3dd4ec72f591432db6b28c2c044e5");// 获取token
String accessToken = params.get("access_token");
System.out.println("---------token-------"+accessToken);
// 构造请求URL
String requestUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
// 发送HTTP请求并获取返回结果
HttpGet httpGet = new HttpGet(requestUrl);
System.out.println("---------httpGet-------"+httpGet);
CloseableHttpClient httpClient = HttpClients.createDefault();
System.out.println("---------httpClient-------"+httpClient);
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("---------httpResponse-------"+httpResponse);
HttpEntity httpEntity = httpResponse.getEntity();
System.out.println("---------httpEntity-------"+httpEntity);
String responseJson = EntityUtils.toString(httpEntity, "UTF-8");
System.out.println("---------responseJson-------"+responseJson);
// 解析返回结果获取手机号
JSONObject jsonObject = new JSONObject(responseJson);
String ticket = String.valueOf(jsonObject.get("ticket"));
String nonceStr = UUID.randomUUID().toString();
String timestamp = Long.toString(System.currentTimeMillis() / 1000);
String string1 = new StringBuilder("jsapi_ticket=").append(ticket)
.append("&noncestr=")
.append(nonceStr)
.append("&timestamp=")
.append(timestamp)
.toString();// 得到签名
String signature = encryptSHA(string1);
Map<String,String> map = new HashMap<String,String>();
map.put("signature", signature);
map.put("timestamp", timestamp);
map.put("nonceStr", nonceStr);
System.out.println("---------jsonObject-------"+signature);
return map;
}
/** * sha */
private static String encryptSHA(String signStr) {
StringBuffer hexValue = new StringBuffer();
try {
MessageDigest sha = MessageDigest.getInstance("SHA-1");
byte[] byteArray = signStr.getBytes("UTF-8");
byte[] md5Bytes = sha.digest(byteArray);
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
} catch (Exception e) {
e.printStackTrace(); return "";
} return hexValue.toString();
}
}