package wechat import ( "context" "errors" "gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/internal/app_api_helper" "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 WechatCode2UserIdLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } func NewWechatCode2UserIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WechatCode2UserIdLogic { app_api_helper.Init(ctx, svcCtx.AppAccount) return &WechatCode2UserIdLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *WechatCode2UserIdLogic) WechatCode2UserId(req *types.WechatCode2TokenRequest) (resp *types.Auth, err error) { resp = new(types.Auth) wechatCli, err := app_api_helper.WechatCli.GetWechatOpenApi(req.AppId) if err != nil { return } res, err := wechatCli.GetAuth().Code2Session(req.Code) if err != nil { return } if res.ErrCode != 0 { err = errors.New(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, } 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 }