bindbox-game/internal/api/wechat/mini_template.go
邹方成 5717c97e7e feat(微信): 添加获取微信小程序模板ID接口
新增/api/wechat/template接口,用于根据AppID获取微信小程序的模板ID
添加相关请求和响应数据结构定义
实现模板ID查询逻辑,包括权限验证和错误处理
更新swagger文档
2025-10-29 22:23:35 +08:00

103 lines
2.5 KiB
Go

package wechat
import (
"fmt"
"net/http"
"mini-chat/internal/code"
"mini-chat/internal/pkg/core"
"mini-chat/internal/pkg/validation"
"gorm.io/gorm"
)
type templateRequest struct {
AppID string `json:"app_id" binding:"required"` // 微信小程序 AppID
}
type templateResponse struct {
Success bool `json:"success"`
Message string `json:"message"`
AppID string `json:"app_id"` // 小程序 AppID
TemplateID string `json:"template_id"` // 模板 ID
}
// GetTemplate 获取微信小程序模板ID
// @Summary 获取微信小程序模板ID
// @Description 根据 AppID 获取微信小程序的模板ID
// @Tags 微信
// @Accept json
// @Produce json
// @Param request body templateRequest true "请求参数"
// @Success 200 {object} templateResponse
// @Failure 400 {object} code.Failure
// @Failure 404 {object} code.Failure
// @Failure 500 {object} code.Failure
// @Router /api/wechat/template [post]
func (h *handler) GetTemplate() core.HandlerFunc {
return func(ctx core.Context) {
req := new(templateRequest)
res := new(templateResponse)
if err := ctx.ShouldBindJSON(req); err != nil {
ctx.AbortWithError(core.Error(
http.StatusBadRequest,
code.ParamBindError,
validation.Error(err),
))
return
}
// 根据 AppID 查询小程序信息
miniProgram, err := h.readDB.MiniProgram.WithContext(ctx.RequestContext()).
Where(h.readDB.MiniProgram.AppID.Eq(req.AppID)).
First()
if err != nil {
if err == gorm.ErrRecordNotFound {
ctx.AbortWithError(core.Error(
http.StatusNotFound,
code.ServerError,
fmt.Sprintf("未找到 AppID 为 %s 的小程序", req.AppID),
))
return
}
h.logger.Error(fmt.Sprintf("查询小程序信息失败: %s", err.Error()))
ctx.AbortWithError(core.Error(
http.StatusInternalServerError,
code.ServerError,
"查询小程序信息失败",
))
return
}
// 检查是否有权限访问该小程序
if ctx.SessionUserInfo().IsSuper != 1 && miniProgram.AdminID != ctx.SessionUserInfo().Id {
ctx.AbortWithError(core.Error(
http.StatusForbidden,
code.ServerError,
"无权限访问该小程序",
))
return
}
// 检查模板ID是否存在
if miniProgram.TemplateID == "" {
ctx.AbortWithError(core.Error(
http.StatusNotFound,
code.ServerError,
"该小程序未配置模板ID",
))
return
}
res.Success = true
res.Message = "获取模板ID成功"
res.AppID = miniProgram.AppID
res.TemplateID = miniProgram.TemplateID
ctx.Payload(res)
}
}