开发环境的搭建--开通隧道
1、官网看介绍,下载客户端:https://www.ngrok.cc/
2、注册账号,申请免费渠道:https://www.ngrok.cc/login
3、用渠道ID,启动,映射本地的8080端口
package com.aja.test_wx.controller;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
public class connect {
private final String TOKEN = "aja";
/**
* 认证
* @param signature
* @param timestamp
* @param nonce
* @param echostr
* @return
* @throws NoSuchAlgorithmException
*/
@GetMapping(value = "/wx/connect")
@ResponseBody
public String connect(String signature, String timestamp, String nonce, String echostr) throws NoSuchAlgorithmException {
System.out.println(signature+"|"+timestamp+"|"+nonce+"|"+echostr);
// 1)将token、timestamp、nonce三个参数进行字典序排序
String[] strs = {TOKEN, timestamp, nonce};
Arrays.sort(strs);
// 2)将三个参数字符串拼接成一个字符串进行sha1加密
String s = strs[0] + strs[1] + strs[2];
String s1 = sha1(s);
// 3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
if (s1.equals(signature)){
//若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。
System.out.println(s1);
System.out.println(signature);
return echostr;
}else {
return "false";
}
}
/**
* 接受消息
* @param xml
* @return
* @throws DocumentException
*/
@PostMapping(value = "/wx/connect")
@ResponseBody
public String message(@RequestBody String xml) throws DocumentException {
Map<String, String> map = new HashMap<>();
SAXReader saxReader = new SAXReader();
//读入文件
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
Document read = saxReader.read(byteArrayInputStream);
//获得根节点
Element rootElement = read.getRootElement();
//获取根节点下所有子节点
List<Element> elements = rootElement.elements();
for (Element e:elements)
map.put(e.getName(),e.getStringValue());
System.out.println(map);
return "";
}
/**
* 进行sha1加密
* @param s
* @return
*/
private String sha1(String s) throws NoSuchAlgorithmException {
//获取一个加密对象
MessageDigest sha1 = MessageDigest.getInstance("sha1");
//加密
byte[] digest = sha1.digest(s.getBytes());
char[] chars = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
StringBuilder stringBuilder = new StringBuilder();
//处理加密结果
for (byte b:digest){
stringBuilder.append(chars[(b>>4)&15]);
stringBuilder.append(chars[b&15]);
}
return stringBuilder.toString();
}
}