[博客小程序]評論通知功能實現(一)——小程序發送模板消息的幾種實現

這兩天抽空把評論通知的功能給基本實現了,主要解決讀者評論後,我沒法及時看到並回復的痛點。這篇主要說說模板消息發送的坑。

使用前準備

準備的話就是先讀下文檔,瞭解下模板消息怎麼發送和怎麼接入的,而後到你的後臺去選擇你想要的消息模板,記錄好對應的模板ID便可。php

image

最初看文檔的時候感受挺簡單的,無非先調用個接口獲取ACCESS_TOKEN, 而後調用發送模板消息的接口就完事了,固然事實也確實如此,但其中仍是有些小坑的。java

後端實現

後端實現對於我來講最輕鬆,畢竟是搞後端開發的嘛,我用.net core的方式實現了一把,輕鬆搞定,貼下代碼,至於java或者php,其實差很少。git

/// <summary>
/// 獲取新的 AccessToken
/// </summary>
/// <returns></returns>
public static async Task<string> GetAccessToken()
{
    var url = $"{WechatApiHost}/cgi-bin/token";
    var response = await HttpRequestHelper.GetAsync<dynamic>(url, new
    {
        grant_type = "client_credential",
        appid = WechatAppId,
        secret = WechatSecret
    }, null, GlobalRequestConfig);
    return response.IsSucceed && response.Data != null ? response.Data.access_token : null;
}

/// <summary>
/// 發送模板消息
/// </summary>
/// <returns>The template message.</returns>
/// <param name="openId">Open identifier.</param>
public static async Task<ResponseResult> sendTemplateMessage(String openId)
{
    //先從redis獲取token
    var accessToken = await RedisInstance.Get<string>(MiniAccessTokenRedisKey);
    if(string.IsNullOrWhiteSpace(accessToken))
    {
        accessToken =await GetNewAccessToken();
        if (string.IsNullOrWhiteSpace(accessToken))
            return new ResponseResult { Result = false, ErrorMessage = "token獲取失敗", Code = ResponseCode.InvalidParameters };
        //保存到redis,默認1小時
        await RedisInstance.Set<string>(MiniAccessTokenRedisKey, accessToken, 1 * 60 * 60);
    }
    var url = $"{WechatApiHost}/cgi-bin/message/wxopen/template/send?access_token={accessToken}";
    var tempData = new
    {
        touser = openId,
        template_id = MiniMessageTemplate,//申請的模板消息id,
        page = "/pages/detail/detail?blog=1",
        form_id = FormId,
        data = new
        {
            keyword1 = new
            {
                value = "元素1"
            },
            keyword2 = new
            {
                value = "元素2"
            },
            keyword3 = new
            {
                value = "元素3"
            }
        },
        //emphasis_keyword= "keyword1.DATA"
    };
    var response = await HttpRequestHelper.PostAsync<dynamic>(url, tempData, null, GlobalRequestConfig);
    var sendResult = "";
    if (!response.IsSucceed)
        return new ResponseResult { Result = false, ErrorMessage = response.ErrorMessage, Code = ResponseCode.UnknownException };

    return new ResponseResult { Result = true, ErrorMessage = "", Code = ResponseCode.Success };
}

js實現

js的實現方式和後端代碼實現也差很少,也是調用兩個接口,邏輯一致,這裏主要介紹util函數,避免重複造輪子。程序員

#github地址
https://github.com/lcxfs1991/wx-js-utils

image

對應的微信開放平臺接口都基本已經封裝好了,文檔也比較詳細,有興趣的能夠本身體驗下。github

雲調用實現

這纔是我想要的,自己個人博客小程序部分功能是基於雲開發的,同時雲調用實現的方式省去了獲取ACCESS_TOKEN的步驟,使用起來比較方便。redis

具體實現文檔仍是比較詳細的,在使用前必定要在你的雲函數目錄下添加config.json文件,聲明好所需調用的接口,並上傳到雲端。json

#聲明使用發送模板消息接口
{
  "permissions": {
    "openapi": ["templateMessage.send"]
  }
}

這樣就能夠正常使用啦,貼下個人發送模板消息的代碼:小程序

const sendResult = await cloud.openapi.templateMessage.send({
    touser: touser,
    templateId: template,
    formId: form_id,
    page: 'pages/detail/detail?blogId=' + event.blogId,
    data: {
      keyword1: {
        value: event.nickName // keyword1 的值
      },
      keyword2: {
        value: event.message // keyword2 的值
      }
    },
  })

本覺得一切順利,但終究好事多磨,上傳到雲端以後一直提示:後端

function has no permission to call this API

首先懷疑個人config.json沒有上傳上去,經過雲開發後臺去下載對應的函數,發現已經上傳,同時也肯定配置沒有問題。api

再次仔細看文檔,看到這樣一句話:

版本要求:wx-server-sdk >= 0.4.0、開發者工具 >= 1.02.1903251 (目前需開發版或測試版

因而嘗試下載了開發版,從新上傳了雲函數,問題解決了「淚奔中」

因此有使用雲調用實現的小夥伴必定要注意本身的開發中工具。

其餘

使用ACCESS_TOKEN的時候必定要注意,建議使用統一的服務來獲取和刷新 access_token,其餘業務邏輯所使用的 access_token 均來自於該服務,不該該各自去刷新,不然容易形成衝突,致使 access_token 覆蓋而影響業務。

另外開發版工具支持本地調試雲函數了,同時雲開發的管理界面也有很大改動,有興趣的能夠嘗試下載看看。

最後,下一篇文章講講個人博客小程序中評論通知功能的具體實現。

Ps.小程序名稱:程序員的博客

相關文章
相關標籤/搜索