kefu/lib/wechat_offical.go

94 lines
2.4 KiB
Go
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package lib
import (
"github.com/silenceper/wechat/v2"
"github.com/silenceper/wechat/v2/cache"
"github.com/silenceper/wechat/v2/credential"
"github.com/silenceper/wechat/v2/officialaccount"
"github.com/silenceper/wechat/v2/officialaccount/basic"
offConfig "github.com/silenceper/wechat/v2/officialaccount/config"
"github.com/silenceper/wechat/v2/officialaccount/message"
"kefu/tools"
"log"
"time"
)
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也可选择redismemcache或者自定cache
cfg := &offConfig.Config{
AppID: appId,
AppSecret: appSecret,
Token: token,
//EncodingAESKey: "xxxx",
Cache: memory,
}
obj.OfficialAccount = wc.GetOfficialAccount(cfg)
stableAccessToken := credential.NewStableAccessToken(appId, appSecret, credential.CacheKeyOfficialAccountPrefix, memory)
obj.OfficialAccount.SetAccessTokenHandle(stableAccessToken)
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: tools.SubStr(item["value"], 0, 20),
}
}
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)
}
}
}
/*
获取临时带参二维码
*/
func (this *WechatOffical) TmpQrCode(sceneName string) (string, error) {
basicObj := this.OfficialAccount.GetBasic()
tq := basic.NewTmpQrRequest(time.Duration(24*3600), sceneName)
ticket, err := basicObj.GetQRTicket(tq)
if err != nil {
return "", err
}
url := basic.ShowQRCode(ticket)
return url, nil
}