57 lines
1.4 KiB
Go
Executable File
57 lines
1.4 KiB
Go
Executable File
package common
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"bindbox-game/configs"
|
|
"bindbox-game/internal/pkg/core"
|
|
"bindbox-game/internal/pkg/wechat"
|
|
"bindbox-game/internal/service/sysconfig"
|
|
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
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
|
|
}
|
|
|
|
// 使用动态配置
|
|
wxcfg := &wechat.WechatConfig{}
|
|
if dc := sysconfig.GetDynamicConfig(); dc != nil {
|
|
c := dc.GetWechat(ctx.RequestContext().Context)
|
|
wxcfg.AppID = c.AppID
|
|
wxcfg.AppSecret = c.AppSecret
|
|
} else {
|
|
cfg := configs.Get()
|
|
wxcfg.AppID = cfg.Wechat.AppID
|
|
wxcfg.AppSecret = cfg.Wechat.AppSecret
|
|
}
|
|
|
|
h.logger.Info("GetOpenID Config", zap.String("AppID", wxcfg.AppID), zap.String("AppSecret", wxcfg.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,
|
|
})
|
|
}
|
|
}
|