微信公衆號推送模板跳轉小程序

前幾天因業務需求,需要點擊模板消息跳轉小程序,所以在此發篇博客記錄一下。

代碼如下:

public void textTemplate(String deptExt) throws Exception {
    // 將信息封裝到實體類中
    TemplateMessage temp = new TemplateMessage();
    // 設置模板id
    temp.setTemplate_id("模板消息id");
    // 設置接受方的openid
    temp.setTouser("接收方的openid");
    // 設置點擊跳轉的路徑
    temp.setUrl("http://mp.weixin.qq.com");
    // 主要是這裏, 設置小程序的appid和轉發的頁面
    TreeMap<String, String> miniprograms = new TreeMap<String, String>();
    miniprograms.put("appid","小程序的appid");
    miniprograms.put("pagepath","pages/index/index?temp=1");// 注意,這裏是支持傳參的!!!
    temp.setMiniprogram(miniprograms);
    // 設置消息內容和對應的顏色
    TreeMap<String, TreeMap<String, String>> params = new TreeMap<String, TreeMap<String, String>>();
    // 設置消息內容,具體的按照你選擇的模板消息來
    params.put("first", TemplateMessage.item("1", "#173177"));
    params.put("keyword1", TemplateMessage.item(“2”, "#173177"));
    params.put("keyword2", TemplateMessage.item(“3”, "#173177"));
    params.put("keyword3", TemplateMessage.item("4", "#173177"));
    params.put("remark", TemplateMessage.item("5", "#173177"));
    temp.setData(params);
    // 將實體類轉換爲json格式
    JSONObject data = JSONObject.fromObject(temp);
    System.out.println(data + "");
    // 調用WeChatUtil工具類發送模板消息
    WeChatUtil.sendTemplate(data + "");
}

WeChatUtil是一個工具類,詳情可以看我之前發的博客,微信公衆號開發之模板消息。
TemplateMessage 是一個封裝模板消息的實體類。和之前的有所改變,增加了封裝跳轉小程序的屬性。

import java.util.TreeMap;

public class TemplateMessage {
    private String touser; // 接收者openid

    private String template_id; // 模板ID

    private String url; // 模板跳轉鏈接

    private TreeMap<String, TreeMap<String, String>> data; // data數據
    
    // 新增
    private TreeMap<String, String> miniprogram; // 跳小程序所需數據,不需跳小程序可不用傳該數據
    
    /**
     * 參數
     * 
     * @param value
     * @param color
     *            可不填
     * @return
     */
    public static TreeMap<String, String> item(String value, String color) {
        TreeMap<String, String> params = new TreeMap<String, String>();
        params.put("value", value);
        params.put("color", color);
        return params;
    }

我打感嘆號的地方,有箭頭的即爲可點擊的,也就是添加了點擊跳轉路徑的。可以跳h5頁面。設置了跳轉小程序所需的參數後,點擊就可以進入小程序了。
注意,跳轉的小程序必須是公衆號關聯的小程序!!!
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章