Files
kami_gateway/internal/service/supplier/third_party/eggplant.go
danial aca94de06f
All checks were successful
continuous-integration/drone/push Build is passing
fix(camel): 修正链路追踪名称及错误提示优化
- 调整Camel相关函数的链路追踪span名称,保持一致性
- 请求失败时若包含“不匹配”,错误信息追加“请按照正确金额重新提交”
- 修改Careless相关逻辑,更新URL匹配规则
- 修正测试用例中的IP固定值和请求地址
- 优化FavorableClouds提交订单HTTP请求,统一使用resty客户端并添加代理传递
- 修复Jinke支付通知链路追踪span名称及事件描述
- 调整ScanController中SubmitPool协程的context传递,避免丢失父context
2025-12-18 17:31:25 +08:00

483 lines
14 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package third_party
import (
"context"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"encoding/json"
"gateway/internal/config"
"gateway/internal/models/merchant"
"gateway/internal/models/merchant_deploy"
"gateway/internal/models/order"
"gateway/internal/models/payfor"
"gateway/internal/models/road"
"gateway/internal/models/supply_model"
"gateway/internal/otelTrace"
"gateway/internal/service"
"gateway/internal/service/client"
"gateway/internal/service/supplier"
"gateway/internal/service/supplier/third_party/pool/card_sender"
"gateway/internal/utils"
"strconv"
"time"
"github.com/beego/beego/v2/client/httplib"
"github.com/beego/beego/v2/server/web"
"github.com/bytedance/sonic"
"github.com/duke-git/lancet/v2/convertor"
"github.com/widuu/gojson"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"go.uber.org/zap"
)
type EggplantImpl struct {
web.Controller
}
// HasDependencyHTML 是否有单独的支付页面
func (c *EggplantImpl) HasDependencyHTML() bool {
return false
}
func (c *EggplantImpl) SendCard(ctx context.Context, jsonStr string, cardInfo supplier.RedeemCardInfo, attach string, road road.RoadInfo, merchantInfo merchant.MerchantInfo, roadInfo road.RoadInfo) (bool, string) {
returnIfAmountErr := gojson.Json(jsonStr).Get("returnIfAmountErr").Tostring()
orderAmount, err := (&cardTypeQuery{
OrderNo: attach,
QueryType: gojson.Json(roadInfo.Params).Get("queryType").Tostring(),
CardNo: cardInfo.CardNo,
CardPwd: cardInfo.Data,
Balance: cardInfo.GetFaceTypeFloat(ctx),
}).GetBalance(ctx)
if returnIfAmountErr == "1" && err != nil {
return false, err.Error()
}
cardInfo.FaceType = strconv.FormatFloat(orderAmount, 'f', 2, 64)
merchantDeployInfo := merchant_deploy.GetMerchantDeployByUidAndRoadUid(ctx, merchantInfo.MerchantUid, road.RoadUid)
if merchantDeployInfo == nil {
return false, "商户配置不存在"
}
if merchantDeployInfo.SubmitStrategy == merchant_deploy.SUBMIT_STRATEGY_POOL {
if err := orderPoolService.PushOrder(ctx, card_sender.SendCardTask{
CardInfo: cardInfo,
RoadUid: road.RoadUid,
LocalOrderID: attach,
SendCardTaskType: card_sender.SendCardTaskTypeEnumEggplant,
NeedQuery: gojson.Json(road.Params).Get("needQuery").Tostring() == "1",
}); err != nil {
otelTrace.Logger.WithContext(ctx).Error("推送订单失败", zap.Error(err))
return false, err.Error()
}
return true, "订单提交中"
}
if err := orderPoolService.SubmitOrder(ctx, card_sender.SendCardTask{
CardInfo: cardInfo,
RoadUid: road.RoadUid,
LocalOrderID: attach,
SendCardTaskType: card_sender.SendCardTaskTypeEnumEggplant,
NeedQuery: gojson.Json(road.Params).Get("needQuery").Tostring() == "1",
}); err != nil {
return false, err.Error()
}
return true, "订单提交中"
}
func (c *EggplantImpl) Scan(ctx context.Context, orderInfo order.OrderInfo, roadInfo road.RoadInfo, merchantInfo merchant.MerchantInfo) supplier.ScanData {
ctx, span := otelTrace.Span(ctx, "茄子卡", "Scan", trace.WithAttributes(
attribute.String("BankOrderId", orderInfo.BankOrderId),
attribute.String("MerchantUid", orderInfo.MerchantUid),
attribute.String("ExValue", orderInfo.ExValue),
))
defer span.End()
cdata := supplier.RedeemCardInfo{}
err := json.Unmarshal([]byte(orderInfo.ExValue), &cdata)
if err != nil {
otelTrace.Logger.WithContext(ctx).Error("格式化数据失败", zap.String("ExValue", orderInfo.ExValue))
return supplier.ScanData{Status: "-1", Msg: "订单有误,请稍后再试"}
}
ok, str := c.SendCard(ctx, roadInfo.Params, cdata, orderInfo.BankOrderId, roadInfo, merchantInfo, roadInfo)
var scanData supplier.ScanData
if !ok {
scanData = supplier.ScanData{
Status: "-1",
Msg: "失败:" + str,
BankNo: orderInfo.MerchantOrderId,
OrderNo: orderInfo.BankOrderId,
ReturnData: str,
}
return scanData
}
scanData.Status = "00"
scanData.OrderNo = orderInfo.BankOrderId
scanData.BankNo = orderInfo.MerchantOrderId
scanData.OrderPrice = strconv.FormatFloat(orderInfo.OrderAmount, 'f', 2, 64)
scanData.ReturnData = str
//scanData.PayUrl = forwardUrl
return scanData
}
// KMEncrypt 加密卡密
func (c *EggplantImpl) sign(kf, appSecret string) (string, error) {
secret := utils.GetMd5Lower(appSecret)[:16] // 加密秘钥
block, err := aes.NewCipher([]byte(secret))
if err != nil {
return "", err
}
// 数据填充
plaintext := utils.PadType(kf)
iv := "0102030405060708"
mode := cipher.NewCBCEncrypter(block, []byte(iv))
mode.CryptBlocks(plaintext, plaintext)
return base64.StdEncoding.EncodeToString(plaintext), nil
}
func (c *EggplantImpl) PayNotify() {
ctx := c.Ctx.Request.Context()
ctx, span := otelTrace.Span(ctx, "EggplantImpl", "EggplantImpl.PayNotify")
defer span.End()
var params struct {
OrderId string `json:"order_no" form:"order_no"`
Amount string `json:"amount" form:"amount"`
PayAmount string `json:"pay_amount" form:"pay_amount"`
Sign string `json:"sign" form:"sign"`
Status int `json:"status" form:"status"`
}
err := c.BindForm(&params)
if err != nil {
otelTrace.Logger.WithContext(ctx).Error("解析参数失败", zap.Error(err))
c.Ctx.WriteString("FAIL")
return
}
span.SetAttributes(
attribute.String("orderId", params.OrderId),
attribute.String("amount", params.Amount),
attribute.String("payAmount", params.PayAmount),
attribute.String("status", strconv.Itoa(params.Status)),
)
localId, err := orderPoolService.GetLocalIdByOrderId(ctx, params.OrderId)
var orderInfo order.OrderInfo
if err != nil {
orderInfo = order.GetOrderByPoolOrderId(ctx, params.OrderId)
if orderInfo.Id == 0 {
otelTrace.Logger.WithContext(ctx).Error("获取本地订单ID失败", zap.Error(err))
c.Ctx.WriteString("FAIL")
return
}
} else {
orderInfo = order.GetOrderByBankOrderId(ctx, localId)
}
if orderInfo.BankOrderId == "" || len(orderInfo.BankOrderId) == 0 {
otelTrace.Logger.WithContext(ctx).Error("【茄子】回调的订单号不存在,订单号=", zap.String("attach", params.OrderId))
c.Ctx.WriteString("FAIL")
return
}
if orderInfo.Status != "wait" {
c.Ctx.WriteString("订单已经回调")
return
}
roadInfo := road.GetRoadInfoByRoadUid(ctx, orderInfo.RoadUid)
if roadInfo.RoadUid == "" || len(roadInfo.RoadUid) == 0 {
otelTrace.Logger.WithContext(ctx).Error("【茄子】支付通道已经关系或者删除,不进行回调")
c.Ctx.WriteString("FAIL")
return
}
if params.Status == 3 {
successAmount, _ := strconv.ParseFloat(params.PayAmount, 64)
isOk := false
if successAmount == orderInfo.OrderAmount {
isOk = service.SolvePaySuccess(ctx, orderInfo.BankOrderId, successAmount, orderInfo.MerchantUid, "支付成功")
} else {
SolvePaySuccessByAmountDifferent(ctx, orderInfo.BankOrderId, successAmount, orderInfo.BankOrderId, convertor.ToString(params))
}
if isOk {
c.Ctx.WriteString("success")
} else {
c.Ctx.WriteString("fail")
}
return
}
cdata := supplier.RedeemCardInfo{}
_ = json.Unmarshal([]byte(orderInfo.ExValue), &cdata)
errMsg := "支付失败"
if gojson.Json(roadInfo.Params).Get("jvnkaQuery").Tostring() == "1" {
msg, _ := client.NewHeePayClient().ToString(ctx, &client.QueryCardInput{
OrderId: orderInfo.BankOrderId,
CardNumber: cdata.CardNo,
CardPassword: cdata.Data,
})
if msg != "" {
errMsg += "" + msg
}
}
if _, err = (&cardTypeQuery{
OrderNo: orderInfo.BankOrderId,
QueryType: gojson.Json(roadInfo.Params).Get("queryType").Tostring(),
CardNo: cdata.CardNo,
CardPwd: cdata.Data,
Balance: orderInfo.OrderAmount,
}).GetBalance(ctx); err != nil {
errMsg += "" + err.Error()
}
isOk := service.SolvePayFail(ctx, orderInfo.BankOrderId, orderInfo.BankOrderId, errMsg)
if isOk {
c.Ctx.WriteString("success")
} else {
c.Ctx.WriteString("fail")
}
}
// 查询订单
func (c *EggplantImpl) bindSearch(ctx context.Context, orderNo string) bool {
req := httplib.NewBeegoRequestWithCtx(ctx, "http://api.qixika.com/blindSearch.html", "POST")
req.Param("orderId", orderNo)
type bindSearchResp struct {
Code string `json:"code"`
Message string `json:"message"`
Data struct {
CustomerId int `json:"customerId"`
OrderId string `json:"orderId"`
SystemOrderId string `json:"systemOrderId"`
Message string `json:"message"`
Status string `json:"status"`
} `json:"data"`
}
var resp bindSearchResp
err := req.ToJSON(&resp)
if err != nil {
otelTrace.Logger.WithContext(ctx).Error("【茄子】查询订单失败", zap.Error(err))
return false
}
otelTrace.Logger.WithContext(ctx).Info("【茄子】查询订单返回", zap.Any("resp", resp))
return resp.Data.Status == "0"
}
func (c *EggplantImpl) PayQuery(orderInfo order.OrderInfo, roadInfo road.RoadInfo) bool {
params := map[string]any{}
ctx := context.Background()
cardData, err := sonic.GetFromString(orderInfo.CardReturnData)
if err != nil {
return false
}
orderId, err := cardData.Get("order_id").String()
if err != nil {
return false
}
params["order_id"] = orderId
params["app_key"] = gojson.Json(roadInfo.Params).Get("appKey").Tostring()
params["timestamp"] = strconv.FormatInt(time.Now().Unix(), 10)
params["sign"] = utils.GetMD5SignMF(params, gojson.Json(roadInfo.Params).Get("appSecret").Tostring())
cfg := config.Config{}
url, err := cfg.GetMFCardQueryUrl()
req := httplib.Post(url)
marshal, err := json.Marshal(params)
if err != nil {
otelTrace.Logger.WithContext(ctx).Error("Map转化为byte数组失败,异常。", zap.Error(err))
return false
}
otelTrace.Logger.WithContext(ctx).Info("请求参数" + string(marshal))
req.Header("Content-Type", "application/json")
req.Body(marshal)
req.Header("Accept-Charset", "utf-8")
response, err := req.String()
if err != nil {
otelTrace.Logger.WithContext(ctx).Error("MF GetToken 请求失败:", zap.Error(err))
return false
}
otelTrace.Logger.WithContext(ctx).Info("远端请求返回数据", zap.String("response", response))
resData, err := sonic.GetFromString(response)
if err != nil {
return false
}
resStatus, err := resData.Get("data").Get("status").Int64()
if err != nil {
return false
}
resCode, err := resData.Get("code").Int64()
if err != nil {
return false
}
if resCode == 0 && resStatus == 9 {
return true
}
return false
}
func (c *EggplantImpl) PayQueryV2(orderInfo order.OrderInfo, roadInfo road.RoadInfo) supply_model.MsgModel {
params := map[string]any{}
ctx := context.Background()
cardData, err := sonic.GetFromString(orderInfo.CardReturnData)
if err != nil {
return supply_model.CardMsgErr
}
orderId, err := cardData.Get("order_id").String()
if err != nil {
return supply_model.CardMsgErr
}
params["order_id"] = orderId
params["app_key"] = gojson.Json(roadInfo.Params).Get("appKey").Tostring()
params["timestamp"] = strconv.FormatInt(time.Now().Unix(), 10)
params["sign"] = utils.GetMD5SignMF(params, gojson.Json(roadInfo.Params).Get("appSecret").Tostring())
cfg := config.Config{}
url, err := cfg.GetMFCardQueryUrl()
req := httplib.Post(url)
marshal, err := json.Marshal(params)
if err != nil {
otelTrace.Logger.WithContext(ctx).Error("Map转化为byte数组失败,异常。", zap.Error(err))
// fmt.Printf("Map转化为byte数组失败,异常:%s\n",zap.Error(err))
return supply_model.DataErr
}
otelTrace.Logger.WithContext(ctx).Info("请求参数" + string(marshal))
req.Header("Content-Type", "application/json")
req.Body(marshal)
req.Header("Accept-Charset", "utf-8")
response, err := req.String()
if err != nil {
return supply_model.RemoteDataErr
}
otelTrace.Logger.WithContext(ctx).Info("远端请求返回数据", zap.String("response", response))
resData, err := sonic.GetFromString(response)
if err != nil {
return supply_model.RemoteDataErr
}
resStatus, err := resData.Get("data").Get("status").Int64()
if err != nil {
return supply_model.RemoteDataErr
}
resCode, err := resData.Get("code").Int64()
if err != nil {
return supply_model.RemoteDataErr
}
if resCode == 0 {
switch resStatus {
case 9:
return supply_model.RemoteSuccess
case 2, 3, 4:
return supply_model.RemoteDataDealing
case 7:
return supply_model.RemoteDataHandErr
case 8:
return supply_model.RemoteDataHealingErr
}
}
return supply_model.RemoteDataErr
}
func (c *EggplantImpl) PayFor(info payfor.PayforInfo) string {
return ""
}
func (c *EggplantImpl) PayForQuery(payFor payfor.PayforInfo) (string, string) {
cfg := config.Config{}
url, err := cfg.GetMFCardQueryUrl()
ctx := context.Background()
if err != nil {
return config.PAYFOR_FAIL, ""
}
params := map[string]string{}
params["order_id"] = payFor.BankOrderId
params["app_key"] = gojson.Json("").Get("appKey").Tostring()
req := httplib.Post(url)
marshal, err := json.Marshal(params)
if err != nil {
otelTrace.Logger.WithContext(ctx).Error("Map转化为byte数组失败,异常。", zap.Error(err))
// fmt.Printf("Map转化为byte数组失败,异常:%s\n",zap.Error(err))
return config.PAYFOR_FAIL, "内部错误请稍后再试试"
}
otelTrace.Logger.WithContext(ctx).Info("请求参数" + string(marshal))
req.Header("Content-Type", "application/json")
req.Body(marshal)
req.Header("Accept-Charset", "utf-8")
response, err := req.String()
if err != nil {
otelTrace.Logger.WithContext(ctx).Error("MF GetToken 请求失败:", zap.Error(err))
return config.PAYFOR_FAIL, ""
}
otelTrace.Logger.WithContext(ctx).Info("远端请求返回数据", zap.String("response", response))
if gojson.Json(response).Get("code").Tostring() == "" {
otelTrace.Logger.WithContext(ctx).Error("远程调用失败")
return config.PAYFOR_BANKING, ""
}
if gojson.Json(response).Get("code").Tostring() == "0" {
type data struct {
OrderID int64 `json:"order_id"`
CardNo string `json:"card_no"`
CardPwd string `json:"card_pwd"`
Status int `json:"status"`
RspInfo string `json:"rsp_info"`
FaceVal int `json:"face_val"`
Amount int `json:"amount"`
Discount string `json:"discount"`
}
var d data
err2 := json.Unmarshal([]byte(gojson.Json(response).Get("data").Tostring()), &d)
if err2 != nil {
return config.PAYFOR_FAIL, ""
}
if d.Status == 9 {
return config.PAYFOR_SUCCESS, ""
}
if d.Status == 4 {
return config.PAYFOR_BANKING, ""
}
if d.Status == 7 || d.Status == 8 {
return config.PAYFOR_FAIL, ""
}
}
otelTrace.Logger.WithContext(ctx).Error("远程调用失败")
return config.PAYFOR_BANKING, ""
}
func (c *EggplantImpl) BalanceQuery(roadInfo road.RoadInfo) float64 {
return 0.00
}
func (c *EggplantImpl) PayForNotify() string {
return ""
}