2025-01-18 17:56:36 +08:00

63 lines
1.4 KiB
Go

package wechat_api
import (
"gitea.youtukeji.com.cn/xiabin/douyin-openapi/cache"
"github.com/silenceper/wechat/v2"
"github.com/silenceper/wechat/v2/miniprogram"
miniConfig "github.com/silenceper/wechat/v2/miniprogram/config"
"gorm.io/gorm"
"sync"
"youtu_ecpm/pkg/errors"
)
type WechatApi struct {
db *gorm.DB
m *sync.Map
wc *wechat.Wechat
}
var WechatCli *WechatApi
func NewWechatOpenApiClient() *WechatApi {
return &WechatApi{
m: &sync.Map{},
wc: wechat.NewWechat(),
}
}
// GetWechatOpenApi 获取微信client
// appId: 小程序id
func (d *WechatApi) GetWechatOpenApi(appId string) (api *miniprogram.MiniProgram, err error) {
if v, ok := d.m.Load(appId); !ok {
err = errors.ErrCacheNotFound
return
} else {
api = v.(*miniprogram.MiniProgram)
return
}
}
// SetWechatOpenApi 存储微信client
// appId: 小程序id
func (d *WechatApi) SetWechatOpenApi(appId string, api *miniprogram.MiniProgram) {
d.m.Store(appId, api)
}
// NewAndStoreWechatOpenApi 创建微信client并存储
// appId: 小程序id
// appSecret: 小程序secret
// cache: 缓存
func (d *WechatApi) NewAndStoreWechatOpenApi(appId, appSecret string, cache cache.Cache) {
cfg := &miniConfig.Config{
AppID: appId,
AppSecret: appSecret,
//Token: "xxx",
// EncodingAESKey: "xxxx",
Cache: cache,
}
mini := d.wc.GetMiniProgram(cfg)
d.SetWechatOpenApi(appId, mini)
}