Java微信公众平台开发之发送模板消息

模板消息仅用于公众号向用户发送重要的服务通知,只能用于符合其要求的服务场景中,如信用卡刷卡通知,商品购买成功通知等。不支持广告等营销类消息以及其它所有可能对用户造成骚扰的消息。对于一般的服务号而言,模板ID行业之类会事先配置好,所以用代码控制的只有发送了。

准备工作:已通过认证的服务号或者测试公众号

一、使用规则

  • 所有服务号都可以在功能->添加功能插件处看到申请模板消息功能的入口
  • 需要选择公众账号服务所处的2个行业,每月可更改1次所选行业
  • 在所选择行业的模板库中选用已有的模板进行调用
  • 每个账号可以同时使用25个模板
  • 当前每个账号的模板消息的日调用上限为10万次,单个模板没有特殊限制,以公众号MP后台开发者中心页面中标明的数字为准

二、接口文档规范

  • 模板消息调用时主要需要模板ID和模板中各参数的赋值内容
  • 模板中参数内容必须以".DATA"结尾,否则视为保留字
  • 模板保留符号"{{ }}"

测试公众号可以随意定义,正式的必须用模板库中的

三、 封装模板消息

以下是我使用的模板消息示例

{{first.DATA}}
旅行活动名称:{{keyword1.DATA}}
订单金额:{{keyword2.DATA}}
旅行时间:{{keyword3.DATA}}
参与人数:{{keyword4.DATA}}
{{remark.DATA}}

POST数据示例如下:

      {
           "touser":"OPENID",
           "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
           "url":"http://weixin.qq.com/download",  
           "miniprogram":{
             "appid":"xiaochengxuappid12345",
             "pagepath":"index?foo=bar"
           },          
           "data":{
                   "first": {
                       "value":"恭喜你购买成功!",
                       "color":"#173177"
                   },
                   "keynote1":{
                       "value":"巧克力",
                       "color":"#173177"
                   },
                   "keynote2": {
                       "value":"39.8元",
                       "color":"#173177"
                   },
                   "keynote3": {
                       "value":"2014年9月22日",
                       "color":"#173177"
                   },
                   "remark":{
                       "value":"欢迎再次购买!",
                       "color":"#173177"
                   }
           }
       }
@Getter
@Setter
@NoArgsConstructor
public class WechatTemplateMessage implements Serializable {

    private static final long serialVersionUID = -1035536196053732735L;

    @SerializedName("touser")
    private String touser; //接收者openid

    @SerializedName("template_id")
    private String templateId; //模板ID

    @NotRequire//只是个标识
    private String url; //模板跳转链接

    // "miniprogram":{ 未加入
    // "appid":"xiaochengxuappid12345",
    // "pagepath":"index?foo=bar"
    // },

    private Map<String, Map<String, String>> data; //data数据

    public WechatTemplateMessage(String templateId, String url) {
        this.templateId = templateId;
        this.url = url;
    }

    /**
     * 参数
     *
     * @param value
     * @param color 可不填
     * @return
     */
    public Map<String, String> item(String value, String color) {
        Map<String, String> params = new HashMap<>();
        params.put("value", value);
        params.put("color", color == null ? "#000000" : color);
        return params;
    }

    public String toJson() {
        return JsonUtil.toJson(this);
    }
}

四、发送模板消息

// 发送模板消息
public static final String SEND_TEMPLATE_MESSAGE = "https://api.weixin.qq.com/cgi-bin/message/template/send";
/**
 * 发送模板消息
 * 
 * @param accessToken
 * @param data
 * @return 状态
 */
@Override
public TemplateMessageResult sendTemplate(String accessToken, String data) {
    Map<String, String> params = new HashMap<>();
    params.put("access_token", accessToken);
    String result = HttpUtil.doPost(wechatMessageConfig.getSendTemplateMessageUrl(),
            params, data);
    return JsonUtil.fromJson(result, TemplateMessageResult.class);
}

五、根据业务调用方法

一般注册成功、支付成功、支付失败等等情况下会用到,以下只是个Junit

package com.phil.wechat.message.service.impl;

import com.phil.WechatMainApplication;
import com.phil.wechat.auth.service.WechatAuthService;
import com.phil.wechat.message.model.template.request.WechatTemplateMessage;
import com.phil.wechat.message.service.WechatTemplateMessageService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.HashMap;
import java.util.Map;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = WechatMainApplication.class)
@ActiveProfiles("dev")
public class WechatTemplateMessageServiceImplTest {

    @Autowired
    private WechatAuthService wechatAuthService;

    @Autowired
    private WechatTemplateMessageService wechatTemplateMessageService;

    @Test
    public void testSendTemplate() {
        String accessToken = wechatAuthService.getAccessToken();
        Map<String, Map<String, String>> params = new HashMap<>();
        WechatTemplateMessage template = new WechatTemplateMessage();
        params.put("keyword1", template.item("8.1发现尼泊尔—人文与自然的旅行圣地", null));
        params.put("keyword2", template.item("5000元", null));
        params.put("keyword3", template.item("2017.1.2", null));
        params.put("keyword4", template.item("5", null));
        template.setTemplateId("Ub2oYYFPf8ofmA17H31Zqu9Z_HLycZ7MC-Dx_Se1Nkw");
        template.setTouser("ovHQ5v6CW3INkWUsCl3olODif0cc");
        template.setUrl("http://music.163.com/#/song?id=27867140");
        template.setData(params);
        System.out.println(wechatTemplateMessageService.sendTemplate(accessToken, template.toJson()));
        //ResultState(errcode=0, errmsg=ok)
    }
}

具体源码:https://github.com/philjing/my_wechat/tree/master/src/main/java/com/phil/wechat/message/service

一键加群

本文为Phil Jing原创文章,未经博主允许不得转载,如有问题请直接回复或者加群。
原文地址:https://www.cnblogs.com/phil_jing/p/15615891.html