PaymentCenter/app/http/controllers/api.go

127 lines
2.9 KiB
Go

package controllers
import (
"PaymentCenter/app/constants/common"
"PaymentCenter/app/constants/errorcode"
"PaymentCenter/app/http/entities/front"
"PaymentCenter/app/models/orderrequestlogmodel"
"PaymentCenter/app/services"
"PaymentCenter/app/services/thirdpay/api"
"PaymentCenter/app/utils"
"PaymentCenter/config"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
func ApiRes(c *gin.Context, data interface{}, code int, msg ...string) {
var logId int64
var responseData interface{}
var message string
originData := "{}"
appCheckInfo := GetAppCheckInfo(c).(*services.AppCheck)
// 空数据
if utils.IsNil(data) {
data = struct{}{}
}
// 获取错误信息
if len(msg) > 0 {
message = msg[0]
} else {
message = errorcode.GetMsg(code, "")
}
// 获取日志ID
log, exists := GetApiLogId(c)
if exists {
logId = log.(int64)
}
// 加密数据
if code == errorcode.Success {
if apiRsp, ok := data.(front.ApiResponse); ok {
apiRsp.Order, code = api.EnCrypt(appCheckInfo.App, apiRsp.Order)
if code != errorcode.Success {
message = errorcode.GetMsg(code, "")
}
responseData = apiRsp
} else {
responseData = data
}
}
if code == errorcode.Success {
ApiSuccess(c, responseData, logId, message)
b, _ := json.Marshal(data)
originData = string(b)
} else {
ApiError(c, code, logId, message)
originData = fmt.Sprintf("{\"code\":%d,\"message\":\"%s\"}", code, message)
}
// 记录日志
if logId > 0 {
services.RequestLogUpdate(&orderrequestlogmodel.OrderRequestLog{
Id: logId,
AppId: appCheckInfo.AppId,
OutTradeNo: GetOutTradeNo(c),
MerchantResponse: originData,
Status: common.STATUS_DISABLED,
})
}
}
func ApiSuccess(c *gin.Context, data interface{}, log_id int64, messageSlice ...string) {
var message string
if len(messageSlice) > 0 {
message = messageSlice[0]
}
if message == "" {
message = errorcode.GetMsg(errorcode.Success, c.GetHeader("local"))
}
if config.GetConf().Env == "production" {
c.String(http.StatusOK, EncriptJson(gin.H{
"code": errorcode.Success,
"message": message,
"data": data,
"trace_id": log_id,
}))
} else {
c.JSON(http.StatusOK, gin.H{
"code": errorcode.Success,
"message": message,
"data": data,
"trace_id": log_id,
})
}
c.Abort()
}
/**
* 失败时返回
*/
func ApiError(c *gin.Context, code int, log_id int64, msg ...string) {
message := ""
if len(msg) > 0 {
message = msg[0]
} else {
message = errorcode.GetMsg(code, "")
}
if config.GetConf().Env == "production" {
c.String(http.StatusOK, EncriptJson(gin.H{
"code": code,
"message": message,
"data": make(map[string]string),
"trace_id": log_id,
}))
} else {
c.JSON(http.StatusOK, gin.H{
"code": code,
"message": message,
"data": make(map[string]string),
"trace_id": log_id,
})
}
c.Abort()
}