Sure! Pl
This commit is contained in:
@@ -0,0 +1,111 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"wx_service/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var ErrCodeRequired = errors.New("code is required")
|
||||
|
||||
type AuthService struct {
|
||||
db *gorm.DB
|
||||
wechat *WeChatClient
|
||||
}
|
||||
|
||||
type LoginRequest struct {
|
||||
Code string
|
||||
NickName string
|
||||
AvatarURL string
|
||||
Gender *int
|
||||
Phone string
|
||||
}
|
||||
|
||||
type LoginResult struct {
|
||||
User *model.User
|
||||
SessionKey string
|
||||
}
|
||||
|
||||
func NewAuthService(db *gorm.DB, wechat *WeChatClient) *AuthService {
|
||||
return &AuthService{
|
||||
db: db,
|
||||
wechat: wechat,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AuthService) LoginWithCode(ctx context.Context, req LoginRequest) (*LoginResult, error) {
|
||||
if strings.TrimSpace(req.Code) == "" {
|
||||
return nil, ErrCodeRequired
|
||||
}
|
||||
|
||||
session, err := s.wechat.Code2Session(ctx, req.Code)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if session.OpenID == "" {
|
||||
return nil, fmt.Errorf("wechat response missing openid")
|
||||
}
|
||||
|
||||
tx := s.db.WithContext(ctx)
|
||||
var user model.User
|
||||
err = tx.Where("open_id = ?", session.OpenID).First(&user).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
user = model.User{
|
||||
OpenID: session.OpenID,
|
||||
UnionID: session.UnionID,
|
||||
NickName: req.NickName,
|
||||
AvatarURL: req.AvatarURL,
|
||||
Phone: req.Phone,
|
||||
SessionKey: session.SessionKey,
|
||||
}
|
||||
if req.Gender != nil {
|
||||
user.Gender = *req.Gender
|
||||
}
|
||||
if err := tx.Create(&user).Error; err != nil {
|
||||
return nil, fmt.Errorf("create user: %w", err)
|
||||
}
|
||||
} else if err != nil {
|
||||
return nil, fmt.Errorf("query user: %w", err)
|
||||
} else {
|
||||
updates := map[string]interface{}{
|
||||
"session_key": session.SessionKey,
|
||||
}
|
||||
if session.UnionID != "" && session.UnionID != user.UnionID {
|
||||
updates["union_id"] = session.UnionID
|
||||
user.UnionID = session.UnionID
|
||||
}
|
||||
if req.NickName != "" && req.NickName != user.NickName {
|
||||
updates["nick_name"] = req.NickName
|
||||
user.NickName = req.NickName
|
||||
}
|
||||
if req.AvatarURL != "" && req.AvatarURL != user.AvatarURL {
|
||||
updates["avatar_url"] = req.AvatarURL
|
||||
user.AvatarURL = req.AvatarURL
|
||||
}
|
||||
if req.Phone != "" && req.Phone != user.Phone {
|
||||
updates["phone"] = req.Phone
|
||||
user.Phone = req.Phone
|
||||
}
|
||||
if req.Gender != nil && user.Gender != *req.Gender {
|
||||
updates["gender"] = *req.Gender
|
||||
user.Gender = *req.Gender
|
||||
}
|
||||
if len(updates) > 0 {
|
||||
if err := tx.Model(&user).Updates(updates).Error; err != nil {
|
||||
return nil, fmt.Errorf("update user: %w", err)
|
||||
}
|
||||
}
|
||||
user.SessionKey = session.SessionKey
|
||||
}
|
||||
|
||||
result := &LoginResult{
|
||||
User: &user,
|
||||
SessionKey: session.SessionKey,
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
const weChatCode2SessionURL = "https://api.weixin.qq.com/sns/jscode2session"
|
||||
|
||||
// WeChatClient 调用微信接口获取 session/openid。
|
||||
type WeChatClient struct {
|
||||
appID string
|
||||
appSecret string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
type WeChatSession struct {
|
||||
OpenID string `json:"openid"`
|
||||
UnionID string `json:"unionid"`
|
||||
SessionKey string `json:"session_key"`
|
||||
}
|
||||
|
||||
type weChatSessionResponse struct {
|
||||
WeChatSession
|
||||
ErrCode int `json:"errcode"`
|
||||
ErrMsg string `json:"errmsg"`
|
||||
}
|
||||
|
||||
// WeChatError 表示微信接口级错误。
|
||||
type WeChatError struct {
|
||||
Code int
|
||||
Msg string
|
||||
}
|
||||
|
||||
func (e *WeChatError) Error() string {
|
||||
return fmt.Sprintf("wechat error: code=%d msg=%s", e.Code, e.Msg)
|
||||
}
|
||||
|
||||
func NewWeChatClient(appID, appSecret string, client *http.Client) *WeChatClient {
|
||||
if client == nil {
|
||||
client = &http.Client{
|
||||
Timeout: 5 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
return &WeChatClient{
|
||||
appID: appID,
|
||||
appSecret: appSecret,
|
||||
client: client,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *WeChatClient) Code2Session(ctx context.Context, code string) (*WeChatSession, error) {
|
||||
query := url.Values{}
|
||||
query.Set("appid", c.appID)
|
||||
query.Set("secret", c.appSecret)
|
||||
query.Set("js_code", code)
|
||||
query.Set("grant_type", "authorization_code")
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("%s?%s", weChatCode2SessionURL, query.Encode()), nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build wechat request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("call wechat api: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("wechat api unexpected status: %s", resp.Status)
|
||||
}
|
||||
|
||||
var raw weChatSessionResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&raw); err != nil {
|
||||
return nil, fmt.Errorf("decode wechat response: %w", err)
|
||||
}
|
||||
|
||||
if raw.ErrCode != 0 {
|
||||
return nil, &WeChatError{Code: raw.ErrCode, Msg: raw.ErrMsg}
|
||||
}
|
||||
|
||||
return &raw.WeChatSession, nil
|
||||
}
|
||||
Reference in New Issue
Block a user