微信小程序> 微信通知,微信小程序服务通知

微信通知,微信小程序服务通知

浏览量:999 时间: 来源:Qinejie1314520
前言实现效果
实现必要一个微信小程序,去微信申请就可以,测试号也是可以的小程序里面去申请一个模板消息代码实现下面代码没有问题,这是我项目当中截取的部分。下面代码是我项目中直接复制过来的。仅供参考。具体实现代码在最底下
importcom.alibaba.fastjson.JSON;importcom.example.community.app.user.common.HttpClient;importcom.example.community.app.user.common.TemplateData;importcom.example.community.common.redis.RedisService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.stereotype.Component;importjava.util.HashMap;importjava.util.List;importjava.util.Map;@ComponentpublicclassMessagePush{@AutowiredRedisServiceredisService;@Value("${customer.app.secret}")privateStringAppSecret;@Value("${customer.app.id}")privateStringAppId;@Value("${official.app.secret}")privateStringOfficialAppSecret;@Value("${official.app.id}")privateStringOfficialAppId;@Value("${service.template.message.order.payment.successful}")privateStringServicePushOrderPayMentSuccess;@Value("${service.template.message.order.cancellation}")privateStringServicePushOrderCancellation;@Value("${service.template.message.order.deliver}")privateStringServicePushOrderDeliver;@Value("${official.template.message.order.payment.successful}")privateStringOfficialPushOrderPayMentSuccess;@Value("${wx.getAccessToken}")privateStringAccessTokenUrl;@Value("${wx.service.template.message.send}")privateStringServiceTemplateMessageSendUrl;publicObjectgetServiceAccessToken(){Objectacc=redisService.get("service_push_access_token");if(acc==null){Stringres=HttpClient.doGet(AccessTokenUrl+"?grant_type=client_credential&appid="+AppId+"&secret="+AppSecret);MapmapType=JSON.parseObject(res,Map.class);redisService.set("service_push_access_token",mapType.get("access_token"),7150L);returnmapType.get("access_token");}returnacc;}//小程序服务通知publicStringpushServiceMessage(Integertype,Stringtouser,Stringform_id,ListStringkeywords){MapString,Objectmap=newHashMap();map.put("touser",touser);switch(type){case1:map.put("template_id",ServicePushOrderPayMentSuccess);break;//支付成功case2:map.put("template_id",ServicePushOrderCancellation);break;//取消订单case3:map.put("template_id",ServicePushOrderDeliver);break;//发货通知default:map.put("template_id",ServicePushOrderPayMentSuccess);break;}map.put("form_id",form_id);MapString,Objectmap1=newHashMap();for(inti=0;ikeywords.size();i++){map1.put("keyword"+(i+1),newTemplateData(keywords.get(i),null));}map.put("data",map1);returnHttpClient.doPost(ServiceTemplateMessageSendUrl+"?access_token="+getServiceAccessToken(),map);}}具体实现代码,裁剪后的代码。下面的代码可以直接复制然后运行即可,缺少的包导入进去
importcom.alibaba.fastjson.JSON;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.stereotype.Component;importjava.util.HashMap;importjava.util.List;importjava.util.Map;publicclassMessagePush{privateStringAppSecret=“小程序密匙,在小程序管理页面可以找到”;privateStringAppId=“小程序appip,在小程序管理页面可以找到”;privateStringServicePushOrderPayMentSuccess="t1ictRv_Hv7-ww6TM_7BheLu02UUl_SurJxPHc09YEg";//订单支付成功的模板的idprivateStringAccessTokenUrl=“https://api.weixin.qq.com/cgi-bin/token”;//获取小程序后台鉴权接口,可以不变privateStringServiceTemplateMessageSendUrl=“https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send”;//发送模板消息调用的接口publicObjectgetServiceAccessToken(){Stringres=HttpClient.doGet(AccessTokenUrl+"?grant_type=client_credential&appid="+AppId+"&secret="+AppSecret);MapmapType=JSON.parseObject(res,Map.class);returnmapType.get("access_token");returnacc;}//小程序服务通知//表单提交场景下,为submit事件带上的formId;支付场景下,为本次支付的prepay_id,这些对应就是form_id//touser微信对象的openid//keywords对应模板消息的各个参数的值publicStringpushServiceMessage(Integertype,Stringtouser,Stringform_id,ListStringkeywords){MapString,Objectmap=newHashMap();map.put("touser",touser);switch(type){case1:map.put("template_id",ServicePushOrderPayMentSuccess);break;//支付成功default:map.put("template_id",ServicePushOrderPayMentSuccess);break;}map.put("form_id",form_id);MapString,Objectmap1=newHashMap();for(inti=0;ikeywords.size();i++){map1.put("keyword"+(i+1),newTemplateData(keywords.get(i),null));}map.put("data",map1);returnHttpClient.doPost(ServiceTemplateMessageSendUrl+"?access_token="+getServiceAccessToken(),map);}}发送http请求的工具类
packagecom.example.community.app.user.common;importcom.alibaba.fastjson.JSONObject;importorg.apache.http.HttpEntity;importorg.apache.http.client.ClientProtocolException;importorg.apache.http.client.config.RequestConfig;importorg.apache.http.client.methods.CloseableHttpResponse;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.entity.StringEntity;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClients;importorg.apache.http.util.EntityUtils;importjava.io.IOException;importjava.util.Map;publicclassHttpClient{publicstaticStringdoGet(Stringurl){CloseableHttpClienthttpClient=null;CloseableHttpResponseresponse=null;Stringresult="";try{//通过址默认配置创建一个httpClient实例httpClient=HttpClients.createDefault();//创建httpGet远程连接实例HttpGethttpGet=newHttpGet(url);////设置请求头信息,鉴权//httpGet.setHeader("Authorization","Bearerda3efcbf-0845-4fe3-8aba-ee040be542c0");//设置配置请求参数RequestConfigrequestConfig=RequestConfig.custom().setConnectTimeout(35000)//连接主机服务超时时间.setConnectionRequestTimeout(35000)//请求超时时间.setSocketTimeout(60000)//数据读取超时时间.build();//为httpGet实例设置配置httpGet.setConfig(requestConfig);//执行get请求得到返回对象response=httpClient.execute(httpGet);//通过返回对象获取返回数据HttpEntityentity=response.getEntity();//通过EntityUtils中的toString方法将结果转换为字符串result=EntityUtils.toString(entity);}catch(ClientProtocolExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}finally{//关闭资源if(null!=response){try{response.close();}catch(IOExceptione){e.printStackTrace();}}if(null!=httpClient){try{httpClient.close();}catch(IOExceptione){e.printStackTrace();}}}returnresult;}publicstaticStringdoPost(Stringurl,MapString,ObjectparamMap){CloseableHttpClienthttpClient=null;CloseableHttpResponsehttpResponse=null;Stringresult="";//创建httpClient实例httpClient=HttpClients.createDefault();//创建httpPost远程连接实例HttpPosthttpPost=newHttpPost(url);//配置请求参数实例RequestConfigrequestConfig=RequestConfig.custom().setConnectTimeout(35000)//设置连接主机服务超时时间.setConnectionRequestTimeout(35000)//设置连接请求超时时间.setSocketTimeout(60000)//设置读取数据连接超时时间.build();//为httpPost实例设置配置httpPost.setConfig(requestConfig);//设置请求头httpPost.addHeader("Content-Type","application/json");//封装post请求参数//if(null!=paramMap&&paramMap.size()0){//ListNameValuePairnvps=newArrayListNameValuePair();////通过map集成entrySet方法获取entity//SetMap.EntryString,ObjectentrySet=paramMap.entrySet();////循环遍历,获取迭代器//IteratorMap.EntryString,Objectiterator=entrySet.iterator();//while(iterator.hasNext()){//Map.EntryString,ObjectmapEntry=iterator.next();//nvps.add(newBasicNameValuePair(mapEntry.getKey(),mapEntry.getValue().toString()));//}//System.out.println(JSONObject.toJSONString(nvps));////为httpPost设置封装好的请求参数//try{//httpPost.setEntity(newUrlEncodedFormEntity(nvps,"UTF-8"));//}catch(UnsupportedEncodingExceptione){//e.printStackTrace();//}//}httpPost.setEntity(newStringEntity(JSONObject.toJSONString(paramMap),"utf-8"));try{//httpClient对象执行post请求,并返回响应参数对象httpResponse=httpClient.execute(httpPost);//从响应对象中获取响应内容HttpEntityentity=httpResponse.getEntity();result=EntityUtils.toString(entity);}catch(ClientProtocolExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}finally{//关闭资源if(null!=httpResponse){try{httpResponse.close();}catch(IOExceptione){e.printStackTrace();}}if(null!=httpClient){try{httpClient.close();}catch(IOExceptione){e.printStackTrace();}}}returnresult;}}最后,在一个main方法中,调用这个pushServiceMessage方法,即可发送成功。如果发送失败有什么微信方面的错误,方法返回的字符串输出即可展示错误信息。
总结好像写的比较粗糙,想要写的非常清除明了,还需要努力努力啊!希望这篇文章可以对大家有用。

版权声明

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

产品经理

手机 : 13312967497

擅长 : 小程序流量变现

扫码领取礼包

热门模板

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