再一次接入微信开放平台,只是此次以消息为主,不涉及支付,如需看微信支付,请参考另一篇博文。
此篇博文涉及了微信公众号开发的基础功能部分,包括了服务器校验、获取access_token 、创建自定义菜单,接收微信公众平台的消息,并回复消息,主动推送模版消息等,在此基础上,可以按需回复或者推送各类消息。代码注释比较全,所以直接上代码:
首先是controller(实际应用中很多功能入口不是controller,此处是做测试而已),其中/wechat/index的get方法是做服务器验证,post方法是接收微信服务器发送过来的消息
package com.dnkx.controller.wechat;
import com.dnkx.bo.WeChatTextMessageBO;
import com.dnkx.util.WechatUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;
/**
* Created by 李小拐 on 2017/4/18.
*/
@Controller
@RequestMapping("/wechat")
public class WeChatController {
private final static Logger logger= LoggerFactory.getLogger(WeChatController.class);
@Resource
private HttpServletRequest request;
@Value("${appId}")
private String appId;
@Value("${appSecret}")
private String appSecret;
/**
* 服务器签名验证
*/
@ResponseBody
@RequestMapping(value = "/index",method = RequestMethod.GET)
public String checkSignature(){
try {
// 接收微信服务器以Get请求发送的4个参数
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echoStr = request.getParameter("echostr");
if (WechatUtil.checkSignature(signature,timestamp,nonce)){
logger.info("echoStr:{}",echoStr);
return echoStr;
}
}catch (Exception e){
logger.error(e.getMessage(),e);
}
return "";
}
/**
* 接收微信消息
*/
@ResponseBody
@RequestMapping(value = "/index",method = RequestMethod.POST,produces = "text/xml; charset=utf-8")
public String receiveMessage(){
String message = null;
try {
request.setCharacterEncoding("utf-8");
Map<String, String> map = WechatUtil.xmlToMap(request.getInputStream());
String toUserName = map.get("ToUserName");//微信公众号
String fromUserName = map.get("FromUserName");//openid
String msgType = map.get("MsgType");//接收到消息类型
String MsgId = map.get("MsgId");//消息id,64位整型
//消息类型:text(文本消息)、image(图片消息)、voice(语音)、
// video(视频)、shortvideo(小视频)、location(位置信息)、link(链接)、event(事件)
switch (msgType){
case "text":
//接收到的消息内容(文本消息特有字段)
String content = map.get("Content");
break;
case "event":
//事件类型:subscribe(关注)、unsubscribe(取消关注)、SCAN(扫描)、LOCATION(上报位置)、
// CLICK(点击自定义菜单拉取消息)、VIEW(点击自定义菜单跳转链接)
String event = map.get("Event");