WeChatUtils.java
2.44 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
75
76
77
78
79
80
81
82
83
84
85
86
package com.phxl.modules.wechat.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import com.alibaba.fastjson.JSONObject;
import com.phxl.common.util.Global;
import com.phxl.common.util.HTTPClient;
import com.phxl.common.utils.CacheUtils;
import com.phxl.modules.wechat.constants.WeChatConstants;
public class WeChatUtils implements ApplicationListener<ContextRefreshedEvent> {
/**
* 校验微信认证
* @param timestamp
* @param nonce
* @return
* @throws NoSuchAlgorithmException
*/
public static final String checkWx(String timestamp,String nonce) throws NoSuchAlgorithmException {
String token = Global.getConfig("token");
String [] strs=new String[] {token,timestamp,nonce};
Arrays.sort(strs);
StringBuilder sb=new StringBuilder();
for (String string : strs) {
sb.append(string);
}
String str=sb.toString();
MessageDigest md=MessageDigest.getInstance("SHA-1");
md.update(str.getBytes());
byte[] digest = md.digest();
StringBuffer hexstr = new StringBuffer();
String shaHex = "";
for (int i = 0; i < digest.length; i++) {
shaHex = Integer.toHexString(digest[i] & 0xFF);
if (shaHex.length() < 2) {
hexstr.append(0);
}
hexstr.append(shaHex);
}
return hexstr.toString();
}
//将accessToken缓存到cache中
public static void getAccessToken() {
String appid=Global.getConfig("appid");
String appsecrent=Global.getConfig("appsecrent");
String token_url=WeChatConstants.Access_Token_url.replace("APPID", appid).replace("APPSECRET", appsecrent);
String sendHttpGet = HTTPClient.sendHttpGet(token_url);
JSONObject jsonObject=JSONObject.parseObject(sendHttpGet);
String access_token = jsonObject.getString(WeChatConstants.Access_Token);
CacheUtils.put(WeChatConstants.Access_Token, access_token);
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
// TODO Auto-generated method stub
if(event.getApplicationContext().getParent()!=null) {
getAccessToken();
}
}
public static String encode(String s) {
if (s == null) {
return null;
}
return DigestUtils.md5Hex(s);
}
public static void ReGetOpenId()
{
}
}