1.验证用户消息
@RequestMapping(value = "/verifier",method = {RequestMethod.POST})
public void processPost(HttpServletRequest request, HttpServletResponse response) throws Exception{
PrintWriter out=response.getWriter();
Map<String, String> msgMap = WechatUtils.xmlToMap(request);
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
/**接收消息*/
if (StringUtils.equals("text",msgMap.get("MsgType")) && StringUtils.equals(StringUtils.trim(msgMap.get("Content")),"消息内容")){
String xml = pushBindingInfo(msgMap);
out.println(xml);
}
}
处理推送给用户的消息,转为xml,我这里推送的是一个链接,用户点击消息可以跳转到自定义的页面;
public String pushBindingInfo(Map<String, String> msgMap){
TextMessage textMessage = new TextMessage();
textMessage.setToUserName(msgMap.get("FromUserName"));
textMessage.setFromUserName(msgMap.get("ToUserName"));
textMessage.setCreateTime(msgMap.get("CreateTime"));
textMessage.setMsgType("text");
String appId = "APPID";
String url = "链接";
textMessage.setContent("<a href="+url+">推送的消息</a>");
XStream xstream = new XStream();
xstream.alias("xml", textMessage.getClass());
String xml = xstream.toXML(textMessage);
return xml;
}
2.网页授权获取用户基本信息
微信公众号配置:
/**
*获取关注公众号用户的openId
*/
public String getWxUserOpenId(HttpServletRequest request){
String appId = sysParamService.getValue(Constants.WX_APPID);
String appsecret = sysParamService.getValue(Constants.WX_APPSECRET);
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId+"&secret="+appsecret+"&code=CODE&grant_type=authorization_code";
String code = request.getParameter("code");
if (StringUtils.isNotBlank(code)){
String urlRe = StringUtils.replace(url, "CODE", code);
String info = WechatUtils.get(urlRe);
JSONObject jsonObject = JSONObject.fromObject(info);
Object openid = jsonObject.get("openid");
if (null != openid){
String openId = openid.toString();
return openId;
}
}
return StringUtils.EMPTY;
}