微信公众号模板消息源码实现,打破服务号群发推送次数限制

公众号服务号每个月只能群发推送四次文章,我们可以使用模板消息为公众号粉丝推送信息

下面是使用golang实现的模板消息发送类库封装,轻松实现模板消息发送

wechat.go

package lib

import (
    "github.com/silenceper/wechat/v2"
    "github.com/silenceper/wechat/v2/cache"
    "github.com/silenceper/wechat/v2/officialaccount"
    offConfig "github.com/silenceper/wechat/v2/officialaccount/config"
    "github.com/silenceper/wechat/v2/officialaccount/message"
    "log"
)

type WechatOffical struct {
    AppId, AppSecret, Token string
    OfficialAccount         *officialaccount.OfficialAccount
}

func NewWechatOffical(appId, appSecret, token string, memory cache.Cache) *WechatOffical {
    obj := &WechatOffical{
        AppId:     appId,
        AppSecret: appSecret,
        Token:     token,
    }
    wc := wechat.NewWechat()
    //这里本地内存保存access_token,也可选择redis,memcache或者自定cache

    cfg := &offConfig.Config{
        AppID:     appId,
        AppSecret: appSecret,
        Token:     token,
        //EncodingAESKey: "xxxx",
        Cache: memory,
    }
    obj.OfficialAccount = wc.GetOfficialAccount(cfg)
    return obj
}

/*
发送模板消息
    messages := []map[string]string{
        {"key": "thing4", "value": "我想购买客服系统"},
        {"key": "thing13", "value": "老狼"},
        {"key": "time14", "value": "2023-07-27 10:10:10"},
    }
    offical.SendTemplateMessage(
        []string{"openid"},
        "模板ID",
        "跳转地址",
        messages,
    )
*/
func (this *WechatOffical) SendTemplateMessage(openids []string, templateId, url string, messages []map[string]string) {
    template := this.OfficialAccount.GetTemplate()
    msgData := make(map[string]*message.TemplateDataItem)
    for _, item := range messages {
        msgData[item["key"]] = &message.TemplateDataItem{
            Value: item["value"],
        }
    }
    for _, openid := range openids {
        msg := &message.TemplateMessage{
            ToUser:     openid,
            Data:       msgData,
            TemplateID: templateId,
            URL:        url,
        }
        msgId, err := template.Send(msg)
        if err != nil {
            log.Println(err, msgId)
        }
    }

}

我们的使用方式

package lib

import (
    "github.com/silenceper/wechat/v2/cache"
    "testing"
)

func TestWechatOffical_SendTemplateMessage(t *testing.T) {
    memory := cache.NewMemory()
    offical := NewWechatOffical("xxx", "xxxxx", "xxxx", memory)
    messages := []map[string]string{
        {"key": "thing4", "value": "我想购买客服系统"},
        {"key": "thing13", "value": "老狼"},
        {"key": "time14", "value": "2023-07-27 10:10:10"},
    }
    offical.SendTemplateMessage(
        []string{"xxxx"},
        "xxxxxxxx",
        "https://gofly.v1kf.com",
        messages,
    )
}

推送的效果如图所示,点击模板就能跳转到我们自定义的url上

我在自己客服系统中也是使用这种方式为客服进行消息提醒的,客服收到提醒后,点击就能回复访客消息,非常方便

有需要的朋友可以访问 gofly.v1kf.com ,了解测试我的客服系统

 

开源地址:唯一客服(开源学习版)
官网地址:唯一客服官网