youtu_server/game_open_api/internal/svc/service_context.go

76 lines
2.1 KiB
Go
Raw Normal View History

2025-01-20 10:10:08 +08:00
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"
2025-01-21 16:48:55 +08:00
helper "gitea.youtukeji.com.cn/youtu/openapi-helper"
redisCache "github.com/silenceper/wechat/v2/cache"
2025-01-20 10:10:08 +08:00
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type ServiceContext struct {
Config config.Config
AppUser model.AppUserModel
GameScore model.GameScoreModel
AppAccount model.AppAccountModel
2025-01-21 16:48:55 +08:00
DouyinCli *helper.DouYinOpenApiClient
WechatCli *helper.WechatApi
2025-01-20 10:10:08 +08:00
}
func NewServiceContext(c config.Config) *ServiceContext {
2025-01-21 16:48:55 +08:00
svc := &ServiceContext{
2025-01-20 10:10:08 +08:00
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),
}
2025-01-21 16:48:55 +08:00
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
2025-01-20 10:10:08 +08:00
}
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"))
}