Compare commits

..

No commits in common. "a54212d38c858f67a29b78b98e498ff16e8750a3" and "583aee88e285acb764779996091c299847eee97d" have entirely different histories.

29 changed files with 217 additions and 421 deletions

View File

@ -66,9 +66,6 @@ const (
OrderClosed = 1407 OrderClosed = 1407
OrderFailed = 1408 OrderFailed = 1408
OrderPayed = 1409 OrderPayed = 1409
RefundOrderNotFound = 1410
OrderStatusRefundNotSupport = 1411
//请求日志 //请求日志
RequestLogErrors = 1500 RequestLogErrors = 1500
RequestLogNotFound = 1501 RequestLogNotFound = 1501
@ -144,8 +141,7 @@ var MsgZH = map[int]string{
OrderFailed: "订单支付失败,请重新发起", OrderFailed: "订单支付失败,请重新发起",
OrderPayed: "订单已支付成功,请勿重复支付", OrderPayed: "订单已支付成功,请勿重复支付",
NotifySendFail: "回调发送失败", NotifySendFail: "回调发送失败",
RefundOrderNotFound: "退款订单未找到",
OrderStatusRefundNotSupport: "订单状态不支持退款",
PrePayFail: "预支付失败", PrePayFail: "预支付失败",
} }
var MsgMap map[string]map[int]string = map[string]map[int]string{"en": MsgZH} var MsgMap map[string]map[int]string = map[string]map[int]string{"en": MsgZH}

View File

@ -37,13 +37,3 @@ func (m *OrderRequestLogRepo) OrderRequestLogDelete(orderLog *orderrequestlogmod
func (m *OrderRequestLogRepo) OrderRequestLogUpdate(orderLog *orderrequestlogmodel.OrderRequestLog, conn builder.Cond, columns ...string) (int64, error) { func (m *OrderRequestLogRepo) OrderRequestLogUpdate(orderLog *orderrequestlogmodel.OrderRequestLog, conn builder.Cond, columns ...string) (int64, error) {
return m.repo.Where(conn).MustCols(columns...).Update(orderLog) return m.repo.Where(conn).MustCols(columns...).Update(orderLog)
} }
// 后台查询订单日志列表
func (m *OrderRequestLogRepo) OrderRequestLogBackendList(conn builder.Cond, pageFilter entities.PageRequest, orderLogList *[]orderrequestlogmodel.OrderRequestLog) (int64, error) {
repo := m.repo.Where(conn)
if pageFilter.Page > 0 {
repo = repo.Limit(pageFilter.PageSize, pageFilter.PageSize*(pageFilter.Page-1))
}
repo.Join("left", "orders", "orders.app_id = order_request_log.app_id and orders.out_trade_no = order_request_log.out_trade_no")
return repo.Desc("order_request_log.create_time").FindAndCount(orderLogList)
}

View File

@ -3,73 +3,45 @@ package controllers
import ( import (
"PaymentCenter/app/constants/common" "PaymentCenter/app/constants/common"
"PaymentCenter/app/constants/errorcode" "PaymentCenter/app/constants/errorcode"
"PaymentCenter/app/http/entities/front"
"PaymentCenter/app/models/orderrequestlogmodel" "PaymentCenter/app/models/orderrequestlogmodel"
"PaymentCenter/app/services" "PaymentCenter/app/services"
"PaymentCenter/app/services/thirdpay/api"
"PaymentCenter/app/utils" "PaymentCenter/app/utils"
"PaymentCenter/config" "PaymentCenter/config"
"encoding/json" "encoding/json"
"fmt"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"net/http" "net/http"
) )
func ApiRes(c *gin.Context, data interface{}, code int, msg ...string) { func ApiRes(c *gin.Context, data interface{}, code int, msg ...string) {
var logId int64 var log_id int64
var responseData interface{} message := ""
var message string
var appCheckInfo *services.AppCheck
originData := "{}"
appInfo := GetAppCheckInfo(c)
if appInfo != nil {
appCheckInfo = appInfo.(*services.AppCheck)
}
// 空数据
if utils.IsNil(data) { if utils.IsNil(data) {
data = struct{}{} data = struct{}{}
} }
// 获取错误信息
if len(msg) > 0 { if len(msg) > 0 {
message = msg[0] message = msg[0]
} else { } else {
message = errorcode.GetMsg(code, "") message = errorcode.GetMsg(code, "")
} }
// 获取日志ID
log, exists := GetApiLogId(c) log, exists := GetApiLogId(c)
if exists { if exists {
logId = log.(int64) log_id = log.(int64)
} dataByte, _ := json.Marshal(data)
// 加密数据 status := common.STATUS_ENABLE
if code == errorcode.Success { if code == errorcode.Success {
if apiRsp, ok := data.(front.ApiResponse); ok { status = common.STATUS_DISABLED
apiRsp.Order, code = api.EnCrypt(appCheckInfo.App, apiRsp.Order)
if code != errorcode.Success {
message = errorcode.GetMsg(code, "")
}
responseData = apiRsp
} else {
responseData = data
} }
services.RequestLogUpdate(&orderrequestlogmodel.OrderRequestLog{
Id: log_id,
MerchantResponse: string(dataByte),
Status: status,
})
} }
if code == errorcode.Success { if code == errorcode.Success {
ApiSuccess(c, responseData, logId, message) ApiSuccess(c, data, log_id, message)
b, _ := json.Marshal(data)
originData = string(b)
} else { } else {
ApiError(c, code, logId, message) ApiError(c, code, log_id, 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,
})
} }
} }

View File

