package douyin import ( "context" "gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/model" "github.com/golang-jwt/jwt/v4" "time" "gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/internal/svc" "gitea.youtukeji.com.cn/xiabin/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 { 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 := l.svcCtx.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 }