Pu Zhibing
2025-03-17 7f302004e78ca5220a4f88a7fab843964a18739a
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package com.panzhihua.sangeshenbian.utils;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
 
public class SignatureUtil {
 
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    private static final String JSAPI_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi";
 
    public static String getAccessToken(String appId, String appSecret) throws Exception {
        String url = String.format(ACCESS_TOKEN_URL, appId, appSecret);
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
 
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
 
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
 
        Map<String, String> result = parseJson(response.toString());
        return result.get("access_token");
    }
 
 
    public static String getJsApiTicket(String accessToken) throws Exception {
        String url = String.format(JSAPI_TICKET_URL, accessToken);
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
 
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
 
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
 
        Map<String, String> result = parseJson(response.toString());
        return result.get("ticket");
    }
 
    private static Map<String, String> parseJson(String json) {
        // 简单的JSON解析,实际项目中可以使用更强大的库如Jackson或Gson
        Map<String, String> map = new HashMap<>();
        String[] keyValuePairs = json.replace("{", "").replace("}", "").split(",");
        for (String pair : keyValuePairs) {
            String[] entry = pair.split(":");
            map.put(entry[0].trim().replace("\"", ""), entry[1].trim().replace("\"", ""));
        }
        return map;
    }
 
 
    public static String getSignature(String jsapiTicket, String nonceStr, String timestamp, String url) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("jsapi_ticket", jsapiTicket);
        params.put("noncestr", nonceStr);
        params.put("timestamp", timestamp);
        params.put("url", url);
 
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);
 
        StringBuilder sb = new StringBuilder();
        for (String key : keys) {
            sb.append(key).append("=").append(params.get(key)).append("&");
        }
        sb.deleteCharAt(sb.length() - 1); // Remove the last '&'
 
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] hashBytes = md.digest(sb.toString().getBytes(StandardCharsets.UTF_8));
 
        StringBuilder hexString = new StringBuilder();
        for (byte b : hashBytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
 
        return hexString.toString();
    }
}