youtu_ecpm/api/gin/controller/douyin_open_api.go
2025-01-15 14:44:48 +08:00

117 lines
2.9 KiB
Go

package controller
import (
"context"
"gitea.youtukeji.com.cn/xiabin/douyin-openapi/cache"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"net/http"
"time"
"youtu_ecpm/dao/query"
"youtu_ecpm/pkg/douyinapi"
)
type DouyinOpenApiController struct {
logger *zap.Logger
douyinCli *douyinapi.DouYinOpenApiClient
q *query.Query
}
// NewDouyinOpenApiController 实例化控制器
// logger: 日志
// q: 数据库
// 将数据库中的数据存储到内存中
func NewDouyinOpenApiController(logger *zap.Logger, q *query.Query) *DouyinOpenApiController {
// 创建抖音客户端
douyinCli := douyinapi.NewDouYinOpenApiClient()
// 获取数据库中的数据
list, err := q.Douyin.WithContext(context.Background()).Find()
if err != nil {
logger.Sugar().Error("获取数据失败", err)
}
// 将数据库中的数据存储到内存中
for _, v := range list {
douyinCli.NewAndStoreDouYinOpenApi(v.AppID, v.Secret, v.EcpmValue, v.EcpmView, cache.NewMemory())
}
return &DouyinOpenApiController{
logger: logger,
douyinCli: douyinCli,
}
}
// GetEcpm 获取ECPM,返回true或false
func (ctl *DouyinOpenApiController) GetEcpm(c *gin.Context) {
var req struct {
AppId string `json:"app_id" form:"app_id"`
OpenId string `json:"open_id" form:"open_id"`
}
if err := c.ShouldBind(&req); err != nil {
c.JSON(http.StatusOK, false)
return
}
res, err := ctl.douyinCli.GetEcpmData(req.AppId, req.OpenId, time.Now().Format(time.DateOnly))
if err != nil {
ctl.logger.Sugar().Error("获取ecpm失败", err)
c.JSON(http.StatusOK, false)
return
}
ecpm, err := ctl.douyinCli.GetEcpm(res)
if err != nil {
ctl.logger.Sugar().Error("计算ecpm失败", err)
c.JSON(http.StatusOK, false)
return
}
// 打印日志
ctl.logger.Sugar().Info("ECPM:", zap.Float64("ecpm", ecpm))
// 判断是否满足ECPM值和浏览数
var result bool
if ecpm > float64(ctl.douyinCli.GetEcpmValue(req.AppId)) && len(res) > int(ctl.douyinCli.GetEcpmViewCount(req.AppId)) {
result = true
} else {
result = false
}
// 返回结果
c.JSON(http.StatusOK, result)
}
// Code2OpenId 获取openId
func (ctl *DouyinOpenApiController) Code2OpenId(c *gin.Context) {
code := c.Query("code")
anonymousOpenid := c.Query("anonymous_openid")
appId := c.Query("app_id")
douyinCli, err := ctl.douyinCli.GetDouYinOpenApi(appId)
if err != nil {
ctl.logger.Sugar().Error("获取小程序登录地址失败", err)
c.JSON(200, gin.H{
"code": 500,
"msg": err.Error(),
})
return
}
res, err := douyinCli.Api.Code2Session(code, anonymousOpenid)
if err != nil {
ctl.logger.Sugar().Error("获取小程序登录地址失败", err)
c.JSON(200, gin.H{
"code": 500,
"msg": http.StatusOK,
})
return
}
if res.Errcode != 0 {
ctl.logger.Sugar().Errorf("Code2Session 错误,res : %+v", res)
c.JSON(200, gin.H{
"code": 500,
"msg": http.StatusOK,
})
return
}
c.String(http.StatusOK, res.Openid)
}