java公众号基本配置获取openId
需求是获取用户的openId和手机号,因为公众号没有提供方法获取用户手机号,所以是让用户输入
1.登录微信公众号官网 微信公众平台 (qq.com),配置基本配置
配置也就这么多,接下来是代码
第一次会调get请求,
@RequestMapping(value="/publicBackUrl",method={RequestMethod.GET})
public void doGet(HttpServletRequest request,HttpServletResponse response) {
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");//直接返回这个参数即可,是验证token的
try {
response.getWriter().print(echostr);
} catch (IOException e) {
e.printStackTrace();
}
}
用户关注公众号或者发送消息给公众号都会调用post接口,微信推送到我们服务器的参数都有openId=FromUserName
@RequestMapping(value="/publicBackUrl",method={RequestMethod.POST})
public void doPost(HttpServletRequest request,HttpServletResponse response){
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e1) {
logger.error("进来followBackUrl异常1=="+e1.getMessage(),e1);
e1.printStackTrace();
}
//解决乱码
response.setContentType("text/html; charset=utf-8");
String resultString="哈哈哈哈";
try {
TextMessageResp tResp=new TextMessageResp();
Map<String, String> resultMap = MessageUtil.parseXml(request);
//resultMap ={CreateTime=1630469013, EventKey=, Event=subscribe, ToUserName=ht_f152c9d859c, FromUserName=oyXJK5j57yuho2GZU81giutS8600, MsgType=event}
//判断是否关注
if(MessageUtil.EVENT_TYPE_SUBSCRIBE.equals(resultMap.get("Event"))){
resultString="欢迎关注xxx公众号,点击<a href='https://域名:端口/wechatPublic/bindMoblie.html?fromUserName="+resultMap.get("FromUserName")+"'>绑定手机号</a>";
}
tResp.setContent(resultString);
tResp.setCreateTime(System.currentTimeMillis());
tResp.setFromUserName(resultMap.get("ToUserName"));
tResp.setToUserName(resultMap.get("FromUserName"));
tResp.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
//回复用户信息
//xml格式
/**
<xml>
<ToUserName><![CDATA[2222222]]></ToUserName>
<FromUserName><![CDATA[333333]]></FromUserName>
<CreateTime><![CDATA[1630561924933]]></CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[哈哈哈哈]]></Content>
</xml>*/
String resposeString=MessageUtil.textMessageToXml(tResp);
response.getWriter().write(resposeString);
} catch (Exception e) {
e.printStackTrace();
}
}