实现如下效果
首先,java端提供两个接口,一个get,一个post
/*
* @param signature 微信加密签名,signature结合了开发者填写的 token 参数和请求中的 timestamp 参数、nonce参数。
* @param timestamp 时间戳
* @param nonce 这是个随机数
* @param echostr 随机字符串,验证成功后原样返回
*/
@GetMapping("/wx/event")
public void get(@RequestParam(required = false) String signature,
@RequestParam(required = false) String timestamp,
@RequestParam(required = false) String nonce,
@RequestParam(required = false) String echostr,
HttpServletResponse response) throws IOException {
System.out.println("接受事件===" + echostr);
response.setCharacterEncoding("UTF-8");
response.getWriter().write(echostr);
response.getWriter().flush();
response.getWriter().close();
}
//处理微信推送事件
@PostMapping("/wx/event")
public void post(final HttpServletRequest request, HttpServletResponse response) {
System.out.println("接受事件");
try {
// 微信加密签名
final String signature = request.getParameter("signature");
// 时间戳
final String timestamp = request.getParameter("timestamp");
// 随机数
final String nonce = request.getParameter("nonce");
// 随机字符串
final String echostr = request.getParameter("echostr");
//将xml文件转成易处理的map(下方贴出)
final Map<String, String> map = oConvertUtils.parseXml(request);
//开发者微信号
final String toUserName = map.get("ToUserName");
//OpenId
final String fromUserName = map.get("FromUserName");
//消息创建时间 (整型)
final String createTime = map.get("CreateTime");
//消息类型,event
final String msgType = map.get("MsgType");
//事件类型
final String event = map.get("Event");
String msg = "";
if ("event".equals(msgType)) {
if (event.equals("subscribe")) {
msg = getXmlReturnMsg(fromUserName, toUserName, (new Date()).getTime(), "欢迎您使用量子文档");
}
//注:事件类型为SCAN即已关注
else if (event.equals("SCAN")) {
msg = getXmlReturnMsg(fromUserName, toUserName, (new Date()).getTime(), "您刚刚扫码登录了量子文档");
}
}
System.out.println("打印消息体=========");
System.out.println(msg);
System.out.println("=========");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.print(msg);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 构建普通消息
* @param toUser 接收方账号(openId)
* @param fromUser 开发者账号
* @param createTime 创建时间,整型
* @param content 内容
* @return 回复消息
*/
private String getXmlReturnMsg(String toUser,String fromUser,Long createTime,String content) {
return "<xml>\n" +
" <ToUserName><![CDATA["+toUser+"]]></ToUserName>\n" +
" <FromUserName><![CDATA["+fromUser+"]]></FromUserName>\n" +
" <CreateTime>"+createTime+"</CreateTime>\n" +
" <MsgType><![CDATA[text]]></MsgType>\n" +
" <Content><![CDATA["+content+"]]></Content>\n" +
"</xml>";
}
微信平台进行设置