2025-01-20 01:55:44 +08:00
|
|
|
package wechat
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
2025-01-21 10:38:27 +08:00
|
|
|
"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"
|
2025-01-20 10:10:08 +08:00
|
|
|
"github.com/golang-jwt/jwt/v4"
|
|
|
|
"time"
|
2025-01-20 01:55:44 +08:00
|
|
|
|
2025-01-21 10:38:27 +08:00
|
|
|
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/internal/svc"
|
|
|
|
"gitea.youtukeji.com.cn/xiabin/youtu_server/game_open_api/internal/types"
|
2025-01-20 01:55:44 +08:00
|
|
|
|
|
|
|
"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,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2025-01-20 18:20:25 +08:00
|
|
|
func (l *WechatCode2UserIdLogic) WechatCode2UserId(req *types.WechatCode2TokenRequest) (resp *types.Auth, err error) {
|
2025-01-20 14:37:14 +08:00
|
|
|
resp = new(types.Auth)
|
2025-01-20 01:55:44 +08:00
|
|
|
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,
|
|
|
|
}
|
|
|
|
|
2025-01-20 14:37:14 +08:00
|
|
|
err = l.svcCtx.AppUser.FindOrCreate(l.ctx, aui)
|
2025-01-20 10:10:08 +08:00
|
|
|
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
|
2025-01-20 14:37:14 +08:00
|
|
|
resp.Token, err = token.SignedString([]byte(l.svcCtx.Config.Auth.AccessSecret))
|
2025-01-20 01:55:44 +08:00
|
|
|
|
|
|
|
return
|
|
|
|
}
|