第三章 微信公众号开发之模板消息

       模板消息仅用于公众号向用户发送重要的服务通知,只能用于符合其要求的服务场景中,如信用卡刷卡通知,商品购买成功通知等。不支持广告等营销类消息以及其它所有可能对用户造成骚扰的消息。

  关于使用规则,请注意:

1、所有服务号都可以在功能->添加功能插件处看到申请模板消息功能的入口,但只有认证后的服务号才可以申请模板消息的使用权限并获得该权限;
2、需要选择公众账号服务所处的2个行业,每月可更改1次所选行业;
3、在所选择行业的模板库中选用已有的模板进行调用;
4、每个账号可以同时使用25个模板。
5、当前每个账号的模板消息的日调用上限为10万次,单个模板没有特殊限制。【2014年11月18日将接口调用频率从默认的日1万次提升为日10万次,可在MP登录后的开发者中心查看】。当账号粉丝数超过10W/100W/1000W时,模板消息的日调用上限会相应提升,以公众号MP后台开发者中心页面中标明的数字为准。


发送模板消息

接口调用请求说明

http请求方式: POST
https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN

POST数据说明

POST数据示例如下:

      {
           "touser":"OPENID",
           "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
           "url":"http://weixin.qq.com/download",  
           "miniprogram":{
             "appid":"xiaochengxuappid12345",
             "pagepath":"index?foo=bar"
           },          
           "data":{
                   "first": {
                       "value":"恭喜你购买成功!",
                       "color":"#173177"
                   },
                   "keyword1":{
                       "value":"巧克力",
                       "color":"#173177"
                   },
                   "keyword2": {
                       "value":"39.8元",
                       "color":"#173177"
                   },
                   "keyword3": {
                       "value":"2014年9月22日",
                       "color":"#173177"
                   },
                   "remark":{
                       "value":"欢迎再次购买!",
                       "color":"#173177"
                   }
           }
       }

参数说明

参数 是否必填 说明
touser 接收者openid
template_id 模板ID
url 模板跳转链接
miniprogram 跳小程序所需数据,不需跳小程序可不用传该数据
appid 所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系,暂不支持小游戏)
pagepath 所需跳转到小程序的具体页面路径,支持带参数,(示例index?foo=bar),暂不支持小游戏
data 模板数据
color 模板内容字体颜色,不填默认为黑色

注:url和miniprogram都是非必填字段,若都不传则模板无跳转;若都传,会优先跳转至小程序。开发者可根据实际需要选择其中一种跳转方式即可。当用户的微信客户端版本不支持跳小程序时,将会跳转至url。

返回码说明

扫描二维码关注公众号,回复: 2262403 查看本文章

在调用模板消息接口后,会返回JSON数据包。正常时的返回JSON数据包示例:

    {
           "errcode":0,
           "errmsg":"ok",
           "msgid":200228332
       }

根据官方文档开发代码如下

1.先创建两个实体类:

public class TemplateData {

    private String value;
    private String color;

    public TemplateData(String value,String color){
        this.value = value;
        this.color = color;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

}
public class TemplateMessage {

    private String touser; //用户OpenID

    private String template_id; //模板消息ID

    private String url; //URL置空,在发送后,点模板消息进入一个空白页面(ios),或无法点击(android)。

    private Map<String, TemplateData> data; //模板详细信息

    public String getTemplate_id() {
        return template_id;
    }

    public void setTemplate_id(String template_id) {this.template_id = template_id;
    }

    public String getTouser() {
        return touser;
    }

    public void setTouser(String touser) {
        this.touser = touser;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Map<String, TemplateData> getData() {
        return data;
    }

    public void setData(Map<String, TemplateData> data) {
        this.data = data;
    }
}

2.组装你需要的对象

public BaseResponse DelayedDelivery(Long orderId) {

    BaseResponse response = new BaseResponse();

    try {

        OrderInfo orderInfo1 =new OrderInfo();

        orderInfo1.setOrderId(orderId);

        OrderInfo orderInfo =orderInfoDao.selectByOrderId(orderInfo1);

        Product product = productDao.selcetByProductId(orderInfo.getProductId());

        CustomerInfo customerInfo1 = new CustomerInfo();

        customerInfo1.setCustomerId(orderInfo.getCustomerId());

        CustomerInfo info = customerInfoDao.selectOne(customerInfo1);

        TemplateMessage message = new TemplateMessage();

        if (!("").equals(info.getOpenId())) {

            message.setTouser(info.getOpenId());

            message.setTemplate_id("你选择的模版ID");

            TemplateData templateData1 = new TemplateData("尊敬的『" + info.getNickName() + "』," + "买家选择了延期收货。", colour);

            TemplateData templateData2 = new TemplateData("已支付", colour);

            TemplateData templateData3 = new TemplateData(CommonUtil.getFormatDate(new Date()), colour);

            TemplateData templateData4 = new TemplateData("请你注意买家收货时间。", colour);

            Map<String, TemplateData> date = new HashMap<>();

            date.put("first", templateData1);

            date.put("keyword1", templateData2);

            date.put("keyword2", templateData3);

            date.put("remark", templateData4);

            message.setData(date);

            message.setUrl("填写请求的地址");

            weixinUtil.sendWechatMsgToUser(message);

            PlatformLogger.message("延迟收货通知方法执行成功");
        }
    } catch (Exception e) {

        response.setRepCode(RepCode.BIZ_101.code);
        response.setErrorInfo(RepCode.BIZ_101.message);
        PlatformLogger.error("延迟收货通知方法执行失败", e);
    }
    return response;
}

3.一个访问微信服务器的方法

public  String sendWechatMsgToUser(TemplateMessage message) {

    String tmpurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" +getAllAccessToken() ;

    String datas = JsonUtil.toJson(message);

    HttpsClient client;

    try {
        client = sendPost(tmpurl,datas);
    } catch (Exception e) {
        PlatformLogger.error("给用户推送消息异常", e);
        return null;
    }
    if (client != null && client.getStatus() == SUCCESS_CONNECTION) {
        String jsonResult = client.getResult();
        Map<String, Object> resultMap = (Map<String, Object>) JsonUtil.fromJson(jsonResult, Map.class);
        PlatformLogger.message("用户消息推送结果"+jsonResult);
        if (!resultMap.isEmpty() &&  resultMap.get("errcode")!=null&&(Integer)resultMap.get("errcode") == 0) {
            PlatformLogger.message("推送消息成功");
            return (String) resultMap.get("errmsg");

        } else {
            PlatformLogger.message("给用户推送消息异常,失败原因" + resultMap.get("errmsg"));
        }
    }
    return null;

}
推送模版消息就是这么简单



猜你喜欢

转载自blog.csdn.net/godhexin/article/details/81061307