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;  
	}  

}


猜你喜欢

转载自blog.csdn.net/qq_40715775/article/details/79871543