1. 程式人生 > >springboot框架開發微信公眾號(一)之連線微信伺服器

springboot框架開發微信公眾號(一)之連線微信伺服器

前幾個月研究了一下用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;  
	}  

}