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

 

一鍵加羣

 

發佈了44 篇原創文章 · 獲贊 86 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章