服务器地址配置
服务器可以使用内网穿透(教程在上一篇文章)或者买一个
接入
https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html
package com.example.springboot.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Comparator;
@RestController
public class WeChatController {
private static final String TOKEN = "配置的TOKEN
@GetMapping("/")
public String weixin(HttpServletRequest request,
@RequestParam(name = "signature", required = false) String signature,
@RequestParam(name = "timestamp", required = false) String timestamp,
@RequestParam(name = "nonce", required = false) String nonce,
@RequestParam(name = "echostr", required = false) String echostr) {
try {
// 将token, timestamp, nonce按字典序排序
String[] arr = {TOKEN, timestamp, nonce};
Arrays.sort(arr);
// 将排序后的字符串拼接成一个字符串
String content = String.join("", arr);
// 使用SHA-1算法进行加密
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] digest = md.digest(content.getBytes());
// 转换为十六进制字符串
String hexString = bytesToHex(digest);
if (hexString.equals(signature)){
return echostr;
}else {
return "error";
}
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SHA-1 algorithm not found", e);
}
}
private String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
// 其他处理消息的方法
}