43 lines
1012 B
Go

package common
import (
"net/http"
"bindbox-game/configs"
"bindbox-game/internal/pkg/core"
"bindbox-game/internal/pkg/wechat"
)
type openidRequest struct {
Code string `json:"code" binding:"required"`
}
type openidResponse struct {
OpenID string `json:"openid"`
UnionID string `json:"unionid"`
}
// GetOpenID 通过 code 获取 openid (不涉及登录)
func (h *handler) GetOpenID() core.HandlerFunc {
return func(ctx core.Context) {
req := new(openidRequest)
if err := ctx.ShouldBindJSON(req); err != nil {
ctx.AbortWithError(core.Error(http.StatusBadRequest, 10001, err.Error()))
return
}
cfg := configs.Get()
wxcfg := &wechat.WechatConfig{AppID: cfg.Wechat.AppID, AppSecret: cfg.Wechat.AppSecret}
c2s, err := wechat.Code2Session(ctx.RequestContext().Context, wxcfg, req.Code)
if err != nil {
ctx.AbortWithError(core.Error(http.StatusBadRequest, 10006, err.Error()))
return
}
ctx.Payload(&openidResponse{
OpenID: c2s.OpenID,
UnionID: c2s.UnionID,
})
}
}