com.github.hippoom.wechat.mp.web.WeChatMpInboundMessageController Maven / Gradle / Ivy
package com.github.hippoom.wechat.mp.web;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import javax.servlet.http.HttpServletRequest;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* Controller to handle WeChat inbound messages.
*
* @see WxMpMessageRouter
*/
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/wechat/mp/webhooks/messaging")
public class WeChatMpInboundMessageController {
@NonNull
private final WxMpService wxMpService;
@NonNull
private final WxMpMessageRouter wxMpMessageRouter;
/**
* Handle authentication request from WeChat.
*
* @param signature given by WeChat MP webhook
* @param echostr given by WeChat MP webhook
* @param timestamp given by WeChat MP webhook
* @param nonce given by WeChat MP webhook
* @param request {@link HttpServletRequest}
* @return echostr if authenticated, "invalid authentication request" if failure
* @see Message
* Authentication
*/
@RequestMapping(method = GET)
protected String handleAuthentication(@RequestParam String signature,
@RequestParam String echostr,
@RequestParam String timestamp,
@RequestParam String nonce, HttpServletRequest request) {
log.debug("receiving {}", request.getParameterMap());
// see http://admin.wechat.com/wiki/index.php?title=Message_Authentication
return wxMpService.checkSignature(timestamp, nonce, signature) ? echostr
: "invalid authentication request";
}
/**
* Handle inbound messages from WeChat.
*
* @param message the payload of inbound message
* @return {@link WxMpXmlOutMessage}
* @see Common
* Messages
* @see Event Based
* Messages
*/
@RequestMapping(method = POST)
protected String handleInboundMessage(@RequestBody String message) {
log.debug("receiving {}", message);
WxMpXmlOutMessage outboundMessage = wxMpMessageRouter
.route(WxMpXmlMessage.fromXml(message));
return outboundMessage == null ? null : outboundMessage.toXml();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy