new
This commit is contained in:
136
app/main/api/internal/logic/user/wxh5authlogic.go
Normal file
136
app/main/api/internal/logic/user/wxh5authlogic.go
Normal file
@@ -0,0 +1,136 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
"tyc-server/app/main/model"
|
||||
jwtx "tyc-server/common/jwt"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/zeromicro/go-zero/core/stores/sqlx"
|
||||
|
||||
"tyc-server/app/main/api/internal/svc"
|
||||
"tyc-server/app/main/api/internal/types"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
type WxH5AuthLogic struct {
|
||||
logx.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewWxH5AuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WxH5AuthLogic {
|
||||
return &WxH5AuthLogic{
|
||||
Logger: logx.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *WxH5AuthLogic) WxH5Auth(req *types.WXH5AuthReq) (resp *types.WXH5AuthResp, err error) {
|
||||
// Step 1: 使用code获取access_token
|
||||
accessTokenResp, err := GetAccessToken(req.Code)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "获取access_token失败")
|
||||
}
|
||||
|
||||
// Step 2: 查找用户授权信息
|
||||
userAuth, findErr := l.svcCtx.UserAuthModel.FindOneByAuthTypeAuthKey(l.ctx, accessTokenResp.Openid, "h5-weixin")
|
||||
if findErr != nil && !errors.Is(findErr, model.ErrNotFound) {
|
||||
return nil, errors.Wrapf(findErr, "查询用户授权失败,openid: %s", accessTokenResp.Openid)
|
||||
}
|
||||
|
||||
// Step 3: 查找或创建用户
|
||||
var user *model.User
|
||||
if userAuth != nil {
|
||||
// 授权信息存在,查找用户
|
||||
userModel, findUserErr := l.svcCtx.UserModel.FindOne(l.ctx, userAuth.UserId)
|
||||
if findUserErr != nil {
|
||||
return nil, errors.Wrapf(findUserErr, "查询用户失败,userId: %d", userAuth.UserId)
|
||||
}
|
||||
user = userModel
|
||||
} else {
|
||||
// 授权信息不存在,创建新用户
|
||||
user = &model.User{}
|
||||
if transErr := l.svcCtx.UserModel.Trans(l.ctx, func(context context.Context, session sqlx.Session) error {
|
||||
// 插入数据库
|
||||
insertResult, insertErr := l.svcCtx.UserModel.Insert(l.ctx, session, user)
|
||||
if insertErr != nil {
|
||||
return errors.Wrapf(insertErr, "创建新用户失败,openid: %s", accessTokenResp.Openid)
|
||||
}
|
||||
// 获取插入后生成的 user.Id
|
||||
lastInsertId, lastInsertIdErr := insertResult.LastInsertId()
|
||||
if lastInsertIdErr != nil {
|
||||
return errors.Wrapf(lastInsertIdErr, "获取新用户ID失败,openid: %s", accessTokenResp.Openid)
|
||||
}
|
||||
user.Id = lastInsertId
|
||||
// 创建用户授权信息
|
||||
userAuth = &model.UserAuth{
|
||||
UserId: user.Id,
|
||||
AuthKey: accessTokenResp.Openid,
|
||||
AuthType: "mp-weixin", // 微信小程序
|
||||
}
|
||||
if _, insertUserAuthErr := l.svcCtx.UserAuthModel.Insert(l.ctx, session, userAuth); insertUserAuthErr != nil {
|
||||
return errors.Wrapf(insertUserAuthErr, "创建用户授权失败,openid: %s", accessTokenResp.Openid)
|
||||
}
|
||||
return nil
|
||||
}); transErr != nil {
|
||||
return nil, transErr
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Step 4: 生成JWT Token
|
||||
token, genErr := jwtx.GenerateJwtToken(user.Id, l.svcCtx.Config.JwtAuth.AccessSecret, l.svcCtx.Config.JwtAuth.AccessExpire)
|
||||
if genErr != nil {
|
||||
return nil, errors.Wrap(genErr, "生成JWT token失败")
|
||||
}
|
||||
|
||||
now := time.Now().Unix()
|
||||
return &types.WXH5AuthResp{
|
||||
AccessToken: token,
|
||||
AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
|
||||
RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type AccessTokenResp struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
Openid string `json:"openid"`
|
||||
}
|
||||
|
||||
// GetAccessToken 通过code获取access_token
|
||||
func GetAccessToken(code string) (*AccessTokenResp, error) {
|
||||
appID := "wxd1554b7a57cecc9e"
|
||||
appSecret := "fb8026c0bc66625b580453300d4b43db"
|
||||
|
||||
url := fmt.Sprintf("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", appID, appSecret, code)
|
||||
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "获取access_token失败")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "读取access_token响应失败")
|
||||
}
|
||||
|
||||
var accessTokenResp AccessTokenResp
|
||||
if err := json.Unmarshal(body, &accessTokenResp); err != nil {
|
||||
return nil, errors.Wrap(err, "解析access_token响应失败")
|
||||
}
|
||||
|
||||
if accessTokenResp.AccessToken == "" {
|
||||
return nil, errors.New("获取access_token失败")
|
||||
}
|
||||
|
||||
return &accessTokenResp, nil
|
||||
}
|
||||
Reference in New Issue
Block a user