1. 程式人生 > 其它 >微信小程式訂閱訊息

微信小程式訂閱訊息

概述

訊息能力是小程式能力中的重要組成,我們為開發者提供了訂閱訊息能力,以便實現服務的閉環和更優的體驗。

  • 訂閱訊息推送位置:服務通知
  • 訂閱訊息下發條件:使用者自主訂閱
  • 訂閱訊息卡片跳轉能力:點選檢視詳情可提愛轉至該小程式的頁面

訊息型別

  1. 一次性訂閱訊息
    一次性訂閱訊息用於解決使用者使用小程式後,後續服務環節的通知問題。使用者自主訂閱後,開發這可不限時間的下發一條對應的服務訊息 ; 每條訊息可單獨訂閱或退訂(開發者自行控制傳送)。
  2. 長期訂閱訊息
    一次性訂閱訊息可滿足小程式的大部分服務場景需求,但線下公共服務領域存在一次性訂閱無法滿足的場景,如航班延誤,需根據航班實時動態來多次傳送訊息提醒,為便於服務,因此提供了長期性訂閱訊息,使用者訂閱一次後,開發者可長期下發多條訊息。
    目前長期性訂閱訊息僅向政務民生、醫療、交通、金融、教育等線下公共服務開放。

使用步驟

第一步 選擇/配置模板

在微信公眾號平臺配置並獲取模板ID。
登入https://mp.weixin.qq.com功能 >訂閱訊息欄目,在我的模板中列出了當前使用者定義的所有模板資訊,

當不存在模板或沒有合適的模板時,可在 公共模板 中申請新增新模板,待稽核通過後便可使用。

第二步 訂閱訊息

在小程式中通過編碼的方式呼叫微信介面 wx.requestSubscribeMessage 進行訊息訂閱。

示例
佈局程式碼

    <button bindtap="dingyue_message" >訂閱訊息</button>

js 程式碼

/**
   * 訂閱-訊息
   * @param {*} e 
   */
  dingyue_message : function(e){
    wx.requestSubscribeMessage({
      tmplIds: ['模板ID'],
      success:function(res){
        console.log('success:' + res.errMsg)
      },
      fail: function(res){
        console.log('error:' + res.errMsg + "  " + res.errCode)
      }
    })
  }

例項中點選訂閱訊息按鈕,會彈出訂閱訊息介面,返回使用者訂閱訊息的結果。

注意事項

  • 一次性模板 Id 和永久模板 Id 不可同時使用
  • 低版本基礎庫2.4.4~2.8.3 已支援訂閱訊息介面呼叫,僅支援傳入一個一次性 tmplId / 永久 tmplId。
  • 2.8.2 版本開始,使用者發生點選行為或者發起支付回撥後,才可以調起訂閱訊息介面。
  • 2.10.0 版本開始,開發版和體驗版小程式將禁止使用模板訊息 formId。
  • 一次授權呼叫裡,每個tmplId對應的模板標題不能存在相同的,若出現相同的,只保留一個。
  • 2.10.0 版本開始,支援訂閱語音訊息提醒
第三步 服務端訊息傳送

傳送訂閱訊息的呼叫方式有

HTTPS呼叫雲呼叫 兩種方式,本文只介紹 HTTPS呼叫

請求地址

POST https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN

請求引數

引數名 型別 預設值 必須 說明
access_token / cloudbase_access_token string 介面呼叫憑證
touser string 接收者(使用者)的 openid
template_id string 所需下發的訂閱模板id
page string 點選模板卡片後的跳轉頁面,僅限本小程式內的頁面。支援帶引數,(示例index?foo=bar)。該欄位不填則模板無跳轉。
data Object 模板內容,格式形如 { "key1": { "value": any }, "key2": { "value": any } }
miniprogram_state string 跳轉小程式型別:developer為開發版;trial為體驗版;formal為正式版;預設為正式版
string 進入小程式檢視”的語言型別,支援zh_CN(簡體中文)、en_US(英文)、zh_HK(繁體中文)、zh_TW(繁體中文),預設為zh_CN

