xuzhiheng 4 年之前
父节点
当前提交
946234b101
共有 8 个文件被更改,包括 141 次插入12 次删除
  1. 22 0
      api/v1/projects.go
  2. 7 6
      model/response/response.go
  3. 15 0
      model/user.go
  4. 44 0
      service/callLog.go
  5. 37 0
      test/callLog/callLog_test.go
  6. 10 0
      utils/api_util.go
  7. 2 2
      utils/cost_by_account_balance.go
  8. 4 4
      utils/cost_by_left_num.go

+ 22 - 0
api/v1/projects.go

@@ -22,6 +22,7 @@ func ProjectApiRegister(router *gin.Engine) {
 		routerGroup.POST("/projectList", getProjectsList)
 		routerGroup.POST("/projectDetail", getProjectDetail)
 		routerGroup.POST("/projectListDetail", getProjectsListDetail)
+		routerGroup.POST("/callLog", callLog)
 	}
 }
 
@@ -88,3 +89,24 @@ func getProjectDetail(c *gin.Context) {
 		}, param, requestIP, false)
 	}
 }
+
+//调用日志
+func callLog(c *gin.Context) {
+	appID := c.PostForm("app_id")
+	startTime := c.PostForm("start_time")
+	endTime := c.PostForm("end_time")
+	datas := []map[string]interface{}{}
+	var err error
+	p := gin.H{
+		"appID":     appID,
+		"startTime": startTime,
+		"endTime":   endTime,
+	}
+	global.Logger.Info("api callLog:", zap.Any("param:", p))
+	datas, err = service.CallLog(appID, startTime, endTime)
+	if err == nil {
+		response.FailWithDetailed(response.SUCCESS, datas, "OK", c)
+	} else {
+		response.FailWithDetailed(response.QueryError, datas, "系统查询异常", c)
+	}
+}

+ 7 - 6
model/response/response.go

