1、登录微信公众平台-->设置与开发-->基本配置页面,打开服务器配置
2、在网站后台添加两个接口get请求验证和post请求消息转发,url为上图填写的url,
@RestController
@RequestMapping("/officialAccount/")
public class OfficialAccountController extends BaseController {@GetMapping("/wechat")public String validate(@RequestParam(value = "signature") String signature,@RequestParam(value = "timestamp") String timestamp,@RequestParam(value = "nonce") String nonce,@RequestParam(value = "echostr") String echostr) {return WeChatHelper.checkSignature(signature, timestamp, nonce) ? echostr : null;}/*** 此处是处理微信服务器的消息转发的*/@PostMapping("/wechat")public String processMsg(HttpServletRequest request) {//System.out.println("message received, start process message!");// 调用核心服务类接收处理请求return processRequest(request);}
}
WeChatHelper 为解密验证的代码
package com.ruoyi.stock.applet.util;import com.ruoyi.common.utils.DateUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;public class WeChatHelper {/*** 验证签名** @param signature* @param timestamp* @param nonce* @return*/public static boolean checkSignature(String signature, String timestamp, String nonce) {String[] arr = new String[] {WeChatConstant.TOKEN, timestamp, nonce};// 将token、timestamp、nonce三个参数进行字典序排序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 {md = MessageDigest.getInstance("SHA-1");// 将三个参数字符串拼接成一个字符串进行sha1加密byte[] digest = md.digest(content.toString().getBytes());tmpStr = byteToStr(digest);} catch (NoSuchAlgorithmException e) {e.printStackTrace();}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;}private static void sort(String a[]) {for (int i = 0; i < a.length - 1; i++) {for (int j = i + 1; j < a.length; j++) {if (a[j].compareTo(a[i]) < 0) {String temp = a[i];a[i] = a[j];a[j] = temp;}}}}/*** 解析微信发来的请求(xml)** @param request* @return* @throws Exception*/@SuppressWarnings({"unchecked"})public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {// 将解析结果存储在HashMap中Map<String, String> map = new HashMap<>();// 从request中取得输入流InputStream inputStream = request.getInputStream();// 读取输入流SAXReader reader = new SAXReader();Document document = reader.read(inputStream);// 得到xml根元素Element root = document.getRootElement();// 得到根元素的所有子节点List<Element> elementList = root.elements();// 遍历所有子节点for (Element e : elementList) { map.put(e.getName(), e.getText()); }// 释放资源inputStream.close();inputStream = null;return map;}public static String mapToXML(Map map) {StringBuffer sb = new StringBuffer();sb.append("<xml>");mapToXML2(map, sb);sb.append("</xml>");try {return sb.toString();} catch (Exception e) {}return null;}private static void mapToXML2(Map map, StringBuffer sb) {Set set = map.keySet();for (Iterator it = set.iterator(); it.hasNext(); ) {String key = (String)it.next();Object value = map.get(key);if (null == value) { value = ""; }if (value.getClass().getName().equals("java.util.ArrayList")) {ArrayList list = (ArrayList)map.get(key);sb.append("<" + key + ">");for (int i = 0; i < list.size(); i++) {HashMap hm = (HashMap)list.get(i);mapToXML2(hm, sb);}sb.append("</" + key + ">");} else {if (value instanceof HashMap) {sb.append("<" + key + ">");mapToXML2((HashMap)value, sb);sb.append("</" + key + ">");} else {sb.append("<" + key + "><![CDATA[" + value + "]]></" + key + ">");}}}}/*** 回复文本消息** @param requestMap* @param content* @return*/public static String sendTextMsg(Map<String, String> requestMap, String content) {Map<String, Object> map = new HashMap<String, Object>();map.put("ToUserName", requestMap.get(WeChatConstant.FromUserName));map.put("FromUserName", requestMap.get(WeChatConstant.ToUserName));map.put("MsgType", WeChatConstant.RESP_MESSAGE_TYPE_TEXT);map.put("CreateTime", DateUtils.getDate());map.put("Content", content);return mapToXML(map);}/*** 回复图文消息** @param requestMap* @param items* @return*/
// public static String sendArticleMsg(Map<String, String> requestMap, List<ArticleItem> items) {
// if (items == null || items.size() < 1) {
// return "";
// }
// Map<String, Object> map = new HashMap<String, Object>();
// map.put("ToUserName", requestMap.get(WeChatConstant.FromUserName));
// map.put("FromUserName", requestMap.get(WeChatConstant.ToUserName));
// map.put("MsgType", "news");
// map.put("CreateTime", DateUtils.getDate());
// List<Map<String, Object>> Articles = new ArrayList<Map<String, Object>>();
// for (ArticleItem item : items) {
// Map<String, Object> itemMap = new HashMap<String, Object>();
// Map<String, Object> itemContent = new HashMap<String, Object>();
// itemContent.put("Title", item.getTitle());
// itemContent.put("Description", item.getDescription());
// itemContent.put("PicUrl", item.getPicUrl());
// itemContent.put("Url", item.getUrl());
// itemMap.put("item", itemContent);
// Articles.add(itemMap);
// }
// map.put("Articles", Articles);
// map.put("ArticleCount", Articles.size());
// return mapToXML(map);
// }}