kefu/service/mini_wechat.go

83 lines
2.7 KiB
Go
Raw Normal View History

2024-12-10 02:50:12 +00:00
package service
import (
"fmt"
"github.com/silenceper/wechat/v2"
offConfigMini "github.com/silenceper/wechat/v2/miniprogram/config"
subscribeMsg "github.com/silenceper/wechat/v2/miniprogram/subscribe"
"kefu/models"
"kefu/tools"
"log"
"strings"
)
//发送微信小程序订阅消息
func SendTestMiniSubscribe() {
cfg := &offConfigMini.Config{
AppID: "wxc3d6951d9045036b",
AppSecret: "3722ffd11e3a137c9cdadc2af2e6a58e",
//EncodingAESKey: "xxxx",
Cache: memory,
}
wc := wechat.NewWechat()
mini := wc.GetMiniProgram(cfg)
subscribe := mini.GetSubscribe()
data := make(map[string]*subscribeMsg.DataItem, 0)
data["thing1"] = &subscribeMsg.DataItem{Value: "测试", Color: "#000"}
data["time2"] = &subscribeMsg.DataItem{Value: tools.GetNowTime(), Color: "#000"}
data["name3"] = &subscribeMsg.DataItem{Value: "客服", Color: "#000"}
msg := &subscribeMsg.Message{
ToUser: "okSbF5AhyVeyO-gK-Nj_nwoi2LQU",
TemplateID: "Hk0zWtbgl0aci6b0UIWSUBywYzaglNqkw0KhzkbEuN4",
Page: "/pages/index",
Data: data,
}
log.Printf("%+v \n", msg)
err := subscribe.Send(msg)
if err != nil {
log.Println("发送小程序订阅消息失败:", err)
}
}
func SendMiniSubscribe(visitorId, content, entId, kefuName string) bool {
content = tools.TrimHtml(content)
visitorIdArr := strings.Split(visitorId, "|")
if len(visitorIdArr) < 3 || visitorIdArr[0] != "mini" {
return false
}
toUser := visitorIdArr[2]
configs := models.GetEntConfigsMap(entId, "WechatMiniTemplateId", "WechatMiniPages", "WechatMiniAppId", "WechatMiniAppSecret")
if configs["WechatMiniTemplateId"] == "" ||
configs["WechatMiniPages"] == "" ||
configs["WechatMiniAppId"] == "" ||
configs["WechatMiniAppSecret"] == "" {
return false
}
cfg := &offConfigMini.Config{
AppID: configs["WechatMiniAppId"],
AppSecret: configs["WechatMiniAppSecret"],
Cache: memory,
}
wc := wechat.NewWechat()
mini := wc.GetMiniProgram(cfg)
subscribe := mini.GetSubscribe()
data := make(map[string]*subscribeMsg.DataItem, 0)
data["thing1"] = &subscribeMsg.DataItem{Value: content, Color: "#000"}
data["time2"] = &subscribeMsg.DataItem{Value: tools.GetNowTime(), Color: "#000"}
data["name3"] = &subscribeMsg.DataItem{Value: kefuName, Color: "#000"}
msg := &subscribeMsg.Message{
ToUser: toUser,
TemplateID: configs["WechatMiniTemplateId"],
Page: configs["WechatMiniPages"],
Data: data,
}
err := subscribe.Send(msg)
log.Printf("发送小程序订阅消息:%+v\n", msg)
if err != nil {
log.Println("发送小程序订阅消息失败:", err)
memory.Delete(fmt.Sprintf("%s_access_token_%s", "gowechat_miniprogram_", configs["WechatMiniAppId"]))
subscribe.Send(msg)
}
return true
}