dl_admin/ruoyi-admin/src/main/java/com/ruoyi/api/WxMsgApi.java
2025-04-28 15:02:09 +08:00

63 lines
2.1 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.ruoyi.api;
import com.ruoyi.api.domain.WeChatMessage;
import com.ruoyi.api.service.IWeChatMessageService;
import com.ruoyi.busi.utils.WeChatUtils;
import com.ruoyi.common.annotation.Anonymous;
import com.wechat.pay.java.core.http.HttpMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@RestController
@RequestMapping("/wxMsgApi")
public class WxMsgApi {
@Autowired
private WeChatUtils weChatUtils;
@Resource
private IWeChatMessageService weChatMessageService;
/**
* 校验签名
*
* @param message {@link WeChatMessage}
* @param request {@link HttpServletRequest}
* @return java.lang.Object
* @author PQZ
* @date 12:17 2025/4/25
**/
@RequestMapping("/message")
@Anonymous
public void register(WeChatMessage message, HttpServletRequest request, HttpServletResponse response) throws IOException {
String method = request.getMethod();
if (HttpMethod.GET.name().equalsIgnoreCase(method)) {
String echostr = weChatMessageService.checkSignature(message);
response.getOutputStream().write(echostr.getBytes());
} else if (HttpMethod.POST.name().equalsIgnoreCase(method)) {
// 进入POST聊天处理
// 将请求、响应的编码均设置为UTF-8防止中文乱码
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
// 接收消息并返回消息
String result = weChatMessageService.acceptMessage(request, response);
// 响应消息
PrintWriter out = response.getWriter();
out.print(result);
out.close();
}
}
}