使用SpringMVC搭建一个微信开发环境
直接从网络上下载一个demo修改开始学习,总结了下开发步骤
1、注册一个微信公众号
2、提供2个api接口,分别用户微信服务器验证公众号(get方法)和接收微信服务器转发消息用(post方法)
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public String wxInterface(HttpServletRequest request,HttpServletResponse response,WeChat wc) throws UnsupportedEncodingException{
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String signature = wc.getSignature();
String timestamp = wc.getTimestamp();
String nonce = wc.getNonce();
String echostr = wc.getEchostr();
if (SignUtil.checkSignature(signature, timestamp, nonce)) {
Log.info("是微信服务器发来的请求,请方心!");
return echostr;
} else {
Log.info("不是微信服务器发来的请求,请小心!");
return null;
}
}
@RequestMapping(method = RequestMethod.POST, produces = "application/xml;charset=UTF-8")
//@ResponseBody
public void getWeiXinMessage(HttpServletRequest request, HttpServletResponse response) throws Exception
{
Log.info("/api post 请求");
response.setCharacterEncoding("UTF-8");
//初始化配置文件
String respMessage = CoreService.processRequest(request);
// 响应消息
PrintWriter out = response.getWriter();
out.print(new String(respMessage.getBytes("GBK"), "GBK"));
out.flush();
out.close();
}
其中,get方法中checkSignature需要用到开发者自行给公众号设置的token值。
登录公众号平台,配置公账号服务器的地址、设置的token值、消息加密时用的加密密钥及消息加密方式等信息。设置后,如果启动成功,则最简单的微信开发框架就出来 了。
post方法的CoreService.processRequest(request)是对不同消息类型进行处理,如文本消息,语音消息,图片消息,推送消息以及事件等。
public static String processRequest(HttpServletRequest request) {
String respMessage = null;// 默认返回的文本消息内容
String respContent = "ERROR:请求处理异常,请稍候尝试!";
// xml请求解析
// 调用消息工具类MessageUtil解析微信发来的xml格式的消息,遍历所有节点内容,解析的结果放在HashMap里;
Map<String, String> requestMap = MessageUtil.parseXml(request);
// 从HashMap中取出消息中的字段;
// 发送方帐号(open_id)
String fromUserName = requestMap.get("FromUserName");
// 公众帐号
String toUserName = requestMap.get("ToUserName");
// 消息类型
String msgType = requestMap.get("MsgType");
// 消息内容
String content = requestMap.get("Content");
//根据不同的msgType做不同的响应处理
}
本文介绍如何使用SpringMVC快速搭建微信开发环境。主要包括注册微信公众号、配置API接口等步骤。通过GET方法验证服务器身份,POST方法接收并处理消息。
1153

被折叠的 条评论
为什么被折叠?



