WeChat public account to send template messages

    When we buy goods or other operations, the WeChat public account will push relevant template messages at this time. Next, a brief introduction to the development process: (This article takes order push as an example)

First, the new model version message in the test number

The format is as follows:

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

A template ID will be generated here, which will be used later

Then the background uploads the order interface, and after the upload is successful, it calls to send the template message

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 (goodsInfonew    DataInfo keyword4 =, "#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));
}

A brief introduction to OkHttpUtil

OkHttp is a third-party library for requesting networking in Android.

public String doPost(String url, String param) {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        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;
    }

Note the configuration order template ID

@Value("#{setting.ordertemplateid}")
private String orderTemplateId;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324910881&siteId=291194637