WXUtils.java
2.2 KB
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
package com.framework.util;
import java.security.MessageDigest;
import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.binary.Hex;
import com.alibaba.fastjson.JSONObject;
import com.framework.vo.TokenInfo;
/**
* 微信 工具类
*
* @author dingoolu
*
*/
public class WXUtils {
/**
* 检查数据是否来自微信验证
*
* @param request
* @return
*/
public static Boolean checkIsWx(HttpServletRequest request, String token) {
try {
String signature = request.getParameter("signature"); // 微信加密签名(token、timestamp、nonce。)
String timestamp = request.getParameter("timestamp"); // 时间戳
String nonce = request.getParameter("nonce"); // 随机数
String echostr = request.getParameter("echostr"); // 随机字符串
String[] params = new String[] {token, timestamp, nonce };
Arrays.sort(params);
// 将三个参数字符串拼接成一个字符串进行sha1加密
String clearText = params[0] + params[1] + params[2];
String algorithm = "SHA-1";
String sign = new String(Hex.encodeHex(MessageDigest.getInstance(algorithm).digest(clearText.getBytes()), true));
if (sign.equals(signature)) {
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* @param code
* @param appId
* @param secret
* @return
*/
public static TokenInfo getTokenInfo(String code, String appId, String secret) {
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + secret + "&code=" + code
+ "&grant_type=authorization_code";
try {
String result = HtmlUtils.getWebContent(url);
System.out.println(result);
JSONObject json = JSONObject.parseObject(result);
TokenInfo info = new TokenInfo();
info.setAccessToken(json.getString("access_token"));
info.setOpenId(json.getString("openid"));
info.setRefreshToken(json.getString("refresh_token"));
System.out.println("openId:" + info.getOpenId());
return info;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}