2025-01-21 16:56:59 +08:00

76 lines
2.1 KiB
Go

package svc
import (
"context"
"encoding/json"
"errors"
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/internal/config"
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/model"
helper "gitea.youtukeji.com.cn/youtu/openapi-helper"
redisCache "github.com/silenceper/wechat/v2/cache"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type ServiceContext struct {
Config config.Config
AppUser model.AppUserModel
GameScore model.GameScoreModel
AppAccount model.AppAccountModel
DouyinCli *helper.DouYinOpenApiClient
WechatCli *helper.WechatApi
}
func NewServiceContext(c config.Config) *ServiceContext {
svc := &ServiceContext{
Config: c,
AppUser: model.NewAppUserModel(sqlx.NewMysql(c.DB.DataSource), c.Cache),
GameScore: model.NewGameScoreModel(sqlx.NewMysql(c.DB.DataSource), c.Cache),
AppAccount: model.NewAppAccountModel(sqlx.NewMysql(c.DB.DataSource), c.Cache),
}
dwCache := redisCache.NewRedis(context.Background(), &redisCache.RedisOpts{Host: c.DWCache.Host, IdleTimeout: c.DWCache.IdleTimeout})
svc.DouyinCli = helper.NewDouYinOpenApiClient()
svc.WechatCli = helper.NewWechatOpenApiClient()
result, err := svc.AppAccount.FindAll(context.Background())
if err != nil {
panic(err)
}
for _, v := range *result {
if v.Type == 0 {
svc.DouyinCli.NewAndStoreDouYinOpenApi(v.AppID, v.Secret, v.EcpmValue.V, v.EcpmView.V, dwCache)
} else {
svc.WechatCli.NewAndStoreWechatOpenApi(v.AppID, v.Secret, dwCache)
}
}
return svc
}
type AccessToken struct {
AppId uint64 `json:"appId"`
UserId uint64 `json:"userId"`
AppIdStr string `json:"appIdStr"`
OpenId string `json:"openId"`
}
func UnmarshalAccessToken(d any) (ac AccessToken, err error) {
m, ok := d.(map[string]interface{})
if !ok {
err = errors.New("invalid access token")
return
}
appId, _ := m["appId"].(json.Number).Int64()
ac.AppId = uint64(appId)
userId, _ := m["userId"].(json.Number).Int64()
ac.UserId = uint64(userId)
ac.AppIdStr = m["appIdStr"].(string)
ac.OpenId = m["openId"].(string)
return
}
func GetCtxToken(ctx context.Context) (ac AccessToken, err error) {
return UnmarshalAccessToken(ctx.Value("payload"))
}