@ -5,7 +5,6 @@ import (
"PaymentCenter/app/http/controllers" "PaymentCenter/app/http/controllers"
"PaymentCenter/app/http/entities" "PaymentCenter/app/http/entities"
"PaymentCenter/app/http/entities/backend" "PaymentCenter/app/http/entities/backend"
"PaymentCenter/app/models/ordercallbacklogmodel"
"PaymentCenter/app/models/orderrequestlogmodel" "PaymentCenter/app/models/orderrequestlogmodel"
"PaymentCenter/app/models/ordersmodel" "PaymentCenter/app/models/ordersmodel"
"PaymentCenter/app/models/orderthirdpaylogmodel" "PaymentCenter/app/models/orderthirdpaylogmodel"
@ -35,10 +34,10 @@ func OrderList(c *gin.Context) {
controllers.HandCodeRes(c, data, code) controllers.HandCodeRes(c, data, code)
} }
func OrderRequestLogsList(c *gin.Context) { func OrderLogsList(c *gin.Context) {
req, _ := controllers.GetRequest(c).(*backend.OrderLogsListRequest) req, _ := controllers.GetRequest(c).(*backend.OrderLogsListRequest)
req.SetDefault() req.SetDefault()
requestLog, total, code := services.OrderRequestLogsList(*req) requestLog, thirdLog, code := services.OrderLogsList(*req)
requestLogList := make([]backend.OrderRequestLogResponse, 0, len(requestLog)) requestLogList := make([]backend.OrderRequestLogResponse, 0, len(requestLog))
linq.From(requestLog).SelectT(func(in orderrequestlogmodel.OrderRequestLog) (out backend.OrderRequestLogResponse) { linq.From(requestLog).SelectT(func(in orderrequestlogmodel.OrderRequestLog) (out backend.OrderRequestLogResponse) {
@ -46,42 +45,14 @@ func OrderRequestLogsList(c *gin.Context) {
return return
}).ToSlice(&requestLogList) }).ToSlice(&requestLogList)
controllers.HandCodeRes(c, entities.PageRsp{
Total: total,
Data: requestLogList,
}, code)
}
func OrderThirdLogsList(c *gin.Context) {
req, _ := controllers.GetRequest(c).(*backend.OrderLogsListRequest)
req.SetDefault()
thirdLog, total, code := services.OrderThirdLogsList(*req)
thirdLogList := make([]backend.OrderThirdLogResponse, 0, len(thirdLog)) thirdLogList := make([]backend.OrderThirdLogResponse, 0, len(thirdLog))
linq.From(thirdLog).SelectT(func(in orderthirdpaylogmodel.OrderThirdPayLog) (out backend.OrderThirdLogResponse) { linq.From(thirdLog).SelectT(func(in orderthirdpaylogmodel.OrderThirdPayLog) (out backend.OrderThirdLogResponse) {
out.ResponseFromDb(in) out.ResponseFromDb(in)
return return
}).ToSlice(&thirdLogList) }).ToSlice(&thirdLogList)
controllers.HandCodeRes(c, entities.PageRsp{ controllers.HandCodeRes(c, gin.H{
Total: total, "request_log_list": requestLogList,
Data: thirdLogList, "third_log_list": thirdLogList,
}, code)
}
func OrderCallbackLogsList(c *gin.Context) {
req, _ := controllers.GetRequest(c).(*backend.OrderLogsListRequest)
req.SetDefault()
callbackLog, total, code := services.OrderCallbackLogsList(*req)
callbackLogList := make([]backend.OrderCallbackLogResponse, 0, len(callbackLog))
linq.From(callbackLog).SelectT(func(in ordercallbacklogmodel.OrderCallbackLog) (out backend.OrderCallbackLogResponse) {
out.ResponseFromDb(in)
return
}).ToSlice(&callbackLogList)
controllers.HandCodeRes(c, entities.PageRsp{
Total: total,
Data: callbackLogList,
}, code) }, code)
} }

View File

@ -203,15 +203,6 @@ func GetAppCheckInfo(c *gin.Context) interface{} {
return request return request
} }
// 获取OutTradeNo
func GetOutTradeNo(c *gin.Context) string {
outTradeNo, _ := c.Get("OutTradeNo")
if outTradeNo == nil {
return ""
}
return outTradeNo.(string)
}
func GetApiLogId(c *gin.Context) (interface{}, bool) { func GetApiLogId(c *gin.Context) (interface{}, bool) {
request, exists := c.Get("log") request, exists := c.Get("log")
return request, exists return request, exists

View File

@ -7,15 +7,14 @@ import (
"PaymentCenter/app/models/ordersmodel" "PaymentCenter/app/models/ordersmodel"
"PaymentCenter/app/services" "PaymentCenter/app/services"
"PaymentCenter/app/services/thirdpay" "PaymentCenter/app/services/thirdpay"
"PaymentCenter/app/services/thirdpay/api"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"xorm.io/builder" "xorm.io/builder"
) )
func PayUrl(c *gin.Context) { func PayUrl(c *gin.Context) {
var res front.ApiResponse var res front.PayUrlResp
req := controllers.GetRequest(c).(*front.PayReqs) req := controllers.GetRequest(c).(*front.PayReqs)
c.Set("OutTradeNo", req.OutTradeNo)
appCheckInfo := controllers.GetAppCheckInfo(c).(*services.AppCheck) appCheckInfo := controllers.GetAppCheckInfo(c).(*services.AppCheck)
check := thirdpay.ThirdPayInfoCheck(c.Request.Context(), req, appCheckInfo, c.ClientIP()) check := thirdpay.ThirdPayInfoCheck(c.Request.Context(), req, appCheckInfo, c.ClientIP())
if check.CheckCode != errorcode.Success { if check.CheckCode != errorcode.Success {
@ -32,8 +31,14 @@ func PayUrl(c *gin.Context) {
controllers.ApiRes(c, nil, pay.PayCode) controllers.ApiRes(c, nil, pay.PayCode)
return return
} }
data := thirdpay.NewOrdersResp(pay.Order)
encryptData, errCode := api.EnCrypt(appCheckInfo.App, data)
res.Order = thirdpay.NewOrdersResp(pay.Order) if errCode != errorcode.Success {
controllers.ApiRes(c, nil, pay.PayCode)
return
}
res.Order = string(encryptData)
res.Url = pay.Url res.Url = pay.Url
controllers.ApiRes(c, res, pay.PayCode) controllers.ApiRes(c, res, pay.PayCode)
return return
@ -41,17 +46,18 @@ func PayUrl(c *gin.Context) {
func Refund(c *gin.Context) { func Refund(c *gin.Context) {
req := controllers.GetRequest(c).(*front.RefundReqs) req := controllers.GetRequest(c).(*front.RefundReqs)
c.Set("OutTradeNo", req.OutTradeNo)
appCheckInfo := controllers.GetAppCheckInfo(c).(*services.AppCheck) appCheckInfo := controllers.GetAppCheckInfo(c).(*services.AppCheck)
refund := thirdpay.ThirdPayRefund(c.Request.Context(), req, appCheckInfo, c.ClientIP()) refund := thirdpay.ThirdPayRefund(c.Request.Context(), req, appCheckInfo, c.ClientIP())
if refund.PayCode != errorcode.Success { if refund.PayCode != errorcode.Success {
controllers.ApiRes(c, nil, refund.PayCode) controllers.ApiRes(c, nil, refund.PayCode)
} }
data := thirdpay.NewOrdersResp(refund.Order) data := thirdpay.NewOrdersResp(refund.Order)
var res front.ApiResponse encryptData, errCode := api.EnCrypt(appCheckInfo.App, data)
res.Order = data if errCode != errorcode.Success {
controllers.ApiRes(c, res, refund.PayCode) controllers.ApiRes(c, nil, refund.PayCode)
return
}
controllers.ApiRes(c, encryptData, refund.PayCode)
return return
} }
@ -59,24 +65,26 @@ func Refund(c *gin.Context) {
// 查询订单 // 查询订单
func QueryOrder(c *gin.Context) { func QueryOrder(c *gin.Context) {
req := controllers.GetRequest(c).(*front.QueryReqs) req := controllers.GetRequest(c).(*front.QueryReqs)
c.Set("OutTradeNo", req.OutTradeNo)
appCheckInfo := controllers.GetAppCheckInfo(c).(*services.AppCheck) appCheckInfo := controllers.GetAppCheckInfo(c).(*services.AppCheck)
// 查询订单表 // 查询订单表
order := ordersmodel.Orders{ order := ordersmodel.Orders{
OutTradeNo: req.OutTradeNo, OutTreadNo: req.OutTradeNo,
AppId: req.AppId, AppId: req.AppId,
MerchantId: appCheckInfo.App.MerchantId, MerchantId: appCheckInfo.App.MerchantId,
} }
cond := builder.NewCond() cond := builder.NewCond()
cond = cond.And(builder.Eq{"out_trade_no": order.OutTradeNo}, builder.Eq{"app_id": order.AppId}) cond = cond.And(builder.Eq{"out_tread_no": order.OutTreadNo}, builder.Eq{"app_id": order.AppId})
_, code := services.OrderFindOne(&order, cond) _, code := services.OrderFindOne(&order, cond)
if code != errorcode.Success { if code != errorcode.OrdersExist {
controllers.ApiRes(c, nil, code) controllers.ApiRes(c, nil, code)
return return
} }
data := thirdpay.NewOrdersResp(&order) data := thirdpay.NewOrdersResp(&order)
var res front.ApiResponse encryptData, errCode := api.EnCrypt(appCheckInfo.App, data)
res.Order = data if errCode != errorcode.Success {
controllers.ApiRes(c, res, errorcode.Success) controllers.ApiRes(c, nil, errCode)
return
}
controllers.ApiRes(c, encryptData, errorcode.Success)
} }

View File

@ -2,7 +2,6 @@ package backend
import ( import (
"PaymentCenter/app/http/entities" "PaymentCenter/app/http/entities"
"PaymentCenter/app/models/ordercallbacklogmodel"
"PaymentCenter/app/models/orderrequestlogmodel" "PaymentCenter/app/models/orderrequestlogmodel"
"PaymentCenter/app/models/ordersmodel" "PaymentCenter/app/models/ordersmodel"
"PaymentCenter/app/models/orderthirdpaylogmodel" "PaymentCenter/app/models/orderthirdpaylogmodel"
@ -17,7 +16,7 @@ type OrderListRequest struct {
MerchantId int64 `json:"merchant_id" form:"merchant_id"` MerchantId int64 `json:"merchant_id" form:"merchant_id"`
PayChannelId int64 `json:"pay_channel_id" form:"pay_channel_id"` PayChannelId int64 `json:"pay_channel_id" form:"pay_channel_id"`
AppId int64 `json:"app_id" form:"app_id"` AppId int64 `json:"app_id" form:"app_id"`
OutTradeNo string `json:"out_trade_no" form:"out_trade_no"` OutTreadNo string `json:"out_tread_no" form:"out_tread_no"`
Status int `json:"status" form:"status"` Status int `json:"status" form:"status"`
OrderType int `json:"order_type" form:"order_type"` OrderType int `json:"order_type" form:"order_type"`
StartTime string `json:"start_time" form:"start_time"` StartTime string `json:"start_time" form:"start_time"`
@ -29,7 +28,7 @@ type OrderList struct {
MerchantId int64 `json:"merchant_id"` MerchantId int64 `json:"merchant_id"`
PayChannelId int64 `json:"pay_channel_id"` PayChannelId int64 `json:"pay_channel_id"`
AppId int64 `json:"app_id"` AppId int64 `json:"app_id"`
OutTradeNo string `json:"out_trade_no"` OutTreadNo string `json:"out_tread_no"`
Status int `json:"status"` Status int `json:"status"`
OrderType int `json:"order_type"` OrderType int `json:"order_type"`
StartTime time.Time `json:"start_time"` StartTime time.Time `json:"start_time"`
@ -57,7 +56,7 @@ func (o *OrderListRequest) ValidateRequest() (r OrderList, err error) {
r.MerchantId = o.MerchantId r.MerchantId = o.MerchantId
r.PayChannelId = o.PayChannelId r.PayChannelId = o.PayChannelId
r.AppId = o.AppId r.AppId = o.AppId
r.OutTradeNo = o.OutTradeNo r.OutTreadNo = o.OutTreadNo
r.Status = o.Status r.Status = o.Status
r.OrderType = o.OrderType r.OrderType = o.OrderType
r.PageRequest = o.PageRequest r.PageRequest = o.PageRequest
@ -70,7 +69,7 @@ type OrdersResponse struct {
MerchantId int64 `json:"merchant_id"` MerchantId int64 `json:"merchant_id"`
PayChannelId int64 `json:"pay_channel_id"` PayChannelId int64 `json:"pay_channel_id"`
AppId int64 `json:"app_id"` AppId int64 `json:"app_id"`
OutTradeNo string `json:"out_trade_no"` OutTreadNo string `json:"out_tread_no"`
Status int `json:"status"` Status int `json:"status"`
OrderType int `json:"order_type"` OrderType int `json:"order_type"`
Amount int `json:"amount"` Amount int `json:"amount"`
@ -88,7 +87,7 @@ func (o *OrdersResponse) ResponseFromDb(db ordersmodel.OrdersBackendList) {
o.MerchantId = db.MerchantId o.MerchantId = db.MerchantId
o.PayChannelId = db.PayChannelId o.PayChannelId = db.PayChannelId
o.AppId = db.AppId o.AppId = db.AppId
o.OutTradeNo = db.OutTradeNo o.OutTreadNo = db.OutTreadNo
o.Status = db.Status o.Status = db.Status
o.OrderType = db.OrderType o.OrderType = db.OrderType
o.Amount = db.Amount o.Amount = db.Amount
@ -102,17 +101,12 @@ func (o *OrdersResponse) ResponseFromDb(db ordersmodel.OrdersBackendList) {
} }
type OrderLogsListRequest struct { type OrderLogsListRequest struct {
Id int64 `json:"id" form:"id"`
OrderId int64 `json:"order_id" form:"order_id"` OrderId int64 `json:"order_id" form:"order_id"`
AppId int64 `json:"app_id" form:"app_id"`
OutTradeNo string `json:"out_trade_no" form:"out_trade_no"`
entities.PageRequest entities.PageRequest
} }
type OrderRequestLogResponse struct { type OrderRequestLogResponse struct {
Id int64 `json:"id"` Id int64 `json:"id"`
AppId int64 `json:"app_id"`
OutTradeNo string `json:"out_trade_no"`
IpAddress string `json:"ip_address"` IpAddress string `json:"ip_address"`
Url string `json:"url"` Url string `json:"url"`
MerchantRequest string `json:"merchant_request"` MerchantRequest string `json:"merchant_request"`
@ -123,8 +117,7 @@ type OrderRequestLogResponse struct {
func (o *OrderRequestLogResponse) ResponseFromDb(db orderrequestlogmodel.OrderRequestLog) { func (o *OrderRequestLogResponse) ResponseFromDb(db orderrequestlogmodel.OrderRequestLog) {
o.Id = db.Id o.Id = db.Id
o.AppId = db.AppId
o.OutTradeNo = db.OutTradeNo
o.IpAddress = db.IpAddress o.IpAddress = db.IpAddress
o.Url = db.URL o.Url = db.URL
o.Status = db.Status o.Status = db.Status
@ -153,21 +146,3 @@ func (o *OrderThirdLogResponse) ResponseFromDb(db orderthirdpaylogmodel.OrderThi
o.MerchantCallback = db.MerchantCallback o.MerchantCallback = db.MerchantCallback
o.CreateTime = db.CreateTime.Format("2006-01-02 15:04:05") o.CreateTime = db.CreateTime.Format("2006-01-02 15:04:05")
} }
type OrderCallbackLogResponse struct {
Id int64 `json:"id"`
OrderId int64 `json:"order_id"`
MerchantRequest string `json:"merchant_request"`
Status int `json:"status"`
MerchantResponse string `json:"merchant_response"`
CreateTime string `json:"create_time"`
}
func (o *OrderCallbackLogResponse) ResponseFromDb(db ordercallbacklogmodel.OrderCallbackLog) {
o.Id = db.Id
o.OrderId = db.OrderId
o.MerchantRequest = db.MerchantRequest
o.Status = db.Status
o.MerchantResponse = db.MerchantResponse
o.CreateTime = db.CreateTime.Format("2006-01-02 15:04:05")
}

View File

@ -27,9 +27,8 @@ type PayReqs struct {
type RefundReqs struct { type RefundReqs struct {
PayCommonReqBody PayCommonReqBody
RefundOutTradeNo string `json:"refund_out_trade_no" label:"需要退款的外侧商户订单号"` OutTradeNo string `json:"out_trade_no" label:"外侧商户订单号"`
RefundOrderId string `json:"refundOrder_id" label:"需要退款的平台订单号"` OrderId string `json:"order_id" label:"平台订单号"`
OutTradeNo string `json:"out_trade_no" validate:"required" label:"外侧商户订单号"`
} }
type PayUrlResp struct { type PayUrlResp struct {
@ -41,9 +40,3 @@ type QueryReqs struct {
ApiCommonBody ApiCommonBody
OutTradeNo string `json:"out_trade_no" validate:"required" label:"外侧商户订单号"` OutTradeNo string `json:"out_trade_no" validate:"required" label:"外侧商户订单号"`
} }
// api 接口返回数据, 统一返回结构, order数据会进行加密
type ApiResponse struct {
Order interface{} `json:"order"`
Url string `json:"url,omitempty"`
}

View File

@ -129,13 +129,8 @@ func ValidateRequest() gin.HandlerFunc {
func ValidatePayRequest() gin.HandlerFunc { func ValidatePayRequest() gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
var ( var path = c.FullPath()
path = c.FullPath() var handler func() interface{}
code int
log_id int64
)
var handler func() (interface{}, bool)
requestData, err := utils.SonicApiDataToStruct(controllers.GetRequest(c), &front.RequestBody{}) requestData, err := utils.SonicApiDataToStruct(controllers.GetRequest(c), &front.RequestBody{})
if err != nil { if err != nil {
controllers.ApiRes(c, nil, errorcode.ParamError) controllers.ApiRes(c, nil, errorcode.ParamError)
@ -162,7 +157,12 @@ func ValidatePayRequest() gin.HandlerFunc {
controllers.ApiRes(c, nil, errCode) controllers.ApiRes(c, nil, errCode)
return return
} }
//记录请求日志
id, code := services.AddRequestLog(dataByte, c.ClientIP(), path)
if code != errorcode.Success {
controllers.ApiRes(c, nil, errCode)
}
c.Set("log", id)
//检查解密后的数据是否与请求一致 //检查解密后的数据是否与请求一致
reCheck := appCheck.ReCheckAfterDecrypt(dataByte, requestDataStruct) reCheck := appCheck.ReCheckAfterDecrypt(dataByte, requestDataStruct)
if !reCheck { if !reCheck {
@ -170,18 +170,8 @@ func ValidatePayRequest() gin.HandlerFunc {
return return
} }
//表单验证 //表单验证
handler = requestmapping.FrontRequestMap[path] handler = requestmapping.FrontRequestMap[path]
v, isSaveLog := handler() v := handler()
if isSaveLog {
//记录请求日志
log_id, code = services.AddRequestLog(dataByte, c.ClientIP(), path)
if code != errorcode.Success {
controllers.ApiRes(c, nil, errCode)
}
}
c.Set("log", log_id)
msg, err := controllers.ValidApiData(dataByte, v) msg, err := controllers.ValidApiData(dataByte, v)
if err != nil { if err != nil {
utils.Log(c, "参数错误", "path=", path, "err=", err.Error(), "msg=", msg) utils.Log(c, "参数错误", "path=", path, "err=", err.Error(), "msg=", msg)

View File

@ -26,7 +26,5 @@ var BackendRequestMap = map[string]func() interface{}{
common.ADMIN_V1 + "/app/decrypt": func() interface{} { return new(backend.GenerateDecryptKeyRequest) }, common.ADMIN_V1 + "/app/decrypt": func() interface{} { return new(backend.GenerateDecryptKeyRequest) },
// 订单 // 订单
common.ADMIN_V1 + "/order/list": func() interface{} { return new(backend.OrderListRequest) }, common.ADMIN_V1 + "/order/list": func() interface{} { return new(backend.OrderListRequest) },
common.ADMIN_V1 + "/order/log/request": func() interface{} { return new(backend.OrderLogsListRequest) }, common.ADMIN_V1 + "/order/log/list": func() interface{} { return new(backend.OrderLogsListRequest) },
common.ADMIN_V1 + "/order/log/callback": func() interface{} { return new(backend.OrderLogsListRequest) },
common.ADMIN_V1 + "/order/log/third": func() interface{} { return new(backend.OrderLogsListRequest) },
} }

View File

@ -5,15 +5,11 @@ import (
"PaymentCenter/app/http/entities/front" "PaymentCenter/app/http/entities/front"
) )
var FrontRequestMap = map[string]func() (validForm interface{}, isSaveLog bool){ var FrontRequestMap = map[string]func() interface{}{
common.FRONT_V1 + "/pay/url": func() (interface{}, bool) { return new(front.PayReqs), true }, common.FRONT_V1 + "/pay/url": func() interface{} { return new(front.PayReqs) },
common.FRONT_V1 + "/pay/refund": func() (interface{}, bool) { return new(front.RefundReqs), true }, common.FRONT_V1 + "/pay/refund": func() interface{} { return new(front.RefundReqs) },
common.FRONT_V1 + "/pay/query": func() (interface{}, bool) { return new(front.QueryReqs), false },
} }
var FrontRequestMapBeforeDecrypt = map[string]func() interface{}{ var FrontRequestMapBeforeDecrypt = map[string]func() interface{}{
common.FRONT_V1 + "/pay/url": func() interface{} { return new(front.RequestBody) }, common.FRONT_V1 + "/pay/url": func() interface{} { return new(front.RequestBody) },
common.FRONT_V1 + "/pay/refund": func() interface{} { return new(front.RequestBody) },
common.FRONT_V1 + "/pay/query": func() interface{} { return new(front.RequestBody) },
} }

View File

@ -49,9 +49,7 @@ func RegisterAdminRoute(router *gin.Engine) {
// 订单 // 订单
order := v1.Group("/order") order := v1.Group("/order")
order.GET("/list", backend.OrderList) // 订单列表 order.GET("/list", backend.OrderList) // 订单列表
order.GET("/log/request", backend.OrderRequestLogsList) // 请求日志列表 order.GET("/log/list", backend.OrderLogsList) // 订单日志列表
order.GET("/log/callback", backend.OrderCallbackLogsList) // 回调日志列表
order.GET("/log/third", backend.OrderThirdLogsList) // 三方日志列表
} }

View File

@ -14,8 +14,6 @@ var (
// 实体 // 实体
type OrderRequestLog struct { type OrderRequestLog struct {
Id int64 Id int64
AppId int64 `xorm:"'app_id' bigint(20)"`
OutTradeNo string `xorm:"'out_trade_no' varchar(50)"`
IpAddress string `xorm:"'ip_address' varchar(16)"` IpAddress string `xorm:"'ip_address' varchar(16)"`
URL string `xorm:"'url' varchar(100)"` URL string `xorm:"'url' varchar(100)"`
MerchantRequest string `xorm:"'merchant_request' JSON"` MerchantRequest string `xorm:"'merchant_request' JSON"`

View File

@ -17,7 +17,7 @@ type Orders struct {
MerchantId int64 `xorm:"'merchant_id' bigint(20)"` MerchantId int64 `xorm:"'merchant_id' bigint(20)"`
PayChannelId int64 `xorm:"'pay_channel_id' bigint(20)"` PayChannelId int64 `xorm:"'pay_channel_id' bigint(20)"`
AppId int64 `xorm:"'app_id' bigint(20)"` AppId int64 `xorm:"'app_id' bigint(20)"`
OutTradeNo string `xorm:"'out_trade_no' varchar(50)"` OutTreadNo string `xorm:"'out_tread_no' varchar(50)"`
OrderType int `xorm:"'order_type' TINYINT"` OrderType int `xorm:"'order_type' TINYINT"`
RefundOrderId int64 `xorm:"'refund_order_id' bigint(20)"` RefundOrderId int64 `xorm:"'refund_order_id' bigint(20)"`
Amount int `xorm:"'amount' int(11)"` Amount int `xorm:"'amount' int(11)"`

View File

@ -13,7 +13,7 @@ func NewRsa(app *appmodel.App) ApiCrypt {
} }
} }
func (r *Rsa) Encrypt(data string) (encryptData []byte, errCode int) { func (r *Rsa) Encrypt(data []byte) (encryptData []byte, errCode int) {
if r.App.PublicKey == "" { if r.App.PublicKey == "" {
return nil, errorcode.AppRsaEncryptKeyNotFound return nil, errorcode.AppRsaEncryptKeyNotFound
} }

View File

@ -12,13 +12,13 @@ func NewSm2(app *appmodel.App) ApiCrypt {
} }
} }
func (r *SM2) Encrypt(data string) (encryptData []byte, errCode int) { func (r *SM2) Encrypt(data []byte) (encryptData []byte, errCode int) {
if r.App.MerchantPublicKey == "" { if r.App.MerchantPublicKey == "" {
return nil, errorcode.AppSM2EncryptKeyNotFound return nil, errorcode.AppSM2EncryptKeyNotFound
} }
encryptDataString, err := sm2.SM2Encrypt(data, r.App.MerchantPublicKey) encryptDataString, err := sm2.SM2Encrypt(string(data), r.App.MerchantPublicKey)
if err != nil { if err != nil {
return nil, errorcode.AppSM2EncryptFail return nil, errorcode.AppSM2EncryptFail
} }

View File

@ -13,11 +13,11 @@ func NewSm4(app *appmodel.App) ApiCrypt {
} }
} }
func (r *SM4) Encrypt(data string) (encryptData []byte, errCode int) { func (r *SM4) Encrypt(data []byte) (encryptData []byte, errCode int) {
if r.App.MerchantPublicKey == "" || r.App.PrivateKey == "" { if r.App.MerchantPublicKey == "" || r.App.PrivateKey == "" {
return nil, errorcode.AppSM4DecryptKeyNotFound return nil, errorcode.AppSM4DecryptKeyNotFound
} }
encryptDataString, err := sm4.Sm4Encrypt(strconv.FormatInt(r.App.Id, 10), r.App.PrivateKey, r.App.MerchantPublicKey, data, "", true) encryptDataString, err := sm4.Sm4Encrypt(strconv.FormatInt(r.App.Id, 10), r.App.PrivateKey, r.App.MerchantPublicKey, string(data), "", true)
if err != nil { if err != nil {
return nil, errorcode.AppSM4EncryptFail return nil, errorcode.AppSM4EncryptFail
} }

View File

@ -7,7 +7,7 @@ import (
type ( type (
ApiCrypt interface { ApiCrypt interface {
Encrypt(data string) (encryptData []byte, errCode int) Encrypt(data []byte) (encryptData []byte, errCode int)
Decrypt(encryptData string) (decryptData []byte, errCode int) Decrypt(encryptData string) (decryptData []byte, errCode int)
} }

View File

@ -4,7 +4,6 @@ import (
"PaymentCenter/app/constants/errorcode" "PaymentCenter/app/constants/errorcode"
"PaymentCenter/app/data" "PaymentCenter/app/data"
"PaymentCenter/app/http/entities/backend" "PaymentCenter/app/http/entities/backend"
"PaymentCenter/app/models/ordercallbacklogmodel"
"PaymentCenter/app/models/orderrequestlogmodel" "PaymentCenter/app/models/orderrequestlogmodel"
"PaymentCenter/app/models/ordersmodel" "PaymentCenter/app/models/ordersmodel"
"PaymentCenter/app/models/orderthirdpaylogmodel" "PaymentCenter/app/models/orderthirdpaylogmodel"
@ -30,8 +29,8 @@ func OrderList(req backend.OrderList) (result []ordersmodel.OrdersBackendList, t
if req.AppId > 0 { if req.AppId > 0 {
conn = conn.And(builder.Eq{"orders.app_id": req.AppId}) conn = conn.And(builder.Eq{"orders.app_id": req.AppId})
} }
if req.OutTradeNo != "" { if req.OutTreadNo != "" {
conn = conn.And(builder.Like{"orders.out_trade_no", req.OutTradeNo}) conn = conn.And(builder.Like{"orders.out_tread_no", req.OutTreadNo})
} }
if req.Status > 0 { if req.Status > 0 {
conn = conn.And(builder.Eq{"orders.status": req.Status}) conn = conn.And(builder.Eq{"orders.status": req.Status})
@ -53,62 +52,27 @@ func OrderList(req backend.OrderList) (result []ordersmodel.OrdersBackendList, t
return orderList, count, code return orderList, count, code
} }
// 请求日志列表 func OrderLogsList(req backend.OrderLogsListRequest) (requestLog []orderrequestlogmodel.OrderRequestLog, thirdLod []orderthirdpaylogmodel.OrderThirdPayLog, code int) {
func OrderRequestLogsList(req backend.OrderLogsListRequest) (requestLog []orderrequestlogmodel.OrderRequestLog, total int64, code int) {
requestRepo := data.NewOrderRequestLogRepo(paychannelmodel.GetInstance().GetDb()) requestRepo := data.NewOrderRequestLogRepo(paychannelmodel.GetInstance().GetDb())
thirdRepo := data.NewOrderThirdPayLogRepo(paychannelmodel.GetInstance().GetDb())
conn := builder.NewCond() conn := builder.NewCond()
if req.OrderId > 0 { if req.OrderId > 0 {
conn = conn.And(builder.Eq{"orders.id": req.OrderId}) conn = conn.And(builder.Eq{"order_id": req.OrderId})
}
if req.Id > 0 {
conn = conn.And(builder.Eq{"order_request_log.id": req.Id})
}
if req.AppId > 0 {
conn = conn.And(builder.Eq{"order_request_log.app_id": req.AppId})
}
if req.OutTradeNo != "" {
conn = conn.And(builder.Like{"order_request_log.out_trade_no", req.OutTradeNo})
} }
// 请求日志 // 请求日志
orderLogList := make([]orderrequestlogmodel.OrderRequestLog, 0) orderLogList := make([]orderrequestlogmodel.OrderRequestLog, 0)
total, err := requestRepo.OrderRequestLogBackendList(conn, req.PageRequest, &orderLogList) _, err := requestRepo.OrderRequestLogList(conn, req.PageRequest, &orderLogList)
if err != nil {
code = handErr(err) code = handErr(err)
return orderLogList, total, code return
} }
// 回调日志列表
func OrderCallbackLogsList(req backend.OrderLogsListRequest) (callback []ordercallbacklogmodel.OrderCallbackLog, total int64, code int) {
callbackRepo := data.NewOrderCallbackLogRepo(paychannelmodel.GetInstance().GetDb())
conn := builder.NewCond()
if req.OrderId > 0 {
conn = conn.And(builder.Eq{"order_id": req.OrderId})
}
if req.Id > 0 {
conn = conn.And(builder.Eq{"id": req.Id})
}
// 回调日志
callbackLogList := make([]ordercallbacklogmodel.OrderCallbackLog, 0)
total, err := callbackRepo.OrderCallbackLogList(conn, req.PageRequest, &callbackLogList)
code = handErr(err)
return callbackLogList, total, code
}
// 三方日志列表
func OrderThirdLogsList(req backend.OrderLogsListRequest) (thirdLod []orderthirdpaylogmodel.OrderThirdPayLog, total int64, code int) {
thirdRepo := data.NewOrderThirdPayLogRepo(paychannelmodel.GetInstance().GetDb())
// 三方日志 // 三方日志
conn := builder.NewCond()
if req.OrderId > 0 {
conn = conn.And(builder.Eq{"order_id": req.OrderId})
}
if req.Id > 0 {
conn = conn.And(builder.Eq{"id": req.Id})
}
thirdLogList := make([]orderthirdpaylogmodel.OrderThirdPayLog, 0) thirdLogList := make([]orderthirdpaylogmodel.OrderThirdPayLog, 0)
total, err := thirdRepo.OrderThirdPayLogList(conn, req.PageRequest, &thirdLogList) _, err = thirdRepo.OrderThirdPayLogList(conn, req.PageRequest, &thirdLogList)
code = handErr(err) code = handErr(err)
return thirdLogList, total, code
return orderLogList, thirdLogList, code
} }
func OrderCreate(orderIn *ordersmodel.Orders) (orderOut *ordersmodel.Orders, code int) { func OrderCreate(orderIn *ordersmodel.Orders) (orderOut *ordersmodel.Orders, code int) {

View File

@ -3,7 +3,7 @@ package api
type OrdersResp struct { type OrdersResp struct {
OrderNo int64 `json:"order_no"` OrderNo int64 `json:"order_no"`
OrderType int `json:"order_type"` OrderType int `json:"order_type"`
OutTradeNo string `json:"out_trade_no"` OutTreadNo string `json:"out_tread_no"`
Amount int `json:"amount"` Amount int `json:"amount"`
Desc string `json:"desc"` Desc string `json:"desc"`

View File

@ -18,8 +18,15 @@ func EnCrypt(app *appmodel.App, data interface{}) ([]byte, int) {
if err != nil { if err != nil {
return nil, errorcode.AppAesEncryptFail return nil, errorcode.AppAesEncryptFail
} }
//aesKey, err := aes.GenerateRandomStringCrypto(16)
encryptData, errCode := cryptFunc(appCheck.App).Encrypt(string(dataByte)) //if err != nil {
// return "", errorcode.AppAesEncryptFail
//}
//aesData, err := aes.Encrypt(dataByte, []byte(aesKey))
//if err != nil {
// return "", errorcode.AppAesEncryptFail
//}
encryptData, errCode := cryptFunc(appCheck.App).Encrypt(dataByte)
if errCode != apicrypt.CryptNotError { if errCode != apicrypt.CryptNotError {
return nil, errCode return nil, errCode
} }
@ -39,6 +46,10 @@ func DeCrypt(app *appmodel.App, data string, aesKey string) ([]byte, int) {
if len(dataByte) == 0 { if len(dataByte) == 0 {
return nil, errorcode.AppDeEncryptFail return nil, errorcode.AppDeEncryptFail
} }
//aesData, err := aes.Decrypt(dataByte, []byte(aesKey))
//if err != nil {
// return nil, errorcode.AppAesEncryptFail
//}
return dataByte, errorcode.Success return dataByte, errorcode.Success
} }

View File

@ -7,46 +7,24 @@ import (
"PaymentCenter/app/models/paychannelmodel" "PaymentCenter/app/models/paychannelmodel"
"PaymentCenter/app/services" "PaymentCenter/app/services"
"PaymentCenter/app/third/paymentService/payCommon" "PaymentCenter/app/third/paymentService/payCommon"
"context"
"PaymentCenter/app/models/ordersmodel" "PaymentCenter/app/models/ordersmodel"
"PaymentCenter/app/third/paymentService" "PaymentCenter/app/third/paymentService"
) )
type PayParam struct { type Pay struct {
Merchant *merchantmodel.Merchant Merchant *merchantmodel.Merchant
Channel *paychannelmodel.PayChannel Channel *paychannelmodel.PayChannel
App_id int64
OutTradeNo string
Amount int
ExtJson string
Desc string
ClientIp string
}
type Pay struct { paycheck *PayCheck
ctx *context.Context
PayParam *PayParam
RelationOrder *ordersmodel.Orders
Order *ordersmodel.Orders Order *ordersmodel.Orders
PayCode int PayCode int
Url string Url string
} }
func NewPayWithPayCheck(paycheck *PayCheck) *Pay { func NewPay(paycheck *PayCheck) *Pay {
return &Pay{ return &Pay{
ctx: paycheck.ctx, paycheck: paycheck,
PayParam: &PayParam{
Merchant: paycheck.Merchant,
Channel: paycheck.Channel,
App_id: paycheck.Reqs.AppId,
OutTradeNo: paycheck.Reqs.OutTradeNo,
Amount: paycheck.Reqs.Amount,
ExtJson: paycheck.Reqs.ExtJson,
Desc: paycheck.Reqs.Desc,
ClientIp: paycheck.AppCheck.Ip,
},
RelationOrder: paycheck.OldOrder,
PayCode: errorcode.Success, PayCode: errorcode.Success,
} }
} }
@ -56,21 +34,18 @@ func (w *Pay) CreateOrder(order_type int) {
w.PayCode = errorcode.PayChannelNotFound w.PayCode = errorcode.PayChannelNotFound
return return
} }
order := &ordersmodel.Orders{ w.Order, w.PayCode = services.OrderCreate(&ordersmodel.Orders{
MerchantId: w.PayParam.Merchant.Id, MerchantId: w.paycheck.Merchant.Id,
PayChannelId: w.PayParam.Channel.Id, PayChannelId: w.paycheck.Channel.Id,
AppId: w.PayParam.App_id, AppId: w.paycheck.Reqs.AppId,
OutTradeNo: w.PayParam.OutTradeNo, OutTreadNo: w.paycheck.Reqs.OutTradeNo,
OrderType: order_type, OrderType: order_type,
Amount: w.PayParam.Amount, Amount: w.paycheck.Reqs.Amount,
ExtJson: w.PayParam.ExtJson, ExtJson: w.paycheck.Reqs.ExtJson,
Desc: w.PayParam.Desc, Desc: w.paycheck.Reqs.Desc,
Status: common.ORDER_STATUS_WAITPAY, Status: common.ORDER_STATUS_WAITPAY,
} },
if order_type == common.ORDER_TYPE_REFUND { )
order.RefundOrderId = w.RelationOrder.Id
}
w.Order, w.PayCode = services.OrderCreate(order)
} }
func (w *Pay) PayUrl() (url string) { func (w *Pay) PayUrl() (url string) {
@ -79,23 +54,23 @@ func (w *Pay) PayUrl() (url string) {
ok bool ok bool
) )
thirdPay := &paymentService.PayOrderRequest{ thirdPay := &paymentService.PayOrderRequest{
PayChannelId: w.PayParam.Channel.Id, PayChannelId: w.paycheck.Reqs.PayChannelId,
OrderId: w.Order.Id, OrderId: w.Order.Id,
ChannelType: w.PayParam.Channel.ChannelType, ChannelType: w.paycheck.Channel.ChannelType,
Description: w.Order.Desc, Description: w.Order.Desc,
Amount: w.Order.Amount, Amount: w.Order.Amount,
PayerClientIp: w.PayParam.ClientIp, PayerClientIp: w.paycheck.AppCheck.Ip,
} }
if payFunc, ok = PayWayList[w.PayParam.Channel.ChannelType]; !ok { if payFunc, ok = PayWayList[w.paycheck.Channel.ChannelType]; !ok {
w.PayCode = errorcode.PayChannelNotBuild w.PayCode = errorcode.PayChannelNotBuild
return return
} }
err := payFunc(thirdPay, w.PayParam.Channel) err := payFunc(thirdPay, w.paycheck.Channel)
if err != nil { if err != nil {
w.PayCode = errorcode.PayChannelExtJsonError w.PayCode = errorcode.PayChannelExtJsonError
return return
} }
res := paymentService.PaymentService(*w.ctx, *thirdPay) res := paymentService.PaymentService(*w.paycheck.ctx, *thirdPay)
if res.Code == payCommon.PAY_SUCCESS_CODE { if res.Code == payCommon.PAY_SUCCESS_CODE {
w.Order.Status = common.ORDER_STATUS_PAYING w.Order.Status = common.ORDER_STATUS_PAYING
@ -118,21 +93,21 @@ func (w *Pay) Refund() {
) )
thirdPayRefund := &paymentService.OrderRefundRequest{ thirdPayRefund := &paymentService.OrderRefundRequest{
OrderId: w.Order.Id, OrderId: w.Order.Id,
RefundOrderId: w.RelationOrder.Id, RefundOrderId: w.paycheck.OldOrder.Id,
RefundReason: w.PayParam.Desc, RefundReason: w.paycheck.Reqs.Desc,
RefundAmount: int64(w.PayParam.Amount), RefundAmount: int64(w.paycheck.Reqs.Amount),
PayChannel: w.PayParam.Channel.ChannelType, PayChannel: w.paycheck.Channel.ChannelType,
} }
if refundFunc, ok = RefundWayList[w.PayParam.Channel.ChannelType]; !ok { if refundFunc, ok = RefundWayList[w.paycheck.Channel.ChannelType]; !ok {
w.PayCode = errorcode.PayChannelNotBuild w.PayCode = errorcode.PayChannelNotBuild
return return
} }
err := refundFunc(thirdPayRefund, w.PayParam.Channel) err := refundFunc(thirdPayRefund, w.paycheck.Channel)
if err != nil { if err != nil {
w.PayCode = errorcode.PayChannelExtJsonError w.PayCode = errorcode.PayChannelExtJsonError
return return
} }
res := paymentService.OrderRefund(*w.ctx, *thirdPayRefund) res := paymentService.OrderRefund(*w.paycheck.ctx, *thirdPayRefund)
if res.Code == payCommon.PAY_SUCCESS_CODE { if res.Code == payCommon.PAY_SUCCESS_CODE {
w.Order.Status = common.ORDER_STATUS_PAYING w.Order.Status = common.ORDER_STATUS_PAYING
code := services.OrderUpdate(w.Order, "status") code := services.OrderUpdate(w.Order, "status")

View File

@ -61,9 +61,7 @@ func (w *PayCheck) CheckMerchant() {
} }
func (w *PayCheck) CheckOrderPay() { func (w *PayCheck) CheckOrderPay() {
w.GetOrder(&types.OrderFindOne{ w.GetOrder()
OutTradeNo: w.Reqs.OutTradeNo,
})
if w.OldOrder != nil { if w.OldOrder != nil {
switch w.OldOrder.Status { switch w.OldOrder.Status {
case common.ORDER_STATUS_CLOSE: case common.ORDER_STATUS_CLOSE:
@ -80,40 +78,34 @@ func (w *PayCheck) CheckOrderPay() {
} }
func (w *PayCheck) CheckOrderRefund() { func (w *PayCheck) CheckOrderRefund() {
w.GetOrder(&types.OrderFindOne{ w.GetOrder()
OutTradeNo: w.Reqs.RefundOutTradeNo,
OrderId: w.Reqs.RefundOrderId,
})
if w.OldOrder == nil { if w.OldOrder == nil {
w.CheckCode = errorcode.RefundOrderNotFound w.CheckCode = errorcode.OrdersNotFound
return
} }
if w.OldOrder.Status != common.ORDER_STATUS_PAYED { switch w.OldOrder.Status {
w.CheckCode = errorcode.OrderStatusRefundNotSupport case common.ORDER_STATUS_CLOSE:
w.CheckCode = errorcode.OrderClosed
case common.ORDER_STATUS_FAILED:
w.CheckCode = errorcode.OrderFailed
case common.ORDER_STATUS_WAITPAY:
w.CheckCode = errorcode.OrderStatusErr
case common.ORDER_STATUS_PAYING:
w.CheckCode = errorcode.OrderStatusErr
default:
} }
return return
} }
func (w *PayCheck) GetOrder(orderCol *types.OrderFindOne) { func (w *PayCheck) GetOrder() {
cond := builder.NewCond() cond := builder.NewCond()
cond = cond.And(builder.Eq{"app_id": w.AppCheck.AppId}) cond = cond.And(builder.Eq{"out_tread_no": w.Reqs.OutTradeNo}, builder.Eq{"app_id": w.AppCheck.AppId})
if orderCol.OrderId == "" && orderCol.OutTradeNo == "" {
w.CheckCode = errorcode.OrdersNotFound
return
}
if orderCol.OrderId != "" {
cond = cond.And(builder.Eq{"order_id": orderCol.OrderId})
}
if orderCol.OutTradeNo != "" {
cond = cond.And(builder.Eq{"out_trade_no": orderCol.OutTradeNo})
}
order, code := services.OrderFindOne(&ordersmodel.Orders{}, cond) order, code := services.OrderFindOne(&ordersmodel.Orders{}, cond)
if code == errorcode.SystemError { if code == errorcode.SystemError {
w.CheckCode = code w.CheckCode = code
return return
} }
if code == errorcode.Success { if code == errorcode.OrdersExist {
w.OldOrder = order w.OldOrder = order
} }
return
} }

View File

@ -23,7 +23,7 @@ func ThirdPayUrl(check *thirdpay.PayCheck) *thirdpay.Pay {
func NewOrdersResp(db *ordersmodel.Orders) *api.OrdersResp { func NewOrdersResp(db *ordersmodel.Orders) *api.OrdersResp {
return &api.OrdersResp{ return &api.OrdersResp{
OrderNo: db.Id, OrderNo: db.Id,
OutTradeNo: db.OutTradeNo, OutTreadNo: db.OutTreadNo,
Status: db.Status, Status: db.Status,
OrderType: db.OrderType, OrderType: db.OrderType,
Amount: db.Amount, Amount: db.Amount,
@ -47,7 +47,7 @@ func ThirdPayInfoCheck(ctx context.Context, payReq *front.PayReqs, appCheck *ser
func ThirdPayRefund(ctx context.Context, refundReq *front.RefundReqs, appCheck *services.AppCheck, ip string) (refund *thirdpay.Pay) { func ThirdPayRefund(ctx context.Context, refundReq *front.RefundReqs, appCheck *services.AppCheck, ip string) (refund *thirdpay.Pay) {
var req types.Reqs var req types.Reqs
copier.Copy(&req, refundReq) copier.Copy(req, refundReq)
check := thirdpay.NewPayCheck(&ctx, &req, appCheck, ip) check := thirdpay.NewPayCheck(&ctx, &req, appCheck, ip)
// 校验表单 // 校验表单
check.CheckPayInfo() check.CheckPayInfo()
@ -58,22 +58,22 @@ func ThirdPayRefund(ctx context.Context, refundReq *front.RefundReqs, appCheck *
if check.CheckCode != errorcode.Success { if check.CheckCode != errorcode.Success {
return return
} }
refund = thirdpay.NewPayWithPayCheck(check) refund = thirdpay.NewPay(check)
refund.CreateOrder(common.ORDER_TYPE_REFUND) refund.CreateOrder(common.ORDER_TYPE_REFUND)
refund.Refund() refund.Refund()
return return
} }
func ThirdPay(check *thirdpay.PayCheck) (pay *thirdpay.Pay) { func ThirdPay(check *thirdpay.PayCheck) (pay *thirdpay.Pay) {
pay = thirdpay.NewPayWithPayCheck(check) pay = thirdpay.NewPay(check)
// 创建订单 // 创建订单
if check.OldOrder != nil { if &check.OldOrder != nil {
pay.Order = check.OldOrder
} else {
pay.CreateOrder(common.ORDER_TYPE_PAY) pay.CreateOrder(common.ORDER_TYPE_PAY)
if pay.PayCode != errorcode.Success { if pay.PayCode != errorcode.Success {
return pay return pay
} }
} else {
pay.Order = check.OldOrder
} }
return return
} }

View File

@ -38,7 +38,7 @@ type OrderNotifyResp struct {
type OrderNotifySendContent struct { type OrderNotifySendContent struct {
OrderId int64 `json:"order_id"` OrderId int64 `json:"order_id"`
OutTradeNo string `json:"out_trade_no"` OutTreadNo string `json:"out_tread_no"`
CompleteTime time.Time `json:"complete_time"` CompleteTime time.Time `json:"complete_time"`
OrderType int `json:"order-type"` OrderType int `json:"order-type"`
Status int `json:"status"` Status int `json:"status"`
@ -133,7 +133,7 @@ func (o *OrderNotify) sendNotify(body *OrderNotifySendContent) {
func (o *OrderNotify) setBody() *OrderNotifySendContent { func (o *OrderNotify) setBody() *OrderNotifySendContent {
return &OrderNotifySendContent{ return &OrderNotifySendContent{
OrderId: o.OrderId, OrderId: o.OrderId,
OutTradeNo: o.order.OutTradeNo, OutTreadNo: o.order.OutTreadNo,
CompleteTime: o.CompleteTime, CompleteTime: o.CompleteTime,
Status: o.order.Status, Status: o.order.Status,
OrderType: o.order.OrderType, OrderType: o.order.OrderType,

View File

@ -5,11 +5,4 @@ import "PaymentCenter/app/http/entities/front"
type Reqs struct { type Reqs struct {
front.PayCommonReqBody front.PayCommonReqBody
OutTradeNo string `json:"out_trade_no"` OutTradeNo string `json:"out_trade_no"`
RefundOutTradeNo string `json:"refund_out_trade_no"`
RefundOrderId string `json:"refundOrder_id"`
}
type OrderFindOne struct {
OrderId string
OutTradeNo string `json:"out_trade_no"`
} }

View File

@ -20,13 +20,6 @@ func Encrypt(plaintext, key []byte) ([]byte, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
// 加密后的数据会比原文长,因为需要添加一些填充字节
// PKCS#7填充
plaintext = pkcs7Padding(plaintext, block.BlockSize())
// 创建一个cipher.BlockMode这里使用CBC模式
// 需要一个iv初始化向量它的长度和Block的块大小相同
ciphertext := make([]byte, aes.BlockSize+len(plaintext)) ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize] iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil { if _, err := io.ReadFull(rand.Reader, iv); err != nil {
@ -36,8 +29,7 @@ func Encrypt(plaintext, key []byte) ([]byte, error) {
mode := cipher.NewCBCEncrypter(block, iv) mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext) mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
// 返回的密文包括iv和加密后的数据 return iv, nil
return ciphertext, nil
} }
// 解密函数 // 解密函数

View File

@ -32,8 +32,7 @@ func parseRSAPublicKeyFromPEM(pemData []byte) (*rsa.PublicKey, error) {
} }
// encrypt 使用RSA公钥加密数据 // encrypt 使用RSA公钥加密数据
func Encrypt(publicKeyPEM string, plaintext string) ([]byte, error) { func Encrypt(publicKeyPEM string, plaintext []byte) ([]byte, error) {
var encryptedData []byte
// 将PEM编码的公钥转换为[]byte // 将PEM编码的公钥转换为[]byte
pemData := []byte(publicKeyPEM) pemData := []byte(publicKeyPEM)
@ -42,24 +41,14 @@ func Encrypt(publicKeyPEM string, plaintext string) ([]byte, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
hash := sha256.New()
maxBlockSize := pubKey.Size() - 2*hash.Size() - 2
// 创建用于加密的随机填充 // 创建用于加密的随机填充
label := []byte("") // OAEP标签对于某些情况可能是非空的 label := []byte("") // OAEP标签对于某些情况可能是非空的
for len(plaintext) > 0 { ciphertext, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, pubKey, plaintext, label)
blockSize := maxBlockSize
if len(plaintext) < maxBlockSize {
blockSize = len(plaintext)
}
block := plaintext[:blockSize]
encryptedBlock, err := rsa.EncryptOAEP(hash, rand.Reader, pubKey, []byte(block), label)
if err != nil { if err != nil {
return nil, err return nil, err
} }
encryptedData = append(encryptedData, encryptedBlock...) return ciphertext, nil
plaintext = plaintext[blockSize:]
}
return encryptedData, nil
} }
// parseRSAPrivateKeyFromPEM 解析PEM编码的RSA私钥 // parseRSAPrivateKeyFromPEM 解析PEM编码的RSA私钥
@ -91,38 +80,34 @@ func parseRSAPrivateKeyFromPEM(pemData []byte) (*rsa.PrivateKey, error) {
// decrypt 使用RSA私钥解密数据 // decrypt 使用RSA私钥解密数据
func Decrypt(privateKeyPEM string, encryptedDataBase64 string) ([]byte, error) { func Decrypt(privateKeyPEM string, encryptedDataBase64 string) ([]byte, error) {
var decryptedData []byte
// 将PEM编码的私钥转换为[]byte // 将PEM编码的私钥转换为[]byte
pemData := []byte(privateKeyPEM) pemData := []byte(privateKeyPEM)
// 解析PEM数据以获取私钥 // 解析PEM数据以获取私钥
privKey, err := parseRSAPrivateKeyFromPEM(pemData) privKey, err := parseRSAPrivateKeyFromPEM(pemData)
if err != nil { if err != nil {
return nil, err return nil, err
} }
keySize := privKey.PublicKey.Size()
label := []byte("") // OAEP标签对于某些情况可能是非空的
hash := sha256.New()
// 将Base64编码的加密数据解码为字节切片 // 将Base64编码的加密数据解码为字节切片
encryptedData, err := base64.StdEncoding.DecodeString(encryptedDataBase64) encryptedData, err := base64.StdEncoding.DecodeString(encryptedDataBase64)
if err != nil { if err != nil {
return nil, err return nil, err
} }
for len(encryptedData) > 0 {
block := encryptedData[:keySize] // 根据你的加密方式选择合适的解密函数
// 这里假设使用的是OAEP填充和SHA-256哈希函数 // 这里假设使用的是OAEP填充和SHA-256哈希函数
decryptedBlock, err := rsa.DecryptOAEP(hash, rand.Reader, privKey, block, label) label := []byte("") // OAEP标签对于某些情况可能是非空的
decrypted, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, privKey, encryptedData, label)
if err != nil { if err != nil {
//// 如果失败可以尝试使用PKCS#1 v1.5填充 // 如果失败可以尝试使用PKCS#1 v1.5填充
decryptedBlock, err = rsa.DecryptPKCS1v15(rand.Reader, privKey, encryptedData) decrypted, err = rsa.DecryptPKCS1v15(rand.Reader, privKey, encryptedData)
if err != nil { if err != nil {
return nil, err return nil, err
} }
} }
decryptedData = append(decryptedData, decryptedBlock...)
encryptedData = encryptedData[keySize:] return decrypted, nil
}
return decryptedData, nil
} }
// 生成密钥对 // 生成密钥对

View File

@ -18,7 +18,7 @@ func TestRsaEncrypt(t *testing.T) {
} }
func TestRsaDecrypt(t *testing.T) { func TestRsaDecrypt(t *testing.T) {
data := "pPnAPy7v2SY9Fu0LFcQH8UBA6VQ2FCfSg3nRZdMXS7mWjBwlacKHuFnh9UhobL7mxnmMyZPP100bpjCg2kvcfOpOp3ci85p+OYWINt4Fh3qgEOTG5FUyziaagGLm882t/I36KsDTVvbMZvC5sg4gZ9JQ5yAR+nuJfr0IxI0se/iD5luV1rms1kZHggd30iXdZtbkbX7xJ4xtnIiJmZU7kL+Xmvv1rDdPLxbol65QfnM1me1IHkXJapqSBnhEEmFQyBx31vp1ccNjkza8ZWbvTPCngc1k4kvlm6lKfwsG4hMuSdXUzveDm+Oo8StAKnyVoerJ202n7Vfx1XhehineQT0TPD7bO0HCEsDXXYEWwvcax8VdzYvHk7qSbH6e154qCr4LgDRSHKwAAExinTrzxx2rtSimieBLaEpDL2v5ch45HnhjRhWTRmM61W1g6sdHaVX1mQxaXvrT4v+h+f4TbIV4r4qeGJ6rXG+yKRoYseLzyGgystoOny9P0UH15W8rWPytV2eioWT7i3Cglg04BWP9mst67LQXeFH4CA6CkwVV2w9nCHrzxX2ouYSQELUEkTlIMry2AlkZubUnupGJLmLLUyZj7pM/6cLjyAgm02/gRc4wwf7JBBq/ipmKXpkhHXWLtQDWJEZTT+ug2v9EXy5dgPNPe8ZI0MILAeipjIc=" data := encrypt()
privateKeyPEM := `-----BEGIN RSA PRIVATE KEY----- privateKeyPEM := `-----BEGIN RSA PRIVATE KEY-----
` + PRI + ` ` + PRI + `
-----END RSA PRIVATE KEY-----` -----END RSA PRIVATE KEY-----`
@ -27,11 +27,13 @@ func TestRsaDecrypt(t *testing.T) {
} }
func encrypt() string { func encrypt() string {
data := "{\"pay_channel_id\":8935141660703064070,\"out_trade_no\":\"refundOutTreadNo001\",\"amount\":1,\"desc\":\"退款\",\"ext_json\":\"\",\"app_id\":5476377146882523138,\"timestamp\":53612533412643,\"refund_out_trade_no\":\"asdadasdas\"}" data := "{\"order_no\":4323455642275676219,\"order_type\":1,\"out_tread_no\":\"asdadasdas\",\"amount\":1,\"desc\":\"abc\",\"status\":2,\"create_time\":\"2024-08-07 18:36:43\"}"
fmt.Println(len(data))
dataJson := []byte(data)
pub := `-----BEGIN PUBLIC KEY----- pub := `-----BEGIN PUBLIC KEY-----
` + PUB + ` ` + PUB + `
-----END PUBLIC KEY-----` -----END PUBLIC KEY-----`
en, err := Encrypt(pub, data) en, err := Encrypt(pub, dataJson)
if err != nil { if err != nil {
panic(err) panic(err)
} }
@ -40,10 +42,9 @@ func encrypt() string {
} }
func encryptWithAes() string { func encryptWithAes() string {
data := "{\"pay_channel_id\":8935141660703064070,\"out_trade_no\":\"refundOutTreadNo001\",\"amount\":1,\"desc\":\"退款\",\"ext_json\":\"\",\"app_id\":5476377146882523138,\"timestamp\":53612533412643\"refund_out_trade_no\":\"asdadasdas\"}" data := "{\"pay_channel_id\":8935141660703064070,\"out_trade_no\":\"asdadasdas\",\"order_type\":1,\"amount\":1,\"desc\":\"abc\",\"ext_json\":\"\",\"app_id\":5476377146882523138,\"timestamp\":53612533412643}"
aes.Encrypt([]byte(data), []byte(aes.TestKey)) aes.Encrypt([]byte(data), []byte(aes.TestKey))
dataJson := []byte(data)
dataJson := base64.StdEncoding.EncodeToString([]byte(data))
pub := `-----BEGIN PUBLIC KEY----- pub := `-----BEGIN PUBLIC KEY-----
` + PUB + ` ` + PUB + `
-----END PUBLIC KEY-----` -----END PUBLIC KEY-----`
@ -57,7 +58,14 @@ func encryptWithAes() string {
// 测试生成密钥对 // 测试生成密钥对
func TestGenerateRSAKey(t *testing.T) { func TestGenerateRSAKey(t *testing.T) {
pub, pri, _ := GenerateKey() pub, pri, err := GenerateKey()
data := "{\"pay_channel_id\":8935141660703064070,\"out_trade_no\":\"asdadasdas\",\"order_type\":1,\"amount\":1,\"desc\":\"abc\",\"ext_json\":\"\",\"app_id\":5476377146882523138,\"timestamp\":53612533412643}"
fmt.Println("pub:", pub, "\n", "pri:", pri) dataJson := []byte(data)
en, err := Encrypt(pub, dataJson)
if err != nil {
panic(err)
}
content := base64.StdEncoding.EncodeToString(en)
res, err := Decrypt(pri, content)
fmt.Println("解密", string(res), err)
} }