返回值

屬性 型別 說明
errCode number 錯誤碼
errMsg string 錯誤資訊

errCode 程式碼說明

程式碼 說明
0 成功
40003 touser欄位openid為空或者不正確
40037 訂閱模板id為空不正確
43101 使用者拒絕接受訊息,如果使用者之前曾經訂閱過,則表示使用者取消了訂閱關係
47003 模板引數不準確,可能為空或者不滿足規則,errmsg會提示具體是哪個欄位出錯
41030 page路徑不正確,需要保證在現網版本小程式中存在,與app.json保持一致

請求示例


/// <summary>
/// 微信傳送訊息
/// </summary>
public class MessageService : IMessageService
{

    /// <summary>
    /// 傳送秒殺活動訊息
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<ServiceResult<WeixinResultBase>> SendSeckillMessageAsync(SeckillMessageRequest request)
    {
        var goodsName = request.GoodsName;
        if (goodsName.Length >= 20)
        {
            goodsName = request.GoodsName.Substring(0, 15) + "...";
        }
        var req = new SendMessageRequest
        {
            OpenId = request.OpenId,
            TemplateId = request.TemplateId,
            Page = $"{_seckillPagePath}?corpId={request.CorpId}&customerId={request.CustomerId}",
            Data = new Dictionary<string, object>()
            {
                {"thing1",new { value = goodsName } },
                {"time2",new { value = request.Time } },
                {"thing3",new { value = "秒殺活動即將開始,支援一鍵釋出到商店" } }
            }
        };
        return await SendMessageAsync(req);
    }

    public async Task<ServiceResult<WeixinResultBase>> SendMessageAsync(SendMessageRequest request)
    {
        //先從快取讀取token
        var accessToken = await _cache.GetStringAsync("store_assistant_accesstoken");
        var url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={_appId}&secret={_appSecret}";
        var response = await _httpClientFactory.GetClient().GetAsync(url);
        var accessTokenResult = await response.Content.ReadAsAsync<WxAccessTokenQueryResult>();
        if (accessTokenResult != null && accessTokenResult.ErrCode == 0)
            accessToken = accessTokenResult.AccessToken;

        var url = $"https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={access_token.Result}";
        var response = await _httpClientFactory.GetClient().PostDataAsync(url, request);
        var responseTxt = await response.Content.ReadAsStringAsync();
        var sendMsgResult = JsonConvert.DeserializeObject<WeixinResultBase>(responseTxt);
        if (sendMsgResult != null && sendMsgResult.ErrCode == 0)
            return ServiceResult.Succeed(sendMsgResult);
        
        return ServiceResult.Failed(sendMsgResult, sendMsgResult.ErrCode, sendMsgResult.ErrMsg);
    }
}

/// <summary>
/// 傳送微信訊息通知
/// </summary>
public class SendMessageRequest
{
    /// <summary>
    /// 使用者openId
    /// </summary>
    [JsonProperty("touser")]
    public string OpenId { get; set; }

    /// <summary>
    /// 訂閱模板id
    /// </summary>
    [JsonProperty("template_id")]
    public string TemplateId { get; set; }

    /// <summary>
    /// 跳轉頁面
    /// </summary>
    [JsonProperty("page")]
    public string Page { get; set; }

    /// <summary>
    /// 模板型別
    /// </summary>
    [JsonProperty("data")]
    public Dictionary<string, object> Data { get; set; }

    /// <summary>
    /// 跳轉小程式型別 (eveloper為開發版;trial為體驗版;formal為正式版;預設為正式版)
    /// </summary>
    [JsonProperty("miniprogram_state")]
    public string MiniType { get; set; } = "formal";

    /// <summary>
    /// 語言型別(預設為zh_CN)
    /// </summary>
    [JsonProperty("lang")]
    public string Lang { get; set; } = "zh_CN";
}