微信小程序> 微信服务通知,小程序服务消息通知集成

微信服务通知,小程序服务消息通知集成

浏览量:704 时间: 来源:pianpiannia
微信接口文档:调用微信服务消息的请求接口为:还有一个地址为微信公众号的消息推送接口:这里用服务消息的接口而不是公众号消息推送的接口,公众号接口需要付费开通权限关于服务推送form_id问题:
form_id有时效性,网上有说7天,但文档中没有维护。form_id用过一次就失效。form_id要真机提供才有效1.模板实体类
publicclassTemplateData{privateStringvalue;//color在服务消息通知中废弃,但在公众号消息通知仍存在privateStringcolor;publicTemplateData(Stringvalue,Stringcolor){this.value=value;this.color=color;}//getset省略}publicclassTemplateMessage{/接收者openid/privateStringtouser;/所需下发的模板消息的id/privateStringtemplateId;/小程序要跳转的页面url/privateStringpage;/表单提交场景下,为submit事件带上的formId;支付场景下,为本次支付的prepay_id/privateStringformId;/模板数据/privateMapString,TemplateDatadata;/模板需要放大的关键词,不填则默认无放大/privateStringemphasiseyword;//getset省略}2.获取token
publicclassAccessTokenRequestHandlerextendsRequestHandler{publicAccessTokenRequestHandler(HttpServletRequestrequest,HttpServletResponseresponse){super(request,response);}privatestaticStringaccess_token="";/获取小程序凭证access_token@return/publicstaticStringgetMinAccessToken(){if("".equals(access_token)){//如果为空直接获取returngetMinTokenReal();}if(tokenIsExpire(access_token)){//如果过期重新获取returngetMinTokenReal();}returnaccess_token;}/实际获取小程序access_token的方法@return/protectedstaticStringgetMinTokenReal(){//获取token所需参数url,grant_type,appid,appsecret用自己的StringrequestUrl=TOKENURL+"?grant_type="+GRANT_TYPE+"&appid="+APPID+"&secret="+APPSECRET;StringresContent="";TenpayHttpClienthttpClient=newTenpayHttpClient();httpClient.setMethod("GET");httpClient.setReqContent(requestUrl);if(httpClient.call()){resContent=httpClient.getResContent();if(resContent.indexOf(ConstantUtil.ACCESS_TOKEN)0){access_token=JsonUtil.getJsonValue(resContent,ConstantUtil.ACCESS_TOKEN);}else{System.out.println("获取access_token值返回错误!!!");}}else{System.out.println("后台调用通信失败");System.out.println(httpClient.getResponseCode());System.out.println(httpClient.getErrInfo());//有可能因为网络原因,请求已经处理,但未收到应答。}returnaccess_token;}}3.发起https请求并获取结果
publicclassWeixinUtil{privatestaticLoggerlog=LoggerFactory.getLogger(WeixinUtil.class);/发起https请求并获取结果@paramrequestUrl请求地址@paramrequestMethod请求方式(GET、POST)@paramoutputStr提交的数据@returnJSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)/publicstaticStringhttpRequest(StringrequestUrl,StringrequestMethod,StringoutputStr){StringBufferbuffer=newStringBuffer();try{//创建SSLContext对象,并使用我们指定的信任管理器初始化TrustManager[]tm={newMyX509TrustManager()};SSLContextsslContext=SSLContext.getInstance("SSL","SunJSSE");sslContext.init(null,tm,newjava.security.SecureRandom());//从上述SSLContext对象中得到SSLSocketFactory对象SSLSocketFactoryssf=sslContext.getSocketFactory();URLurl=newURL(requestUrl);HttpsURLConnectionhttpUrlConn=(HttpsURLConnection)url.openConnection();httpUrlConn.setSSLSocketFactory(ssf);httpUrlConn.setDoOutput(true);httpUrlConn.setDoInput(true);httpUrlConn.setUseCaches(false);//设置请求方式(GET/POST)httpUrlConn.setRequestMethod(requestMethod);if("GET".equalsIgnoreCase(requestMethod))httpUrlConn.connect();//当有数据需要提交时if(null!=outputStr){OutputStreamoutputStream=httpUrlConn.getOutputStream();//注意编码格式,防止中文乱码outputStream.write(outputStr.getBytes("UTF-8"));outputStream.close();}//将返回的输入流转换成字符串InputStreaminputStream=httpUrlConn.getInputStream();InputStreamReaderinputStreamReader=newInputStreamReader(inputStream,"utf-8");BufferedReaderbufferedReader=newBufferedReader(inputStreamReader);Stringstr=null;while((str=bufferedReader.readLine())!=null){buffer.append(str);}bufferedReader.close();inputStreamReader.close();//释放资源inputStream.close();inputStream=null;httpUrlConn.disconnect();}catch(ConnectExceptionce){log.error("Weixinserverconnectiontimedout.");}catch(Exceptione){log.error("httpsrequesterror:{}",e);}returnbuffer.toString();}}4.发送
publicclassWXMsgRun{publicstaticTemplateMessageTemplateMessage(Stringopinid,Stringpagepath,StringformId,MapString,TemplateDatadata,Stringemphasiseyword){TemplateMessagetemplateMessage=newTemplateMessage();templateMessage.setTouser(opinid);templateMessage.setPagepath(pagepath);templateMessage.setFormId(formId);templateMessage.setData(data);templateMessage.setEmphasiseyword(emphasiseyword);returntemplateMessage;}//publicstaticvoidsendOrderPayMessage(String...相关模板字段的值自己配){MapString,TemplateDatadata=newHashMapString,TemplateData();data.put("keyword1",newTemplateData(xxxxx,null));data.put("keyword2",newTemplateData(yyyyy,null));sendMessage(opinid,page,data,formId,null);}/@paramopinid被推送用户的openid@parampage消息推送后小程序跳转的页面路径@paramdata封装的主体数据@paramformId小程序提交的表单id@paramemphasiseyword需要强调的关键字段格式为"keyword1.DATA"/publicstaticvoidsendMessage(Stringopinid,Stringpage,MapString,TemplateDatadata,StringformId,Stringemphasiseyword){sendWechatMsgToUser(opinid,page,formId,data,emphasiseyword);}privatestaticvoidsendWechatMsgToUser(TemplateMessagetemplateMessage){WXSendMsgJobjob=newWXSendMsgJob(TemplateMessage);//我的方法用线程处理,也可不用,只是个demoThreadPoolManager.getInstance().addExecuteTask(job);}}publicclassWXMessageUtil{privatestaticLoggerlog=LoggerFactory.getLogger(WXMessageUtil.class);publicstaticJSONObjectdataJsonmsg(MapString,TemplateDatadata){JSONObjectjson=newJSONObject();for(Map.EntryString,TemplateDataentry:data.entrySet()){JSONObjectkeyJson=newJSONObject();TemplateDatadta=entry.getValue();keyJson.put("value",dta.getValue());keyJson.put("color",dta.getColor());json.put(entry.getKey(),keyJson);}returnjson;}/发送微信消息(模板消息)@paramtouser用户OpenID@paramtemplatId模板消息ID@return/publicstaticJSONObjectsendWechatMsgToUser(Stringtouser,StringtemplatId,Stringpage,StringformId,MapString,TemplateDatadata,Stringemphasiseyword){//Stringurl="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="//+AccessTokenRequestHandler.getAccessToken();Stringurl="https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+AccessTokenRequestHandler.getMinAccessToken();JSONObjectjson=newJSONObject();JSONObjectjsonDataMsg=dataJsonmsg(data);json.put("touser",touser);json.put("template_id",templatId);json.put("page",page);json.put("form_id",formId);json.put("data",jsonDataMsg);json.put("emphasis_keyword",emphasiseyword);System.out.println("post数据包"+json.toString());JSONObjectparseObject=null;try{StringrequestMethod="POST";Stringresult=WeixinUtil.httpRequest(url,requestMethod,json.toString());parseObject=JSON.parseObject(result);log.info("发送微信消息返回信息:"+parseObject);log.info("发送微信消息返回信息编码:"+parseObject.get("errcode"));Stringerrmsg=(String)parseObject.get("errmsg");log.info("获取模板编号返回信息:"+errmsg);if(!"ok".equals(errmsg)){//如果为errmsg为ok,则代表发送成功log.info("失败信息"+parseObject.toJSONString());//失败处理}}catch(Exceptione){e.printStackTrace();}returnparseObject;}}

版权声明

即速应用倡导尊重与保护知识产权。如发现本站文章存在版权问题,烦请提供版权疑问、身份证明、版权证明、联系方式等发邮件至197452366@qq.com ,我们将及时处理。本站文章仅作分享交流用途,作者观点不等同于即速应用观点。用户与作者的任何交易与本站无关,请知悉。

产品经理

手机 : 13312967497

擅长 : 小程序流量变现

扫码领取礼包

热门模板

  • 头条
  • 搜狐
  • 微博
  • 百家
  • 一点资讯
  • 知乎