@@ -10,12 +10,12 @@ const (
 	ERROR   int = -1
 	SUCCESS int = 0
 	//服务级错误码
-	EmptyResult                  int = 201  //查询无结果
+	EmptyResult                  int = 201 //查询无结果
 	ParamError                   int = 202 //参数错误
-	ParamEmpty                       = 203  //参数为空
-	ParamLenInValid              int = 204  //参数长度小于4
-	Waiting                      int = 205  //等待处理中
-	MoreThanQueryDataNumberLimit int = 206  //请求数据的条数超过上限
+	ParamEmpty                       = 203 //参数为空
+	ParamLenInValid              int = 204 //参数长度小于4
+	Waiting                      int = 205 //等待处理中
+	MoreThanQueryDataNumberLimit int = 206 //请求数据的条数超过上限
 	LeftNumEmpty                     = 207 //余额不足
 	QueryError                   int = 299 //系统查询异常,请联系客服
 
@@ -28,13 +28,14 @@ const (
 
 	//105非法请求过多,请联系管理员
 	IpInvalid                       = 108 //被禁止的IP
-	MoreThanEveryDayQueryTimesLimit = 109  //请求超过每日系统限制
+	MoreThanEveryDayQueryTimesLimit = 109 //请求超过每日系统限制
 	//108当前相同查询连续出错,请等2小时后重试
 	InterfaceRightInvalid           = 110 //接口权限未开通
 	InterfaceExpired                = 111 //您的账号剩余使用量已过期
 	InterfaceDeleted                = 112 //接口已停用,请联系管理员
 	MoreThanEveryDayDataNumberLimit = 113 //请求超过每日调用总量限制
 	OtherError                      = 199 //系统未知错误,请联系技术客服
+	CallRate                        = 114 //调用频率超过系统设置
 )
 
 type Response struct {

+ 15 - 0
model/user.go

@@ -58,3 +58,18 @@ type UserBuyRecord struct {
 func (p *UserBuyRecord) TableName() string {
 	return "user_buy_record"
 }
+
+type UserCallRecord struct {
+	ID            int       `json:"id" gorm:"primaryKey"`
+	AppID         string    `json:"app_id"`
+	UserProductId int       `json:"user_product_id"`
+	Status        int       `json:"status"`
+	Ip            string    `json:"ip"`
+	Param         string    `json:"param"`
+	OrderCode     string    `json:"order_code"`
+	CreateAt      time.Time `json:"-" gorm:"autoCreateTime"`
+}
+
+func (p *UserCallRecord) TableName() string {
+	return "user_call_record"
+}

+ 44 - 0
service/callLog.go

@@ -0,0 +1,44 @@
+package service
+
+import (
+	"log"
+	"sfis/db"
+	"sfis/model"
+	"strings"
+	"time"
+)
+
+func CallLog(appid, startTime, endTime string) ([]map[string]interface{}, error) {
+	key := []string{}
+	param := []interface{}{}
+	datas := []map[string]interface{}{}
+	if startTime != "" {
+		key = append(key, "create_at >= ?")
+		param = append(param, startTime+" 00:00:00")
+	}
+	if endTime != "" {
+		key = append(key, "create_at <= ?")
+		param = append(param, endTime+" 23:59:59")
+	} else {
+		key = append(key, "create_at <= ?")
+		param = append(param, time.Now().Local().Format("2006-01-02 15:04:05"))
+	}
+	whereSql := strings.Join(key, " and ")
+	log.Println("whereSql", whereSql)
+	userCallRecord := []model.UserCallRecord{}
+	err := db.GetSFISDB().Where(whereSql, param...).Where("app_id = ? ", appid).Find(&userCallRecord).Error
+	if err != nil {
+		return nil, err
+	} else {
+		for _, v := range userCallRecord {
+			dataMap := map[string]interface{}{
+				"app_id":     v.AppID,
+				"invok_time": v.CreateAt.Local().Format("2006-01-02 15:04:05"),
+				"ip":         v.Ip,
+				//TODO
+			}
+			datas = append(datas, dataMap)
+		}
+	}
+	return datas, nil
+}

+ 37 - 0
test/callLog/callLog_test.go

@@ -0,0 +1,37 @@
+package userRecharge
+
+import (
+	"fmt"
+	"log"
+	"net/url"
+	"sfbase/utils"
+	"testing"
+	"time"
+)
+
+var (
+	apiurl = "http://127.0.0.1:8080/sfis/api/v1/callLog"
+)
+
+func Test_Project(t *testing.T) {
+	getData()
+}
+
+func getData() {
+	appID := "sfGAhYRQMABAYHAAsBJywr"
+	secretKey := "8706384T"
+	startTime := "2021-01-14"
+	endTime := "2021-01-18"
+	data := make(url.Values)
+	data["end_time"] = []string{endTime}
+	data["start_time"] = []string{startTime}
+	data["app_id"] = []string{appID}
+	now := time.Now().Unix()
+	log.Println("now", now)
+	log.Println("token", utils.MD5(fmt.Sprintf("%s%d%s", appID, now, secretKey)))
+	bs, _ := utils.HttpPostForm(apiurl, map[string]string{
+		"token":     utils.MD5(fmt.Sprintf("%s%d%s", appID, now, secretKey)),
+		"timestamp": fmt.Sprint(now),
+	}, data)
+	log.Print("data", string(bs))
+}

+ 10 - 0
utils/api_util.go

@@ -1,6 +1,7 @@
 package utils
 
 import (
+	"sfbase/core"
 	// "context"
 	"fmt"
 	"log"
@@ -60,6 +61,12 @@ func Check(appID string, productID int, c *gin.Context, getData func() ([]map[st
 			redis.Put("limit", limittodaykey, 0, int(max-now))
 		}
 	}
+	//
+	limitrate := fmt.Sprintf("limitrate_%d_%s", userProduct.ProductID, userProduct.AppID)
+	Exists, _ := redis.Exists("limit", limitrate)
+	if Exists {
+		response.FailWithDetailed(response.CallRate, nil, "请求频率过快,请稍后重试", c)
+	}
 	//2.2 取用户(产品余量|钱包账户余额)校验-必须加锁
 	costModel := userProduct.CostModel //扣费模式 0扣余量,1-扣余额
 	product := GetProductByID(productID)
@@ -90,7 +97,10 @@ func Check(appID string, productID int, c *gin.Context, getData func() ([]map[st
 			"create_at":       time.Now().Unix(),
 		})
 		limittodaykey := fmt.Sprintf("limittoday_%d_%d_%s", time.Now().Day(), userProduct.ProductID, userProduct.AppID)
+		limitrate := fmt.Sprintf("limitrate_%d_%s", userProduct.ProductID, userProduct.AppID)
+		rateTime := core.GetIntConf("base.session.interface_call_rate")
 		redis.Incr("limit", limittodaykey)
+		redis.Put("limit", limitrate, 1, rateTime)
 		if !concurrentTest {
 			response.FailWithDetailed(response.SUCCESS, datas, "OK", c)
 		}

+ 2 - 2
utils/cost_by_account_balance.go

@@ -100,14 +100,14 @@ func afterCheck(dataLen, payMoney int, userProduct *model.UserProduct, statusCod
 			return err
 		}
 		//生调用记录
-		err = tx.Exec("insert into user_call_record (app_id,user_product_id,status,ip,param,order_code,create_at) values (?,?,?,?,?,?,?)", appID, userProductID, statusCode, ip, param, orderCode, nowStr).Error
+		err = tx.Exec("insert into user_call_record (app_id,product_id,user_product_id,status,ip,param,order_code,create_at) values (?,?,?,?,?,?,?,?)", appID, productID, userProductID, statusCode, ip, param, orderCode, nowStr).Error
 		if err != nil {
 			log.Printf("appID:[%s],productID:[%d] execute insert into user_call_record error:[%v]", appID, productID, err)
 			tx.Rollback()
 			return err
 		}
 		//生订单
-		err = tx.Exec("insert into interface_order (order_code,app_id,user_product_id,`before`,`after`,cost_model,trade_num,create_at) values (?,?,?,?,?,?,?,?)", orderCode, appID, userProductID, orderBefore, orderAfter, 1, payMoney, nowStr).Error
+		err = tx.Exec("insert into interface_order (order_code,app_id,product_id,user_product_id,`before`,`after`,cost_model,trade_num,create_at) values (?,?,?,?,?,?,?,?,?)", orderCode, appID, productID, userProductID, orderBefore, orderAfter, 1, payMoney, nowStr).Error
 		if err != nil {
 			log.Printf("appID:[%s],productID:[%d] execute insert into interface_order error:[%v]", appID, productID, err)
 			tx.Rollback()

+ 4 - 4
utils/cost_by_left_num.go

@@ -101,14 +101,14 @@ func after(productType int, dataLen int, userProduct *model.UserProduct, statusC
 				return err
 			}
 			//生调用记录
-			err = tx.Exec("insert into user_call_record (app_id,user_product_id,status,ip,param,order_code,create_at) values (?,?,?,?,?,?,?)", appID, userProductID, statusCode, ip, param, orderCode, nowStr).Error
+			err = tx.Exec("insert into user_call_record (app_id,product_id,user_product_id,status,ip,param,order_code,create_at) values (?,?,?,?,?,?,?,?)", appID, productID, userProductID, statusCode, ip, param, orderCode, nowStr).Error
 			if err != nil {
 				log.Printf("appID:[%s],productID:[%d] execute insert into user_call_record error:[%v]", appID, productID, err)
 				tx.Rollback()
 				return err
 			}
 			//生订单
-			err = tx.Exec("insert into interface_order (order_code,app_id,user_product_id,`before`,`after`,cost_model,trade_num,create_at) values (?,?,?,?,?,?,?,?)", orderCode, appID, userProductID, orderBefore, orderAfter, 0, 1, nowStr).Error
+			err = tx.Exec("insert into interface_order (order_code,app_id,product_id,user_product_id,`before`,`after`,cost_model,trade_num,create_at) values (?,?,?,?,?,?,?,?,?)", orderCode, appID, productID, userProductID, orderBefore, orderAfter, 0, 1, nowStr).Error
 			if err != nil {
 				log.Printf("appID:[%s],productID:[%d] execute insert into interface_order error:[%v]", appID, productID, err)
 				tx.Rollback()
@@ -131,14 +131,14 @@ func after(productType int, dataLen int, userProduct *model.UserProduct, statusC
 				return err
 			}
 			//生调用记录
-			err = tx.Exec("insert into user_call_record (app_id,user_product_id,status,ip,param,order_code,create_at) values (?,?,?,?,?,?,?)", appID, userProductID, statusCode, ip, param, orderCode, nowStr).Error
+			err = tx.Exec("insert into user_call_record (app_id,product_id,user_product_id,status,ip,param,order_code,create_at) values (?,?,?,?,?,?,?,?)", appID, productID, userProductID, statusCode, ip, param, orderCode, nowStr).Error
 			if err != nil {
 				log.Printf("appID:[%s],productID:[%d] execute insert into user_call_record error:[%v]", appID, productID, err)
 				tx.Rollback()
 				return err
 			}
 			//生订单
-			err = tx.Exec("insert into interface_order (order_code,app_id,user_product_id,`before`,`after`,cost_model,trade_num,create_at) values (?,?,?,?,?,?,?,?)", orderCode, appID, userProductID, orderBefore, orderAfter, 0, dataLen, nowStr).Error
+			err = tx.Exec("insert into interface_order (order_code,app_id,product_id,user_product_id,`before`,`after`,cost_model,trade_num,create_at) values (?,?,?,?,?,?,?,?,?)", orderCode, appID, productID, userProductID, orderBefore, orderAfter, 0, dataLen, nowStr).Error
 			if err != nil {
 				log.Printf("appID:[%s],productID:[%d] execute insert into interface_order error:[%v]", appID, productID, err)
 				tx.Rollback()