Files
wx_service/internal/handler/auth_handler.go
T
2025-12-29 09:32:44 +00:00

77 lines
1.9 KiB
Go

package handler
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"wx_service/internal/model"
"wx_service/internal/service"
)
type AuthHandler struct {
authService *service.AuthService
}
func NewAuthHandler(authService *service.AuthService) *AuthHandler {
return &AuthHandler{
authService: authService,
}
}
type weChatLoginRequest struct {
Code string `json:"code" binding:"required"`
NickName string `json:"nickname"`
AvatarURL string `json:"avatar_url"`
Gender *int `json:"gender"`
Phone string `json:"phone"`
}
func (h *AuthHandler) LoginWithWeChat(c *gin.Context) {
var req weChatLoginRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "invalid request payload"))
return
}
result, err := h.authService.LoginWithCode(c.Request.Context(), service.LoginRequest{
Code: req.Code,
NickName: req.NickName,
AvatarURL: req.AvatarURL,
Gender: req.Gender,
Phone: req.Phone,
})
if err != nil {
switch {
case errors.Is(err, service.ErrCodeRequired):
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "code is required"))
default:
var apiErr *service.WeChatError
if errors.As(err, &apiErr) {
c.JSON(http.StatusBadGateway, model.Error(http.StatusBadGateway, apiErr.Error()))
return
}
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "login failed"))
}
return
}
userPayload := gin.H{
"id": result.User.ID,
"open_id": result.User.OpenID,
"nickname": result.User.NickName,
"avatar_url": result.User.AvatarURL,
"gender": result.User.Gender,
"phone": result.User.Phone,
}
if result.User.UnionID != "" {
userPayload["union_id"] = result.User.UnionID
}
c.JSON(http.StatusOK, model.Success(gin.H{
"user": userPayload,
"session_key": result.SessionKey,
}))
}