80 lines
1.8 KiB
Go
80 lines
1.8 KiB
Go
package douyin
|
|
|
|
import (
|
|
"context"
|
|
"github.com/golang-jwt/jwt/v4"
|
|
"time"
|
|
"youtu_server/game_open_api/internal/app_api_helper"
|
|
"youtu_server/game_open_api/model"
|
|
|
|
"youtu_server/game_open_api/internal/svc"
|
|
"youtu_server/game_open_api/internal/types"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
)
|
|
|
|
type DouyinCode2tokenLogic struct {
|
|
logx.Logger
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
}
|
|
|
|
func NewDouyinCode2tokenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DouyinCode2tokenLogic {
|
|
app_api_helper.Init(ctx, svcCtx.AppAccount)
|
|
return &DouyinCode2tokenLogic{
|
|
Logger: logx.WithContext(ctx),
|
|
ctx: ctx,
|
|
svcCtx: svcCtx,
|
|
}
|
|
}
|
|
|
|
func (l *DouyinCode2tokenLogic) DouyinCode2token(req *types.DouyinCode2TokenRequest) (resp *types.Auth, err error) {
|
|
resp = new(types.Auth)
|
|
|
|
douyinCli, err := app_api_helper.DouyinCli.GetDouYinOpenApi(req.AppId)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
res, err := douyinCli.Api.Code2Session(req.Code, req.AnonymousCode)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
if res.Errcode != 0 {
|
|
resp.Message = res.Errmsg
|
|
return
|
|
}
|
|
|
|
accountId, err := l.svcCtx.AppAccount.FindIdByAppId(l.ctx, req.AppId)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
aui := &model.AppUser{
|
|
AppAccountId: accountId,
|
|
Openid: res.Openid,
|
|
Unionid: res.Unionid,
|
|
AnonymousOpenid: res.AnonymousOpenid,
|
|
}
|
|
err = l.svcCtx.AppUser.FindOrCreate(l.ctx, aui)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
claims := make(jwt.MapClaims)
|
|
claims["exp"] = time.Now().Unix() + l.svcCtx.Config.Auth.AccessExpire
|
|
claims["iat"] = l.svcCtx.Config.Auth.AccessExpire
|
|
|
|
claims["payload"] = &svc.AccessToken{
|
|
AppId: accountId,
|
|
UserId: aui.Id,
|
|
AppIdStr: req.AppId,
|
|
OpenId: res.Openid,
|
|
}
|
|
token := jwt.New(jwt.SigningMethodHS256)
|
|
token.Claims = claims
|
|
resp.Token, err = token.SignedString([]byte(l.svcCtx.Config.Auth.AccessSecret))
|
|
return
|
|
}
|