feat: integrate unified payment and wallet refunds
This commit is contained in:
129
backend/api/internal/logic/payment/callback.go
Normal file
129
backend/api/internal/logic/payment/callback.go
Normal file
@@ -0,0 +1,129 @@
|
||||
package payment
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"git.apinb.com/heqiapp/platforms/backend/api/internal/config"
|
||||
"git.apinb.com/heqiapp/platforms/backend/api/internal/impl"
|
||||
"git.apinb.com/heqiapp/platforms/backend/api/internal/models"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/wechatpay-apiv3/wechatpay-go/core/auth/verifiers"
|
||||
"github.com/wechatpay-apiv3/wechatpay-go/core/downloader"
|
||||
"github.com/wechatpay-apiv3/wechatpay-go/core/notify"
|
||||
"github.com/wechatpay-apiv3/wechatpay-go/services/payments"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
func digest(value string) string {
|
||||
sum := sha256.Sum256([]byte(value))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// AlipayNotify 验证支付宝证书签名、商户身份、金额和状态后幂等入账。
|
||||
func AlipayNotify(ctx *gin.Context) {
|
||||
client, err := alipayClient()
|
||||
if err != nil {
|
||||
ctx.String(http.StatusServiceUnavailable, "failure")
|
||||
return
|
||||
}
|
||||
if err = ctx.Request.ParseForm(); err != nil || client.VerifySign(ctx, ctx.Request.PostForm) != nil {
|
||||
ctx.String(http.StatusBadRequest, "failure")
|
||||
return
|
||||
}
|
||||
values := ctx.Request.PostForm
|
||||
amount, amountErr := strconv.ParseFloat(values.Get("total_amount"), 64)
|
||||
if amountErr != nil || values.Get("app_id") != config.Spec.Payment.Alipay.AppID || (values.Get("trade_status") != "TRADE_SUCCESS" && values.Get("trade_status") != "TRADE_FINISHED") {
|
||||
ctx.String(http.StatusBadRequest, "failure")
|
||||
return
|
||||
}
|
||||
err = complete(values.Get("out_trade_no"), values.Get("trade_no"), int64(amount*100+0.5), "alipay", digest(values.Encode()))
|
||||
if err != nil {
|
||||
ctx.String(http.StatusConflict, "failure")
|
||||
return
|
||||
}
|
||||
ctx.String(http.StatusOK, "success")
|
||||
}
|
||||
|
||||
// WechatNotify 使用微信平台证书验签并解密 API v3 通知后幂等入账。
|
||||
func WechatNotify(ctx *gin.Context) {
|
||||
if _, err := wechatClient(ctx); err != nil {
|
||||
ctx.JSON(http.StatusServiceUnavailable, gin.H{"code": "FAIL", "message": "channel unavailable"})
|
||||
return
|
||||
}
|
||||
visitor := downloader.MgrInstance().GetCertificateVisitor(config.Spec.Payment.Wechat.MerchantID)
|
||||
handler := notify.NewNotifyHandler(config.Spec.Payment.Wechat.APIv3Key, verifiers.NewSHA256WithRSAVerifier(visitor))
|
||||
transaction := new(payments.Transaction)
|
||||
if _, err := handler.ParseNotifyRequest(ctx, ctx.Request, transaction); err != nil || transaction.OutTradeNo == nil || transaction.Amount == nil || transaction.Amount.Total == nil || transaction.TradeState == nil || *transaction.TradeState != "SUCCESS" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"code": "FAIL", "message": "invalid notification"})
|
||||
return
|
||||
}
|
||||
tradeNo := ""
|
||||
if transaction.TransactionId != nil {
|
||||
tradeNo = *transaction.TransactionId
|
||||
}
|
||||
if err := complete(*transaction.OutTradeNo, tradeNo, *transaction.Amount.Total, "wechat", digest(transaction.String())); err != nil {
|
||||
ctx.JSON(http.StatusConflict, gin.H{"code": "FAIL", "message": "payment conflict"})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, gin.H{"code": "SUCCESS", "message": "成功"})
|
||||
}
|
||||
|
||||
func complete(paymentNo, tradeNo string, amount int64, channel, callbackDigest string) error {
|
||||
return impl.DBService.Transaction(func(tx *gorm.DB) error {
|
||||
var order models.PaymentOrder
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("payment_no = ?", paymentNo).First(&order).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if order.PaymentStatus == StatusPaid {
|
||||
return nil
|
||||
}
|
||||
if order.Channel != channel || order.Amount != amount {
|
||||
return errors.New("payment identity or amount mismatch")
|
||||
}
|
||||
if time.Now().After(order.ExpiresAt) {
|
||||
return tx.Model(&order).Updates(map[string]any{"payment_status": 50, "channel_trade_no": tradeNo, "callback_digest": callbackDigest, "failure_code": "PAID_AFTER_EXPIRED"}).Error
|
||||
}
|
||||
now := time.Now()
|
||||
if err := tx.Model(&order).Updates(map[string]any{"payment_status": StatusPaid, "channel_trade_no": tradeNo, "callback_digest": callbackDigest, "paid_at": &now}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
switch order.BusinessType {
|
||||
case "ec_order":
|
||||
return tx.Model(&models.EcOrder{}).Where("identity = ? AND order_status = ?", order.BusinessIdentity, 16).Updates(map[string]any{"order_status": 18, "paid_at": &now}).Error
|
||||
case "gasorder":
|
||||
return tx.Model(&models.GasorderBasic{}).Where("identity = ? AND order_status IN ?", order.BusinessIdentity, []int{16, 18}).Update("order_status", 35).Error
|
||||
case "recharge":
|
||||
return completeRecharge(tx, order, now)
|
||||
}
|
||||
return errors.New("unsupported payment business")
|
||||
})
|
||||
}
|
||||
|
||||
func completeRecharge(tx *gorm.DB, payment models.PaymentOrder, now time.Time) error {
|
||||
var recharge models.WalletRechargeOrder
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("identity = ? AND recharge_status = ?", payment.BusinessIdentity, 10).First(&recharge).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
var wallet models.WalletBasic
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&wallet, recharge.WalletBasicID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
wallet.Balance += payment.Amount
|
||||
if err := tx.Model(&wallet).Update("balance", wallet.Balance).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Model(&recharge).Updates(map[string]any{"recharge_status": 23, "completed_at": &now}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
date := now.In(time.Local)
|
||||
return tx.Create(&models.WalletRecord{Entity: models.Entity{Identity: models.NewIdentity(), Status: 1}, WalletBasicID: wallet.ID,
|
||||
RecordNo: "WR" + now.Format("20060102150405.000000"), RequestNo: "recharge:" + recharge.Identity, Direction: "income", TradeType: "recharge",
|
||||
Amount: payment.Amount, BalanceAfter: wallet.Balance, WithdrawalBalanceAfter: wallet.WithdrawalBalance, InTradeNo: recharge.RechargeNo,
|
||||
PayChannel: payment.Channel, OperatorIdentity: payment.UserIdentity, Ymd: int32(date.Year()*10000 + int(date.Month())*100 + date.Day()), Ym: int32(date.Year()*100 + int(date.Month()))}).Error
|
||||
}
|
||||
68
backend/api/internal/logic/payment/close.go
Normal file
68
backend/api/internal/logic/payment/close.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package payment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.apinb.com/heqiapp/platforms/backend/api/internal/config"
|
||||
"git.apinb.com/heqiapp/platforms/backend/api/internal/impl"
|
||||
"git.apinb.com/heqiapp/platforms/backend/api/internal/models"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/smartwalle/alipay/v3"
|
||||
)
|
||||
|
||||
// CloseExpired 批量关闭已过期的渠道支付单;单笔失败留待下一轮安全重试。
|
||||
func CloseExpired(ctx context.Context, limit int) (int, error) {
|
||||
var orders []models.PaymentOrder
|
||||
if err := impl.DBService.Where("payment_status = ? AND expires_at <= ?", StatusPending, time.Now()).Order("expires_at asc").Limit(limit).Find(&orders).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
closed := 0
|
||||
for _, order := range orders {
|
||||
if err := closeChannelOrder(ctx, order); err != nil {
|
||||
continue
|
||||
}
|
||||
now := time.Now()
|
||||
result := impl.DBService.Model(&models.PaymentOrder{}).Where("id = ? AND payment_status = ?", order.ID, StatusPending).Updates(map[string]any{"payment_status": StatusClosed, "closed_at": &now})
|
||||
if result.Error == nil && result.RowsAffected == 1 {
|
||||
closed++
|
||||
}
|
||||
}
|
||||
return closed, nil
|
||||
}
|
||||
|
||||
func closeChannelOrder(ctx context.Context, order models.PaymentOrder) error {
|
||||
if order.Channel == "alipay" {
|
||||
client, err := alipayClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = client.TradeClose(ctx, alipay.TradeClose{OutTradeNo: order.PaymentNo})
|
||||
return err
|
||||
}
|
||||
if order.Channel == "wechat" {
|
||||
client, err := wechatClient(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = client.Post(ctx, fmt.Sprintf("https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/%s/close", order.PaymentNo), map[string]string{"mchid": config.Spec.Payment.Wechat.MerchantID})
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CloseExpiredHandler 只接受 Worker 共享凭证,不暴露为平台用户动作。
|
||||
func CloseExpiredHandler(ctx *gin.Context) {
|
||||
if config.Spec.Payment.InternalServiceToken == "" || ctx.GetHeader("X-Heqi-Worker-Token") != config.Spec.Payment.InternalServiceToken {
|
||||
ctx.AbortWithStatus(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
count, err := CloseExpired(ctx, 100)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "close expired payments failed"})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, gin.H{"closed": count})
|
||||
}
|
||||
139
backend/api/internal/logic/payment/provider.go
Normal file
139
backend/api/internal/logic/payment/provider.go
Normal file
@@ -0,0 +1,139 @@
|
||||
// Package payment 统一承载支付宝、微信和钱包支付请求及渠道回调。
|
||||
package payment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"git.apinb.com/heqiapp/platforms/backend/api/internal/config"
|
||||
"git.apinb.com/heqiapp/platforms/backend/api/internal/models"
|
||||
"github.com/smartwalle/alipay/v3"
|
||||
wechatcore "github.com/wechatpay-apiv3/wechatpay-go/core"
|
||||
"github.com/wechatpay-apiv3/wechatpay-go/core/option"
|
||||
wechatapp "github.com/wechatpay-apiv3/wechatpay-go/services/payments/app"
|
||||
wechatjsapi "github.com/wechatpay-apiv3/wechatpay-go/services/payments/jsapi"
|
||||
wechatnative "github.com/wechatpay-apiv3/wechatpay-go/services/payments/native"
|
||||
"github.com/wechatpay-apiv3/wechatpay-go/utils"
|
||||
)
|
||||
|
||||
var ErrChannelUnavailable = errors.New("payment channel is not configured")
|
||||
|
||||
func money(amount int64) string { return fmt.Sprintf("%d.%02d", amount/100, amount%100) }
|
||||
|
||||
func createChannelOrder(ctx context.Context, order models.PaymentOrder, openID string) (string, error) {
|
||||
switch order.Channel {
|
||||
case "alipay":
|
||||
return createAlipayOrder(order)
|
||||
case "wechat":
|
||||
return createWechatOrder(ctx, order, openID)
|
||||
default:
|
||||
return "", errors.New("unsupported payment channel")
|
||||
}
|
||||
}
|
||||
|
||||
func alipayClient() (*alipay.Client, error) {
|
||||
cfg := config.Spec.Payment.Alipay
|
||||
if !cfg.Enabled || cfg.AppID == "" || cfg.PrivateKeyPath == "" {
|
||||
return nil, ErrChannelUnavailable
|
||||
}
|
||||
privateKey, err := os.ReadFile(cfg.PrivateKeyPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client, err := alipay.New(cfg.AppID, string(privateKey), cfg.Production)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = client.LoadAppCertPublicKeyFromFile(cfg.AppPublicCertPath); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = client.LoadAliPayRootCertFromFile(cfg.AlipayRootCertPath); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = client.LoadAlipayCertPublicKeyFromFile(cfg.AlipayPublicCertPath); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func createAlipayOrder(order models.PaymentOrder) (string, error) {
|
||||
client, err := alipayClient()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
trade := alipay.Trade{NotifyURL: config.Spec.Payment.Alipay.NotifyURL, ReturnURL: config.Spec.Payment.Alipay.ReturnURL,
|
||||
Subject: order.Subject, OutTradeNo: order.PaymentNo, TotalAmount: money(order.Amount), TimeoutExpress: fmt.Sprintf("%dm", config.Spec.Payment.ExpireMinutes)}
|
||||
if order.PayType == "app" {
|
||||
trade.ProductCode = "QUICK_MSECURITY_PAY"
|
||||
return client.TradeAppPay(alipay.TradeAppPay{Trade: trade})
|
||||
}
|
||||
if order.PayType == "wap" {
|
||||
trade.ProductCode = "QUICK_WAP_WAY"
|
||||
value, err := client.TradeWapPay(alipay.TradeWapPay{Trade: trade})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return value.String(), nil
|
||||
}
|
||||
return "", errors.New("unsupported alipay product")
|
||||
}
|
||||
|
||||
func wechatClient(ctx context.Context) (*wechatcore.Client, error) {
|
||||
cfg := config.Spec.Payment.Wechat
|
||||
if !cfg.Enabled || cfg.MerchantID == "" || cfg.MerchantPrivateKeyPath == "" || len(cfg.APIv3Key) != 32 {
|
||||
return nil, ErrChannelUnavailable
|
||||
}
|
||||
key, err := utils.LoadPrivateKeyWithPath(cfg.MerchantPrivateKeyPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return wechatcore.NewClient(ctx, option.WithWechatPayAutoAuthCipher(cfg.MerchantID, cfg.MerchantCertificateSerial, key, cfg.APIv3Key))
|
||||
}
|
||||
|
||||
func createWechatOrder(ctx context.Context, order models.PaymentOrder, openID string) (string, error) {
|
||||
cfg := config.Spec.Payment.Wechat
|
||||
client, err := wechatClient(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
marshal := func(value any) (string, error) { raw, err := json.Marshal(value); return string(raw), err }
|
||||
switch order.PayType {
|
||||
case "app":
|
||||
resp, _, err := (&wechatapp.AppApiService{Client: client}).PrepayWithRequestPayment(ctx, wechatapp.PrepayRequest{
|
||||
Appid: wechatcore.String(cfg.AppAppID), Mchid: wechatcore.String(cfg.MerchantID), Description: wechatcore.String(order.Subject),
|
||||
OutTradeNo: wechatcore.String(order.PaymentNo), TimeExpire: &order.ExpiresAt, NotifyUrl: wechatcore.String(cfg.NotifyURL), Amount: &wechatapp.Amount{Total: wechatcore.Int64(order.Amount)}})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return marshal(resp)
|
||||
case "jsapi", "mini":
|
||||
if strings.TrimSpace(openID) == "" {
|
||||
return "", errors.New("openid is required")
|
||||
}
|
||||
appid := cfg.OfficialAccountAppID
|
||||
if order.PayType == "mini" {
|
||||
appid = cfg.MiniProgramAppID
|
||||
}
|
||||
resp, _, err := (&wechatjsapi.JsapiApiService{Client: client}).PrepayWithRequestPayment(ctx, wechatjsapi.PrepayRequest{
|
||||
Appid: wechatcore.String(appid), Mchid: wechatcore.String(cfg.MerchantID), Description: wechatcore.String(order.Subject),
|
||||
OutTradeNo: wechatcore.String(order.PaymentNo), TimeExpire: &order.ExpiresAt, NotifyUrl: wechatcore.String(cfg.NotifyURL),
|
||||
Amount: &wechatjsapi.Amount{Total: wechatcore.Int64(order.Amount)}, Payer: &wechatjsapi.Payer{Openid: wechatcore.String(openID)}})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return marshal(resp)
|
||||
case "native":
|
||||
resp, _, err := (&wechatnative.NativeApiService{Client: client}).Prepay(ctx, wechatnative.PrepayRequest{
|
||||
Appid: wechatcore.String(cfg.AppAppID), Mchid: wechatcore.String(cfg.MerchantID), Description: wechatcore.String(order.Subject),
|
||||
OutTradeNo: wechatcore.String(order.PaymentNo), TimeExpire: &order.ExpiresAt, NotifyUrl: wechatcore.String(cfg.NotifyURL), Amount: &wechatnative.Amount{Total: wechatcore.Int64(order.Amount)}})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return marshal(resp)
|
||||
}
|
||||
return "", errors.New("unsupported wechat product")
|
||||
}
|
||||
166
backend/api/internal/logic/payment/refund.go
Normal file
166
backend/api/internal/logic/payment/refund.go
Normal file
@@ -0,0 +1,166 @@
|
||||
package payment
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"git.apinb.com/heqiapp/platforms/backend/api/internal/config"
|
||||
"git.apinb.com/heqiapp/platforms/backend/api/internal/impl"
|
||||
"git.apinb.com/heqiapp/platforms/backend/api/internal/models"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type RefundItemInput struct {
|
||||
Identity string `json:"identity"`
|
||||
Quantity int `json:"quantity"`
|
||||
}
|
||||
type RefundInput struct {
|
||||
RequestNo, Reason, Description string
|
||||
Items []RefundItemInput
|
||||
}
|
||||
|
||||
// CreateRefund 校验本人订单、退款窗口、履约状态、数量和累计金额后创建待审核退款。
|
||||
func CreateRefund(userID uint64, userIdentity, businessType, businessIdentity string, input RefundInput) (models.PaymentRefund, error) {
|
||||
var result models.PaymentRefund
|
||||
err := impl.DBService.Transaction(func(tx *gorm.DB) error {
|
||||
var pay models.PaymentOrder
|
||||
if err := tx.Where("business_type = ? AND business_identity = ? AND user_identity = ? AND payment_status = ?", businessType, businessIdentity, userIdentity, StatusPaid).Order("paid_at desc").First(&pay).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if pay.PaidAt == nil || time.Now().After(pay.PaidAt.AddDate(0, 0, config.Spec.Payment.RefundWindowDays)) {
|
||||
return errors.New("refund window expired")
|
||||
}
|
||||
var wallet models.WalletBasic
|
||||
if err := tx.Where("owner_type = ? AND owner_identity = ? AND owner_id = ?", "user", userIdentity, userID).First(&wallet).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
items, whole, err := refundItems(tx, businessType, businessIdentity, userID, input.Items)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var used int64
|
||||
if err := tx.Model(&models.PaymentRefund{}).Where("payment_order_id = ? AND refund_status IN ?", pay.ID, []int{10, 20}).Select("COALESCE(SUM(amount),0)").Scan(&used).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
var amount int64
|
||||
for _, item := range items {
|
||||
amount += item.Amount
|
||||
}
|
||||
if whole {
|
||||
amount = pay.Amount - used
|
||||
}
|
||||
if amount <= 0 || used+amount > pay.Amount {
|
||||
return errors.New("refund amount exceeds payment")
|
||||
}
|
||||
result = models.PaymentRefund{Entity: models.Entity{Identity: models.NewIdentity(), Status: 1}, RefundStatus: 10, PaymentOrderID: pay.ID, WalletBasicID: wallet.ID,
|
||||
RefundNo: "RF" + time.Now().Format("20060102150405.000000"), RequestNo: input.RequestNo, BusinessType: businessType, BusinessIdentity: businessIdentity,
|
||||
UserIdentity: userIdentity, Amount: amount, Reason: input.Reason, Description: input.Description}
|
||||
if err := tx.Create(&result).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for index := range items {
|
||||
items[index].PaymentRefundID = result.ID
|
||||
items[index].Identity = models.NewIdentity()
|
||||
if err := tx.Create(&items[index]).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return result, err
|
||||
}
|
||||
|
||||
func refundItems(tx *gorm.DB, businessType, identity string, userID uint64, requested []RefundItemInput) ([]models.PaymentRefundItem, bool, error) {
|
||||
if len(requested) == 0 {
|
||||
return nil, false, errors.New("refund items are required")
|
||||
}
|
||||
result := make([]models.PaymentRefundItem, 0, len(requested))
|
||||
whole := true
|
||||
switch businessType {
|
||||
case "ec_order":
|
||||
var order models.EcOrder
|
||||
if err := tx.Where("identity = ? AND user_account_id = ? AND order_status = ? AND logistics_status < ?", identity, userID, 18, 30).First(&order).Error; err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
var all []models.EcOrderItem
|
||||
if err := tx.Where("ec_order_id = ?", order.ID).Find(&all).Error; err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
by := map[string]models.EcOrderItem{}
|
||||
for _, value := range all {
|
||||
by[value.Identity] = value
|
||||
}
|
||||
for _, request := range requested {
|
||||
value, ok := by[request.Identity]
|
||||
if !ok || request.Quantity <= 0 || request.Quantity > value.Quantity {
|
||||
return nil, false, gorm.ErrInvalidData
|
||||
}
|
||||
if request.Quantity != value.Quantity {
|
||||
whole = false
|
||||
}
|
||||
result = append(result, models.PaymentRefundItem{OrderItemIdentity: value.Identity, Quantity: request.Quantity, Amount: value.SaleAmount * int64(request.Quantity)})
|
||||
}
|
||||
if len(requested) != len(all) {
|
||||
whole = false
|
||||
}
|
||||
case "gasorder":
|
||||
var order models.GasorderBasic
|
||||
if err := tx.Where("identity = ? AND user_account_id = ? AND order_status = ?", identity, userID, 35).First(&order).Error; err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
var all []models.GasorderItem
|
||||
if err := tx.Where("gasorder_basic_id = ?", order.ID).Find(&all).Error; err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
by := map[string]models.GasorderItem{}
|
||||
for _, value := range all {
|
||||
by[value.Identity] = value
|
||||
}
|
||||
for _, request := range requested {
|
||||
value, ok := by[request.Identity]
|
||||
if !ok || request.Quantity != 1 {
|
||||
return nil, false, gorm.ErrInvalidData
|
||||
}
|
||||
result = append(result, models.PaymentRefundItem{OrderItemIdentity: value.Identity, Quantity: 1, Amount: value.UnitPrice})
|
||||
}
|
||||
if len(requested) != len(all) {
|
||||
whole = false
|
||||
}
|
||||
default:
|
||||
return nil, false, errors.New("business does not support refund")
|
||||
}
|
||||
return result, whole, nil
|
||||
}
|
||||
|
||||
// ReviewRefund 驳回时记录原因;通过时在同一事务中立即增加钱包与不可变流水。
|
||||
func ReviewRefund(identity, reviewer, remark string, approve bool) error {
|
||||
return impl.DBService.Transaction(func(tx *gorm.DB) error {
|
||||
var refund models.PaymentRefund
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("identity = ? AND refund_status = ?", identity, 10).First(&refund).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
now := time.Now()
|
||||
if !approve {
|
||||
if remark == "" {
|
||||
return errors.New("reject reason required")
|
||||
}
|
||||
return tx.Model(&refund).Updates(map[string]any{"refund_status": 30, "review_remark": remark, "reviewer_identity": reviewer, "reviewed_at": &now}).Error
|
||||
}
|
||||
var wallet models.WalletBasic
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&wallet, refund.WalletBasicID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
wallet.Balance += refund.Amount
|
||||
if err := tx.Model(&wallet).Update("balance", wallet.Balance).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Model(&refund).Updates(map[string]any{"refund_status": 20, "review_remark": remark, "reviewer_identity": reviewer, "reviewed_at": &now, "completed_at": &now}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
date := now.In(time.Local)
|
||||
return tx.Create(&models.WalletRecord{Entity: models.Entity{Identity: models.NewIdentity(), Status: 1}, WalletBasicID: wallet.ID, RecordNo: models.NewIdentity(), RequestNo: "refund:" + refund.Identity,
|
||||
Direction: "income", TradeType: "refund", Amount: refund.Amount, BalanceAfter: wallet.Balance, WithdrawalBalanceAfter: wallet.WithdrawalBalance, InTradeNo: refund.RefundNo, PayChannel: "wallet", OperatorIdentity: reviewer,
|
||||
Ymd: int32(date.Year()*10000 + int(date.Month())*100 + date.Day()), Ym: int32(date.Year()*100 + int(date.Month())), Remark: "退款审核:" + remark}).Error
|
||||
})
|
||||
}
|
||||
61
backend/api/internal/logic/payment/service.go
Normal file
61
backend/api/internal/logic/payment/service.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package payment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"git.apinb.com/heqiapp/platforms/backend/api/internal/config"
|
||||
"git.apinb.com/heqiapp/platforms/backend/api/internal/impl"
|
||||
"git.apinb.com/heqiapp/platforms/backend/api/internal/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
StatusPending = 10
|
||||
StatusPaid = 23
|
||||
StatusClosed = 30
|
||||
)
|
||||
|
||||
type CreateInput struct {
|
||||
RequestNo, BusinessType, BusinessIdentity, UserIdentity string
|
||||
Channel, PayType, Subject, OpenID string
|
||||
Amount int64
|
||||
}
|
||||
|
||||
// Create 创建幂等支付单并向渠道请求客户端调起参数。
|
||||
func Create(ctx context.Context, input CreateInput) (models.PaymentOrder, error) {
|
||||
if input.Amount <= 0 || input.RequestNo == "" || input.BusinessIdentity == "" || input.UserIdentity == "" {
|
||||
return models.PaymentOrder{}, gorm.ErrInvalidData
|
||||
}
|
||||
var existing models.PaymentOrder
|
||||
if err := impl.DBService.Where("business_type = ? AND request_no = ?", input.BusinessType, input.RequestNo).First(&existing).Error; err == nil {
|
||||
if existing.BusinessIdentity != input.BusinessIdentity || existing.Amount != input.Amount || existing.Channel != input.Channel || existing.PayType != input.PayType {
|
||||
return existing, errors.New("idempotency conflict")
|
||||
}
|
||||
return existing, nil
|
||||
}
|
||||
order := models.PaymentOrder{Entity: models.Entity{Identity: models.NewIdentity(), Status: 1}, PaymentStatus: StatusPending,
|
||||
PaymentNo: "PAY" + time.Now().Format("20060102150405.000000"), RequestNo: input.RequestNo, BusinessType: input.BusinessType,
|
||||
BusinessIdentity: input.BusinessIdentity, UserIdentity: input.UserIdentity, MerchantIdentity: "platform", Channel: input.Channel,
|
||||
PayType: input.PayType, Amount: input.Amount, Subject: input.Subject, ExpiresAt: time.Now().Add(time.Duration(config.Spec.Payment.ExpireMinutes) * time.Minute)}
|
||||
args, err := createChannelOrder(ctx, order, input.OpenID)
|
||||
if err != nil {
|
||||
return order, err
|
||||
}
|
||||
order.ClientArgs = args
|
||||
if err = impl.DBService.Create(&order).Error; err != nil {
|
||||
return order, err
|
||||
}
|
||||
return order, nil
|
||||
}
|
||||
|
||||
// PublicResponse 仅返回客户端调起支付所需的非密钥参数。
|
||||
func PublicResponse(order models.PaymentOrder) map[string]any {
|
||||
response := map[string]any{"identity": order.Identity, "payment_no": order.PaymentNo, "payment_status": order.PaymentStatus,
|
||||
"channel": order.Channel, "pay_type": order.PayType, "amount": order.Amount, "client_args": order.ClientArgs, "expires_at": order.ExpiresAt}
|
||||
if order.Channel == "wechat" && order.PayType == "app" {
|
||||
response["app_id"] = config.Spec.Payment.Wechat.AppAppID
|
||||
}
|
||||
return response
|
||||
}
|
||||
Reference in New Issue
Block a user