youtu_ecpm/api/gin/controller/wechat_open_api.go

108 lines
2.6 KiB
Go
Raw Normal View History

2025-01-18 17:56:36 +08:00
package controller
import (
"context"
"errors"
"gitea.youtukeji.com.cn/xiabin/douyin-openapi/cache"
2025-01-20 00:11:11 +08:00
"gitea.youtukeji.com.cn/xiabin/youtu_ecpm/api/gin/service"
"gitea.youtukeji.com.cn/xiabin/youtu_ecpm/dao/model"
"gitea.youtukeji.com.cn/xiabin/youtu_ecpm/dao/query"
"gitea.youtukeji.com.cn/xiabin/youtu_ecpm/pkg/wechat_api"
2025-01-18 17:56:36 +08:00
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"net/http"
)
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
}
2025-01-18 19:02:58 +08:00
aui := &model.AppUserInfo{
2025-01-18 17:56:36 +08:00
AppAccountID: accountId,
Openid: res.OpenID,
Unionid: res.UnionID,
2025-01-18 19:02:58 +08:00
}
err = ctl.appUser.SaveUserInfoByRes(c, aui)
2025-01-18 17:56:36 +08:00
if err != nil {
ctl.ResponseErr(c, err)
return
}
2025-01-18 19:02:58 +08:00
c.JSON(http.StatusOK, gin.H{
"user_id": aui.ID,
})
2025-01-18 17:56:36 +08:00
}