前幾個月研究了一下用springboot開發微信公衆號,現在做一下整理總結
開發準備
1.申請微信公衆平臺測試號(測試號適用於開發階段)
2.有jdk和開發工具(這裏筆者選擇jdk1.8和STS)
流程圖
代碼實現
1.新建springboot項目,在controller層創建一個控制類
package com.gzc.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.gzc.weixin.util.WeiXinSignUtil;
/**
*
* @Description: 微信請求處理的核心類
* @Parameters:
* @Return:
* @Create Date:
* @Version: V1.00
* @author: 來日可期
*/
@RestController
@RequestMapping(value="/wechat")
public class WeixinCoreController {
private static Logger logger = LoggerFactory.getLogger(WeixinCoreController.class);
@Autowired
private WeiXinSignUtil weixinSignUtil;
/**
* @Description: 驗證請求是否來自微信服務器
* @Parameters: WeixinCoreController
* @Return: 返回微信服務器發過來的驗證字符
* @Create Date:
* @Version: V1.00
* @author:來日可期
*/
@RequestMapping(value="/access", method=RequestMethod.GET )
public String WeChatInterface(HttpServletRequest request)throws Exception{
System.out.println("-------------驗證微信服務號信息開始----------");
// 微信加密簽名
String signature = request.getParameter("signature");
// 時間戳
String timestamp = request.getParameter("timestamp");
// 隨機數
String nonce = request.getParameter("nonce");
// 隨機字符串
String echostr = request.getParameter("echostr");
logger.info("signature is :"+signature+"timestamp is"+timestamp+"nonce is :"+nonce);
if (weixinSignUtil.checkSignature(signature, timestamp, nonce)){
System.out.println("-----------驗證微信服務號結束------------");
return echostr;
}else {
// 此處可以實現其他邏輯
logger.warn("不是微信服務器發過來的請求,請小心!");
return null;
}
}
2.新建一個工具類用於封裝驗證微信服務器的方法package com.gzc.weixin.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
*
* @Description: 微信請求校驗工具類
* @Parameters:
* @Return:
* @Create Date:
* @Version: V1.00
* @author: 來日可期
*/
@Component
public class WeiXinSignUtil {
public static Logger logger = LoggerFactory.getLogger(WeiXinSignUtil.class);
//與公衆號中配置的TOKEN保持一致
public static String token = "weixin";
/**
* 驗證簽名
* @param signature
* @param timestamp
* @param nonce
* @return
*/
public boolean checkSignature(String signature, String timestamp, String nonce){
String[] arr = new String[] { token, timestamp, nonce };
// 將token、timestamp、nonce三個參數進行字典序排序
Arrays.sort(arr);
StringBuilder content = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
content.append(arr[i]);
}
MessageDigest md = null;
String tmpStr = null;
try {
//創建 MessageDigest對象,MessageDigest 通過其getInstance系列靜態函數來進行實例化和初始化。
md = MessageDigest.getInstance("SHA-1");
// 將三個參數字符串拼接成一個字符串進行sha1加密
byte[] digest = md.digest(content.toString().getBytes());
tmpStr = byteToStr(digest);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
logger.info("執行微信簽名加密認證");
content = null;
// 將sha1加密後的字符串可與signature對比,標識該請求來源於微信
return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
}
/**
* 將字節數組轉換爲十六進制字符串
* @param byteArray
* @return
*/
private static String byteToStr(byte[] byteArray) {
String strDigest = "";
for (int i = 0; i < byteArray.length; i++) {
strDigest += byteToHexStr(byteArray[i]);
}
return strDigest;
}
/**
* 將字節轉換爲十六進制字符串
* @param mByte
* @return
*/
private static String byteToHexStr(byte mByte) {
char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
char[] tempArr = new char[2];
tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
tempArr[1] = Digit[mByte & 0X0F];
String s = new String(tempArr);
return s;
}
}