105 lines
2.4 KiB
Go
105 lines
2.4 KiB
Go
|
package controller
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"errors"
|
||
|
"gitea.youtukeji.com.cn/xiabin/douyin-openapi/cache"
|
||
|
"github.com/gin-gonic/gin"
|
||
|
"go.uber.org/zap"
|
||
|
"net/http"
|
||
|
"youtu_ecpm/api/gin/service"
|
||
|
"youtu_ecpm/dao/model"
|
||
|
"youtu_ecpm/dao/query"
|
||
|
"youtu_ecpm/pkg/wechat_api"
|
||
|
)
|
||
|
|
||
|
type WechatOpenApiController struct {
|
||
|
*Controller
|
||
|
logger *zap.Logger
|
||
|
wechatCli *wechat_api.WechatApi
|
||
|
appUser *service.AppUserInfo
|
||
|
appAccount *service.AppAccount
|
||
|
}
|
||
|
|
||
|
// NewWechatOpenApiController 实例化控制器
|
||
|
// logger: 日志
|
||
|
// q: 数据库
|
||
|
// 将数据库中的数据存储到内存中
|
||
|
func NewWechatOpenApiController(logger *zap.Logger, q *query.Query) *WechatOpenApiController {
|
||
|
// 创建抖音客户端
|
||
|
weChatApiCli := wechat_api.NewWechatOpenApiClient()
|
||
|
// 获取数据库中的数据
|
||
|
ctx := context.Background()
|
||
|
|
||
|
account := q.AppAccount
|
||
|
cfg := q.DouyinEcpmConfig
|
||
|
|
||
|
//获取抖音配置
|
||
|
result, err := account.WithContext(ctx).
|
||
|
Select(
|
||
|
account.AppID,
|
||
|
account.Secret,
|
||
|
).Where(account.Type.Eq(1)).
|
||
|
LeftJoin(cfg, cfg.AppAccountID.EqCol(account.ID)).
|
||
|
Find()
|
||
|
|
||
|
if err != nil {
|
||
|
logger.Sugar().Error("获取数据失败", err)
|
||
|
}
|
||
|
// 将数据库中的数据存储到内存中
|
||
|
for _, v := range result {
|
||
|
weChatApiCli.NewAndStoreWechatOpenApi(v.AppID, v.Secret, cache.NewMemory())
|
||
|
}
|
||
|
return &WechatOpenApiController{
|
||
|
logger: logger,
|
||
|
wechatCli: weChatApiCli,
|
||
|
appUser: service.NewAppUserInfo(q),
|
||
|
appAccount: service.NewAppAccount(q),
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Code2OpenId 获取openId
|
||
|
func (ctl *WechatOpenApiController) Code2OpenId(c *gin.Context) {
|
||
|
code := c.Query("code")
|
||
|
appId := c.Query("app_id")
|
||
|
|
||
|
wechatCli, err := ctl.wechatCli.GetWechatOpenApi(appId)
|
||
|
if err != nil {
|
||
|
ctl.logger.Sugar().Error("获取小程序登录地址失败", err)
|
||
|
ctl.ResponseErr(c, err)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
res, err := wechatCli.GetAuth().Code2Session(code)
|
||
|
if err != nil {
|
||
|
ctl.logger.Sugar().Error("获取小程序登录地址失败", err)
|
||
|
ctl.ResponseErr(c, err)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
if res.ErrCode != 0 {
|
||
|
ctl.logger.Sugar().Errorf("Code2Session 错误,res : %+v", res)
|
||
|
ctl.ResponseErr(c, errors.New(res.ErrMsg))
|
||
|
return
|
||
|
}
|
||
|
|
||
|
accountId, err := ctl.appAccount.GetAppAccountIdByAppId(c, appId)
|
||
|
if err != nil {
|
||
|
ctl.ResponseErr(c, err)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
err = ctl.appUser.SaveUserInfoByRes(c, &model.AppUserInfo{
|
||
|
AppAccountID: accountId,
|
||
|
Openid: res.OpenID,
|
||
|
Unionid: res.UnionID,
|
||
|
})
|
||
|
|
||
|
if err != nil {
|
||
|
ctl.ResponseErr(c, err)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
c.String(http.StatusOK, res.OpenID)
|
||
|
}
|