這幾天正在學(xué)習(xí)微信公眾號開發(fā)宛篇,后臺JAVA基于SSM框架對微信公眾號進行開發(fā)就轧。
微信公眾平臺“基本配置”。詳細(xì)請參考微信開發(fā)者文檔
配置IP白名單腋妙,填寫自己電腦IP地址。如果不配置讯榕,在獲取access_token時微信會攔截IP骤素,造成獲取access_token失敗。如非白名單IP調(diào)用愚屁,將返回錯誤碼:40164 济竹。
-
配置 服務(wù)器地址 和 令牌,并隨機生成EncodingAESKey 霎槐。我使用的后臺是SSM框架送浊,所以配置的服務(wù)器地址如下圖。URL是用來接受微信消息和事件的接口URL丘跌,令牌(Token)會合URL中的Token進行對比驗證罕袋,EncodingAESKey是隨機生成用于消息體解密密鑰。點擊“提交”后微信服務(wù)器會發(fā)送GET請求到填寫的URL上碍岔。服務(wù)器配置截圖
-
后臺Controller中使用get的方式接受請求浴讯,其中包含4個參數(shù)。get請求攜帶參數(shù)列表
設(shè)置token與微信公眾平臺中的Token一致蔼啦,對token榆纽,timestamp,nonce三個參數(shù)進行排序后拼成字符串捏肢,然后進行啥sha1加密奈籽,將加密結(jié)果與signature對比,標(biāo)識該請求來源于微信鸵赫。
@RequestMapping(value = "/weixin.do", method = RequestMethod.GET)
public void testPrint(HttpServletRequest request, HttpServletResponse response) throws IOException {
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
logger.info("進行token驗證--- signature:"+ signature +" timestamp:"+ timestamp +" nonce:"+ nonce + " echostr:"+ echostr);
PrintWriter pw = response.getWriter();
if(CheckUtil.checkSignature(signature,timestamp,nonce)){
System.out.println(echostr);
pw.print(echostr);
logger.info("token驗證成功");
}else{
logger.info("token驗證失敗");
}
pw.close();
}
public static boolean checkSignature(String signature, String timestamp, String nonce) throws IOException {
String token = WeChatConfigProperties.getValue("token");
String[] arr = new String[]{token,timestamp,nonce};
Arrays.sort(arr); // 排序
StringBuffer content = new StringBuffer();
for (int i= 0; i<arr.length; i++){
content.append(arr[i]);
}
String temp = getSha1(content.toString());
return temp.equals(signature);
}
public static String getSha1(String str){
if(str==null||str.length()==0){
return null;
}
char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f'};
try {
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes("UTF-8"));
byte[] md = mdTemp.digest();
int j = md.length;
char buf[] = new char[j*2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
} catch (Exception e) {
// TODO: handle exception
return null;
}
}