|
@@ -1,27 +1,43 @@
|
|
|
package top.husj.husj_wx.controller;
|
|
package top.husj.husj_wx.controller;
|
|
|
|
|
|
|
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
import org.springframework.http.MediaType;
|
|
import org.springframework.http.MediaType;
|
|
|
import org.springframework.web.bind.annotation.*;
|
|
import org.springframework.web.bind.annotation.*;
|
|
|
import top.husj.husj_wx.entity.model.WeChatMsg;
|
|
import top.husj.husj_wx.entity.model.WeChatMsg;
|
|
|
|
|
+import top.husj.husj_wx.utils.WeChatSignatureUtil;
|
|
|
|
|
|
|
|
@RestController
|
|
@RestController
|
|
|
@RequestMapping("/wechat")
|
|
@RequestMapping("/wechat")
|
|
|
|
|
+@Slf4j
|
|
|
public class WeChatController {
|
|
public class WeChatController {
|
|
|
|
|
|
|
|
private final String TOKEN = "你设置的Token";
|
|
private final String TOKEN = "你设置的Token";
|
|
|
|
|
|
|
|
// 1. 微信后台验证 URL 时使用 (GET)
|
|
// 1. 微信后台验证 URL 时使用 (GET)
|
|
|
@GetMapping("/callback")
|
|
@GetMapping("/callback")
|
|
|
- public String checkSignature(String signature, String timestamp, String nonce, String echostr) {
|
|
|
|
|
- // 这里需要按照微信算法:将token、timestamp、nonce字典排序并SHA1加密,对比signature
|
|
|
|
|
- // 为了演示快速上手,这里直接返回 echostr(正式环境必须校验!)
|
|
|
|
|
- return echostr;
|
|
|
|
|
|
|
+ public String checkSignature(
|
|
|
|
|
+ @RequestParam("signature") String signature,
|
|
|
|
|
+ @RequestParam("timestamp") String timestamp,
|
|
|
|
|
+ @RequestParam("nonce") String nonce,
|
|
|
|
|
+ @RequestParam("echostr") String echostr) {
|
|
|
|
|
+
|
|
|
|
|
+ log.info("收到微信服务器验证请求 - signature: {}, timestamp: {}, nonce: {}",
|
|
|
|
|
+ signature, timestamp, nonce);
|
|
|
|
|
+
|
|
|
|
|
+ // 校验签名
|
|
|
|
|
+ if (WeChatSignatureUtil.checkSignature(signature, timestamp, nonce)) {
|
|
|
|
|
+ log.info("微信服务器验证成功");
|
|
|
|
|
+ return "true";
|
|
|
|
|
+ } else {
|
|
|
|
|
+ log.error("微信服务器验证失败 - 签名不匹配");
|
|
|
|
|
+ return "error";
|
|
|
|
|
+ }
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
// 2. 接收用户消息 (POST)
|
|
// 2. 接收用户消息 (POST)
|
|
|
@PostMapping(value = "/callback", consumes = MediaType.TEXT_XML_VALUE, produces = MediaType.TEXT_XML_VALUE)
|
|
@PostMapping(value = "/callback", consumes = MediaType.TEXT_XML_VALUE, produces = MediaType.TEXT_XML_VALUE)
|
|
|
public String handleMessage(@RequestBody WeChatMsg msg) {
|
|
public String handleMessage(@RequestBody WeChatMsg msg) {
|
|
|
- System.out.println("收到来自用户 " + msg.getFromUserName() + " 的消息:" + msg.getContent());
|
|
|
|
|
|
|
+ log.info("收到来自用户 {} 的消息:{}", msg.getFromUserName(), msg.getContent());
|
|
|
|
|
|
|
|
// 构造被动回复(同样是XML)
|
|
// 构造被动回复(同样是XML)
|
|
|
return String.format(
|
|
return String.format(
|