基于springboot微信公众号开发(微信自动回复)
效果图
1.准备工作
申请微信订阅号(个人只能申请订阅号,而且没什么功能,也无法认证),申请完毕,点击开发=>基本配置,如下图:
服务器配置需要有域名80端口,我猜你没有,这里推荐个实用工具,pagekite,下载链接,
这个工具需要python2.7以上环境,还有邮箱一个,一个邮箱一个月,邮箱这东西大家懂得,
用pagekite申请完域名,就可以用自己的电脑做订阅号服务器了.
2.服务器代码
创建个springboot工程
pom.xml
UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-parent 1.5.9.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-thymeleaf net.sourceforge.nekohtml nekohtml 1.9.22 dom4j dom4j 1.6.1 org.springframework.boot spring-boot-maven-plugin
入口类
@SpringBootApplication publicclassWeChatApplication{ publicstaticvoidmain(String[]args){ SpringApplication.run(WeChatApplication.class,args); System.out.println("====启动成功===="); } }
application.properties,配置server.port=80
Controller,这个是处理微信请求,get方法就是微信公众平台服务器配置url请求的路径,post是处理用户事件
@RestController publicclassWeChatController{ @Autowired privateWeChatServiceweChatService; /** *处理微信服务器发来的get请求,进行签名的验证 * *signature微信端发来的签名 *timestamp微信端发来的时间戳 *nonce微信端发来的随机字符串 *echostr微信端发来的验证字符串 */ @GetMapping(value="wechat") publicStringvalidate(@RequestParam(value="signature")Stringsignature, @RequestParam(value="timestamp")Stringtimestamp, @RequestParam(value="nonce")Stringnonce, @RequestParam(value="echostr")Stringechostr){ returnWeChatUtil.checkSignature(signature,timestamp,nonce)?echostr:null; } /** *此处是处理微信服务器的消息转发的 */ @PostMapping(value="wechat") publicStringprocessMsg(HttpServletRequestrequest){ //调用核心服务类接收处理请求 returnweChatService.processRequest(request); } }
Service,处理post请求
/** *核心服务类 */ @Service publicclassWeChatServiceImplimplementsWeChatService{ @Autowired privateFeignUtilfeignUtil; @Autowired privateRedisUtilsredisUtils; publicStringprocessRequest(HttpServletRequestrequest){ //xml格式的消息数据 StringrespXml=null; //默认返回的文本消息内容 StringrespContent; try{ //调用parseXml方法解析请求消息 MaprequestMap=WeChatUtil.parseXml(request); //消息类型 StringmsgType=(String)requestMap.get(WeChatContant.MsgType); Stringmes=null; //文本消息 if(msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_TEXT)){ mes=requestMap.get(WeChatContant.Content).toString(); if(mes!=null&&mes.length()<2){ List items=newArrayList<>(); ArticleItemitem=newArticleItem(); item.setTitle("照片墙"); item.setDescription("阿狸照片墙"); item.setPicUrl("http://changhaiwx.pagekite.me/photo-wall/a/iali11.jpg"); item.setUrl("http://changhaiwx.pagekite.me/page/photowall"); items.add(item); item=newArticleItem(); item.setTitle("哈哈"); item.setDescription("一张照片"); item.setPicUrl("http://changhaiwx.pagekite.me/images/me.jpg"); item.setUrl("http://changhaiwx.pagekite.me/page/index"); items.add(item); item=newArticleItem(); item.setTitle("小游戏2048"); item.setDescription("小游戏2048"); item.setPicUrl("http://changhaiwx.pagekite.me/images/2048.jpg"); item.setUrl("http://changhaiwx.pagekite.me/page/game2048"); items.add(item); item=newArticleItem(); item.setTitle("百度"); item.setDescription("百度一下"); item.setPicUrl("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1505100912368&di=69c2ba796aa2afd9a4608e213bf695fb&imgtype=0&src=http%3A%2F%2Ftx.haiqq.com%2Fuploads%2Fallimg%2F170510%2F0634355517-9.jpg"); item.setUrl("http://www.baidu.com"); items.add(item); respXml=WeChatUtil.sendArticleMsg(requestMap,items); }elseif("我的信息".equals(mes)){ Map userInfo=getUserInfo(requestMap.get(WeChatContant.FromUserName)); System.out.println(userInfo.toString()); Stringnickname=userInfo.get("nickname"); Stringcity=userInfo.get("city"); Stringprovince=userInfo.get("province"); Stringcountry=userInfo.get("country"); Stringheadimgurl=userInfo.get("headimgurl"); List items=newArrayList<>(); ArticleItemitem=newArticleItem(); item.setTitle("你的信息"); item.setDescription("昵称:"+nickname+"地址:"+country+""+province+""+city); item.setPicUrl(headimgurl); item.setUrl("http://www.baidu.com"); items.add(item); respXml=WeChatUtil.sendArticleMsg(requestMap,items); } } //图片消息 elseif(msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_IMAGE)){ respContent="您发送的是图片消息!"; respXml=WeChatUtil.sendTextMsg(requestMap,respContent); } //语音消息 elseif(msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_VOICE)){ respContent="您发送的是语音消息!"; respXml=WeChatUtil.sendTextMsg(requestMap,respContent); } //视频消息 elseif(msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_VIDEO)){ respContent="您发送的是视频消息!"; respXml=WeChatUtil.sendTextMsg(requestMap,respContent); } //地理位置消息 elseif(msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_LOCATION)){ respContent="您发送的是地理位置消息!"; respXml=WeChatUtil.sendTextMsg(requestMap,respContent); } //链接消息 elseif(msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_LINK)){ respContent="您发送的是链接消息!"; respXml=WeChatUtil.sendTextMsg(requestMap,respContent); } //事件推送 elseif(msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_EVENT)){ //事件类型 StringeventType=(String)requestMap.get(WeChatContant.Event); //关注 if(eventType.equals(WeChatContant.EVENT_TYPE_SUBSCRIBE)){ respContent="谢谢您的关注!"; respXml=WeChatUtil.sendTextMsg(requestMap,respContent); } //取消关注 elseif(eventType.equals(WeChatContant.EVENT_TYPE_UNSUBSCRIBE)){ //TODO取消订阅后用户不会再收到公众账号发送的消息,因此不需要回复 } //扫描带参数二维码 elseif(eventType.equals(WeChatContant.EVENT_TYPE_SCAN)){ //TODO处理扫描带参数二维码事件 } //上报地理位置 elseif(eventType.equals(WeChatContant.EVENT_TYPE_LOCATION)){ //TODO处理上报地理位置事件 } //自定义菜单 elseif(eventType.equals(WeChatContant.EVENT_TYPE_CLICK)){ //TODO处理菜单点击事件 } } mes=mes==null?"不知道你在干嘛":mes; if(respXml==null) respXml=WeChatUtil.sendTextMsg(requestMap,mes); System.out.println(respXml); returnrespXml; }catch(Exceptione){ e.printStackTrace(); } return""; } }
微信工具类(只写了回复文本消息,和图文消息,其他的都是大同小异)
packagecom.wechat.util; importjava.io.InputStream; importjava.security.MessageDigest; importjava.security.NoSuchAlgorithmException; importjava.util.ArrayList; importjava.util.Date; importjava.util.HashMap; importjava.util.Iterator; importjava.util.List; importjava.util.Map; importjava.util.Set; importjavax.servlet.http.HttpServletRequest; importorg.dom4j.Document; importorg.dom4j.Element; importorg.dom4j.io.SAXReader; importcom.wechat.bean.ArticleItem; /** *请求校验工具类 * *@author32950745 * */ publicclassWeChatUtil{ /** *验证签名 * *@paramsignature *@paramtimestamp *@paramnonce *@return */ publicstaticbooleancheckSignature(Stringsignature,Stringtimestamp,Stringnonce){ String[]arr=newString[]{WeChatContant.TOKEN,timestamp,nonce}; //将token、timestamp、nonce三个参数进行字典序排序 //Arrays.sort(arr); sort(arr); StringBuildercontent=newStringBuilder(); for(inti=0;i>>4)&0X0F]; tempArr[1]=Digit[mByte&0X0F]; Strings=newString(tempArr); returns; } privatestaticvoidsort(Stringa[]){ for(inti=0;i parseXml(HttpServletRequestrequest)throwsException{ //将解析结果存储在HashMap中 Map map=newHashMap (); //从request中取得输入流 InputStreaminputStream=request.getInputStream(); //读取输入流 SAXReaderreader=newSAXReader(); Documentdocument=reader.read(inputStream); //得到xml根元素 Elementroot=document.getRootElement(); //得到根元素的所有子节点 List elementList=root.elements(); //遍历所有子节点 for(Elemente:elementList) map.put(e.getName(),e.getText()); //释放资源 inputStream.close(); inputStream=null; returnmap; } publicstaticStringmapToXML(Mapmap){ StringBuffersb=newStringBuffer(); sb.append(" "); mapToXML2(map,sb); sb.append(" "); try{ returnsb.toString(); }catch(Exceptione){ } returnnull; } privatestaticvoidmapToXML2(Mapmap,StringBuffersb){ Setset=map.keySet(); for(Iteratorit=set.iterator();it.hasNext();){ Stringkey=(String)it.next(); Objectvalue=map.get(key); if(null==value) value=""; if(value.getClass().getName().equals("java.util.ArrayList")){ ArrayListlist=(ArrayList)map.get(key); sb.append("<"+key+">"); for(inti=0;i"); }else{ if(valueinstanceofHashMap){ sb.append("<"+key+">"); mapToXML2((HashMap)value,sb); sb.append(""+key+">"); }else{ sb.append("<"+key+">"+key+">"); } } } } /** *回复文本消息 *@paramrequestMap *@paramcontent *@return */ publicstaticStringsendTextMsg(Map requestMap,Stringcontent){ Map map=newHashMap (); map.put("ToUserName",requestMap.get(WeChatContant.FromUserName)); map.put("FromUserName",requestMap.get(WeChatContant.ToUserName)); map.put("MsgType",WeChatContant.RESP_MESSAGE_TYPE_TEXT); map.put("CreateTime",newDate().getTime()); map.put("Content",content); returnmapToXML(map); } /** *回复图文消息 *@paramrequestMap *@paramitems *@return */ publicstaticStringsendArticleMsg(Map requestMap,List items){ if(items==null||items.size()<1){ return""; } Map map=newHashMap (); map.put("ToUserName",requestMap.get(WeChatContant.FromUserName)); map.put("FromUserName",requestMap.get(WeChatContant.ToUserName)); map.put("MsgType","news"); map.put("CreateTime",newDate().getTime()); List
微信常量
publicclassWeChatContant{ //APPID publicstaticfinalStringappID="appid"; //appsecret publicstaticfinalStringappsecret="appsecret"; //Token publicstaticfinalStringTOKEN="zch"; publicstaticfinalStringRESP_MESSAGE_TYPE_TEXT="text"; publicstaticfinalObjectREQ_MESSAGE_TYPE_TEXT="text"; publicstaticfinalObjectREQ_MESSAGE_TYPE_IMAGE="image"; publicstaticfinalObjectREQ_MESSAGE_TYPE_VOICE="voice"; publicstaticfinalObjectREQ_MESSAGE_TYPE_VIDEO="video"; publicstaticfinalObjectREQ_MESSAGE_TYPE_LOCATION="location"; publicstaticfinalObjectREQ_MESSAGE_TYPE_LINK="link"; publicstaticfinalObjectREQ_MESSAGE_TYPE_EVENT="event"; publicstaticfinalObjectEVENT_TYPE_SUBSCRIBE="SUBSCRIBE"; publicstaticfinalObjectEVENT_TYPE_UNSUBSCRIBE="UNSUBSCRIBE"; publicstaticfinalObjectEVENT_TYPE_SCAN="SCAN"; publicstaticfinalObjectEVENT_TYPE_LOCATION="LOCATION"; publicstaticfinalObjectEVENT_TYPE_CLICK="CLICK"; publicstaticfinalStringFromUserName="FromUserName"; publicstaticfinalStringToUserName="ToUserName"; publicstaticfinalStringMsgType="MsgType"; publicstaticfinalStringContent="Content"; publicstaticfinalStringEvent="Event"; }
图文消息实体bean
publicclassArticleItem{ privateStringTitle; privateStringDescription; privateStringPicUrl; privateStringUrl; publicStringgetTitle(){ returnTitle; } publicvoidsetTitle(Stringtitle){ Title=title; } publicStringgetDescription(){ returnDescription; } publicvoidsetDescription(Stringdescription){ Description=description; } publicStringgetPicUrl(){ returnPicUrl; } publicvoidsetPicUrl(StringpicUrl){ PicUrl=picUrl; } publicStringgetUrl(){ returnUrl; } publicvoidsetUrl(Stringurl){ Url=url; } }
好了运行项目,在公众平台配置好url,个人订阅号完成.
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。