- 注册微信公众号
- 打开消息推送等权限
- 在基本配置中填写相应信息
![在这里插入图片描述](https://img-blog.csdnimg.cn/da35d07137504d929520baac6814acae.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA6Zuq6aOO6aOe6Iie,size_20,color_FFFFFF,t_70,g_se,x_16)
- Java代码
添加xml解析依赖
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
package cn.web.demo.controller;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;
@RequestMapping("wx")
public class WxController {
@GetMapping("accept")
public String getAccept(String signature,String timestamp,String nonce,String echostr){
String token="adsfasdafsd";
String[] arr={token,timestamp,nonce};
Arrays.sort(arr);
StringBuilder stringBuilder=new StringBuilder();
for (String s : arr) {
stringBuilder.append(s);
}
if (shaEncode(stringBuilder.toString()).equals(signature)){
return echostr;
}else {
return "校验失败";
}
}
private String shaEncode(String inStr) {
MessageDigest sha = null;
try {
sha = MessageDigest.getInstance("SHA");
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
return "";
}
byte[] byteArray = inStr.getBytes(StandardCharsets.UTF_8);
byte[] md5Bytes = sha.digest(byteArray);
StringBuilder hexValue = new StringBuilder();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
@PostMapping("accept")
public String postAccept(HttpServletRequest request) throws IOException {
ServletInputStream inputStream = request.getInputStream();
Map<String, String> map = xmlInputStreamToMap(inputStream);
return "";
}
private static Map<String, String> xmlInputStreamToMap(InputStream inputStream) {
if (inputStream == null) return Collections.emptyMap();
Map<String, String> map = new HashMap<>();
try {
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
Element root = document.getRootElement();
List<Element> elementList = root.elements();
for (Element e : elementList) {
map.put(e.getName(), e.getText());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return map;
}
}