微信公众号发送模版消息

前言:

  在我们购买商品或其他操作的时候,这时候微信公众号会推送相关模版消息。接下来简单介绍开发流程:(本文以订单推送为例)

首先在测试号新建模版消息

格式如下:


{{first.DATA}} 
用户名:{{keyword1.DATA}} 
订单号:{{keyword2.DATA}} 
订单金额:{{keyword3.DATA}} 
商品信息:{{keyword4.DATA}} 
{{remark.DATA}}

这里会生成一个模版ID,后面会用到

然后后台在上传订单接口,上传成功后调用发送模版消息,代码实现:


 1 public void sendOrderTemplateMessage(Order order) {
 2     AugeWechatUser wechatUser = augeWechatUserMapper.selectByPhone(order.getPhone());
 3     String goodsInfo = "";
 4     for (AugeSaleItem augeSaleItem : order.getData()) {
 5         goodsInfo += augeSaleItem.getItemName() + "×" + augeSaleItem.getItemNum() + "\n\t\t\t";
 6     }
 7     DataInfo first = new DataInfo("恭喜你购买成功!", "#ff0000");
 8     DataInfo keyword1 = new DataInfo(wechatUser.getNickName(), "#ff0000");
 9     DataInfo keyword2 = new DataInfo(order.getOrderNumber(), "#ff0000");
10     DataInfo keyword3 = new DataInfo("¥" + order.getSumPrice() + "元", "#ff0000");
11     DataInfo keyword4 = new DataInfo(goodsInfo, "#ff0000");
12     DataInfo remark = new DataInfo("欢迎再次购买!", "#000000");
13 
14     OrderData orderData = new OrderData(first, keyword1, keyword2, keyword3, keyword4, remark);
15     OrderTemplateMessage templateMessage = new OrderTemplateMessage();
16     templateMessage.setTouser(wechatUser.getId());
17     templateMessage.setTemplate_id(orderTemplateId);//模版ID
18     templateMessage.setData(orderData);
19 
20     OkHttpUtil.getInstance().doPost(WechatConstant.getTemplateUrl(wechatAccessTokenService.takeAccessToken()), 
21 JSON.toJSONString(templateMessage));
22 }

简单介绍 OkHttpUtil

OkHttp是一个第三方类库,用于Android中请求网络。


 1 public String doPost(String url, String param) {
 2         MediaType );
 3         RequestBody body = RequestBody.create(JSON, param);
 4         Request request = new Request.Builder()
 5                 .url(url)
 6                 .post(body)
 7                 .build();
 8         Call call = okHttpClient.newCall(request);
 9         try {
10             Response response = call.execute();
11             return response.body().string();
12         } catch (IOException e) {
13             e.printStackTrace();
14         }
15         return null;
16     }

注意配置订单模版ID


1 @Value("#{setting.ordertemplateid}")
2 private String orderTemplateId;
 
 
posted @ 2018-03-23 17:33  小小渔夫  阅读(927)  评论(1编辑  收藏  举报
友情链接: 燕归来兮 李狗蛋Blog 萌力觉醒