一、配置測試號
登入測試號:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
配置測試號:
二、實現微信訪問服務器URL相關代碼
/**
* @program: zhq_weixin_parent
* @description: 微信公衆號回調地址
* @author: HQ Zheng
* @create: 2019-09-17 21:35
*/
@RestController
@Slf4j
public class WeChatServlet {
/**
* 微信驗籤
*
* @param signature
* @param timestamp
* @param nonce
* @param echostr
* @return
*/
@GetMapping("/weChatServlet")
public String getWeChatServlet(String signature, String timestamp, String nonce, String echostr) {
boolean checkSignature = CheckUtil.checkSignature(signature, timestamp, nonce);
if (!checkSignature) {
return null;
}
return echostr;
}
/**
* 解析微信消息 回覆消息
*
* @param request
* @param signature
* @param timestamp
* @param nonce
* @param echostr
* @return
* @throws Exception
*/
@PostMapping("/weChatServlet")
public String getWeChatServlet(HttpServletRequest request, HttpServletResponse response,
String signature, String timestamp, String nonce, String echostr)
throws Exception {
Map<String, String> result = XmlUtils.parseXml(request);
String toUserName = result.get("ToUserName");
String fromUserName = result.get("FromUserName");
String createTime = result.get("CreateTime");
String msgType = result.get("MsgType");
String content = result.get("Content");
String msgId = result.get("MsgId");
switch (msgType) {
case "text":
String resultXml = null;
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
if (content.equals("微信消息測試")) {
TextMessage textMessage = new TextMessage();
textMessage.setToUserName(fromUserName);
textMessage.setFromUserName(toUserName);
textMessage.setCreateTime(System.currentTimeMillis());
textMessage.setContent("微信消息測試回覆");
textMessage.setMsgType("text");
resultXml = XmlUtils.messageToXml(textMessage);
out.print(resultXml);
out.close();
}
break;
default:
break;
}
return echostr;
}
三、測試代碼