java实现微信公众号发送模版消息

前言:

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

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

格式如下:

{{first.DATA}}

用户名:{{keyword1.DATA}}

订单号:{{keyword2.DATA}}

订单金额:{{keyword3.DATA}}

商品信息:{{keyword4.DATA}}

{{remark.DATA}}

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

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

public void sendOrderTemplateMessage(Order order) {

AugeWechatUser wechatUser = augeWechatUserMapper.selectByPhone(order.getPhone());

String goodsInfo = "";

for (AugeSaleItem augeSaleItem : order.getData()) {

goodsInfo += augeSaleItem.getItemName() + "×" + augeSaleItem.getItemNum() + "\n\t\t\t";

}

DataInfo first = new DataInfo("恭喜你购买成功!", "#ff0000");

DataInfo keyword1 = new DataInfo(wechatUser.getNickName(), "#ff0000");

DataInfo keyword2 = new DataInfo(order.getOrderNumber(), "#ff0000");

DataInfo keyword3 = new DataInfo("¥" + order.getSumPrice() + "元", "#ff0000");

DataInfo keyword4 = new DataInfo(goodsInfo, "#ff0000");

DataInfo remark = new DataInfo("欢迎再次购买!", "#000000");

OrderData orderData = new OrderData(first, keyword1, keyword2, keyword3, keyword4, remark);

OrderTemplateMessage templateMessage = new OrderTemplateMessage();

templateMessage.setTouser(wechatUser.getId());

templateMessage.setTemplate_id(orderTemplateId);//模版ID

templateMessage.setData(orderData);

OkHttpUtil.getInstance().doPost(WechatConstant.getTemplateUrl(wechatAccessTokenService.takeAccessToken()),

JSON.toJSONString(templateMessage));

}

简单介绍 OkHttpUtil

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

public String doPost(String url, String param) {

MediaType );

RequestBody body = RequestBody.create(JSON, param);

Request request = new Request.Builder()

.url(url)

.post(body)

.build();

Call call = okHttpClient.newCall(request);

try {

Response response = call.execute();

return response.body().string();

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

注意配置订单模版ID

@Value("#{setting.ordertemplateid}")

private String orderTemplateId;

以上是 java实现微信公众号发送模版消息 的全部内容, 来源链接: utcz.com/z/324415.html

回到顶部