feat(退款): AUG26-006 退款方式选择与原路退款
按 PRD 2.3/2.4/2.5 落地套餐退款的方式矩阵与原路渠道退款: - 退款申请派生并冻结权威实收金额(线上取原成功支付记录,钱包/线下取订单实际收款), 提交人不可填写或修改;按来源支付方式生成可选方式矩阵并在创建、提交、执行前重复校验。 - 审批切换为「每次提交一条不可变审批尝试记录 + 独立企业微信审批实例」,业务标识取尝试 记录主键;终态消费按尝试记录优先、退款申请兜底双读,兼容存量无实例与已关联实例申请。 新增活动退款部分唯一索引 (order_id) WHERE status IN (1,5,6)。 - 本地人工终审保持既有开关,补齐通过入口的 approval_instance_id IS NULL 守卫,使三个 入口一致拒绝已关联审批实例的申请;重提按尝试模式重写(仅已拒绝/已退回/原路失败且无异常)。 - 权益时点:企微通过事务写退款终态、按方式确定的订单态、钱包回款、员工账单冲销与可靠 失效事实;套餐失效/接续/停机仍由既有可靠机制最终一致执行,不把外部调用放入资金事务。 订单支付状态按方式置位:凭证退款与退回原钱包在企微通过时置已退款,原路须渠道明确成功。 - 按官方契约实现微信直连 v3、微信 v2(双向证书)、富友(/commonRefund 与 /refundQuery)、 支付宝四类原路退款;能力只由服务商类型与退款必需凭证完整性决定,无人工开关。 渠道请求号在提交时冻结到尝试记录,并以 channel_submitted_at 条件认领保证资金动作至多 提交一次(重复投递只查询不二次提交);不向任何渠道传递退款结果通知地址。 - 新增 refund:channel:recovery 恢复任务只查询回填;本地查询窗口超期(富友 72 小时、 微信 v2 7 天)转原路退款失败、渠道状态已失败、分类超时未知并置异常转人工,不放行自动 重提以避免重复退款。 - 同步退款 DTO/导出/审计资源与审计查询关联、商户凭证文档,并修正 fuiou 集成契约文档。 迁移 000218(退款尝试与渠道退款事实)、000219(微信 v2 客户端证书凭证)成对提供, 未修改既有迁移;测试库 junhong_cmp_test 完成 up/down/up 与行为核对,未调用真实渠道。
This commit is contained in:
@@ -9,6 +9,7 @@ import (
|
||||
"gorm.io/gorm"
|
||||
|
||||
approvalapp "github.com/break/junhong_cmp_fiber/internal/application/approval"
|
||||
"github.com/break/junhong_cmp_fiber/internal/application/refundapproval"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
@@ -54,7 +55,7 @@ func approvalResources(ctx context.Context, tx *gorm.DB, change approvalapp.Audi
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resources = append(resources, business)
|
||||
resources = append(resources, business...)
|
||||
resources = append(resources, approvalSubmitterResource(change))
|
||||
seenIntegrationIDs := make(map[string]struct{}, len(change.IntegrationIDs))
|
||||
for _, integrationID := range change.IntegrationIDs {
|
||||
@@ -82,30 +83,66 @@ func approvalResources(ctx context.Context, tx *gorm.DB, change approvalapp.Audi
|
||||
return resources, nil
|
||||
}
|
||||
|
||||
func approvalBusinessResource(ctx context.Context, tx *gorm.DB, businessType string, businessID, instanceID uint) (ResourceInput, error) {
|
||||
// approvalBusinessResource 构造审批关联的业务资源。
|
||||
//
|
||||
// 退款审批的业务标识在尝试模式下指向退款审批尝试记录、存量模式下指向退款申请本身,
|
||||
// 因此该分支统一经 refundapproval.ResolveRefundInTx 解析业务归属:主资源固定为解析出的
|
||||
// 退款单,尝试记录存在时再追加一条引用资源,使两种语义在同一审计事件内都可追溯。
|
||||
func approvalBusinessResource(ctx context.Context, tx *gorm.DB, businessType string, businessID, instanceID uint) ([]ResourceInput, error) {
|
||||
id := strconv.FormatUint(uint64(businessID), 10)
|
||||
switch businessType {
|
||||
case constants.ApprovalBusinessTypeRefund:
|
||||
var refund model.RefundRequest
|
||||
if err := tx.WithContext(ctx).First(&refund, businessID).Error; err != nil {
|
||||
return ResourceInput{}, errors.Wrap(errors.CodeDatabaseError, err, "查询审批关联退款单失败")
|
||||
refund, attempt, err := refundapproval.ResolveRefundInTx(ctx, tx, businessID, instanceID)
|
||||
if err != nil {
|
||||
// 提交事务内的「审批申请」审计先于 attachAttemptInstance 执行:此刻尝试记录已写入,
|
||||
// 但 approval_instance_id 仍为空,共享解析器的实例一致性校验必然不命中。
|
||||
// 这里只补一条尚未回写实例的尝试记录解析,其余不一致仍按解析器的冲突错误失败关闭。
|
||||
refund, attempt, err = resolvePendingRefundAttempt(ctx, tx, businessID, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return ResourceInput{
|
||||
Type: constants.AuditResourceRefund, ID: &id, Key: refund.RefundNo, DisplayName: refund.RefundNo,
|
||||
refundID := strconv.FormatUint(uint64(refund.ID), 10)
|
||||
resources := []ResourceInput{{
|
||||
Type: constants.AuditResourceRefund, ID: &refundID, Key: refund.RefundNo, DisplayName: refund.RefundNo,
|
||||
Relation: constants.AuditResourceRelationReference, Role: constants.AuditResourceRoleApprovalBusiness,
|
||||
IdentitySnapshot: map[string]any{
|
||||
"id": refund.ID, "refund_no": refund.RefundNo, "order_id": refund.OrderID, "order_no": refund.OrderNo,
|
||||
"order_type": refund.OrderType, "asset_identifier": refund.AssetIdentifier, "shop_id": refund.ShopID,
|
||||
"requested_refund_amount": refund.RequestedRefundAmount, "actual_received_amount": refund.ActualReceivedAmount,
|
||||
"method": refund.Method, "frozen_actual_received_amount": refund.FrozenActualReceivedAmount,
|
||||
"latest_attempt_id": refund.LatestAttemptID, "channel_refund_status": refund.ChannelRefundStatus,
|
||||
"failure_reason": refund.FailureReason, "anomaly_flag": refund.AnomalyFlag,
|
||||
"approval_instance_id": instanceID, "status": refund.Status,
|
||||
},
|
||||
}, nil
|
||||
}}
|
||||
if attempt == nil {
|
||||
return resources, nil
|
||||
}
|
||||
attemptID := strconv.FormatUint(uint64(attempt.ID), 10)
|
||||
// 客户收款信息是自由文本、凭证是对象存储标识,两者都不进审计快照,只记录存在性与凭证数量。
|
||||
resources = append(resources, ResourceInput{
|
||||
Type: constants.AuditResourceRefundAttempt, ID: &attemptID, Key: attemptID, DisplayName: "退款审批尝试 " + attemptID,
|
||||
Relation: constants.AuditResourceRelationReference, Role: constants.AuditResourceRoleApprovalBusiness,
|
||||
IdentitySnapshot: map[string]any{
|
||||
"id": attempt.ID, "refund_id": attempt.RefundID, "attempt_no": attempt.AttemptNo,
|
||||
"method": attempt.Method, "refund_amount": attempt.RefundAmount,
|
||||
"frozen_actual_received_amount": attempt.FrozenActualReceivedAmount,
|
||||
"approval_instance_id": instanceID,
|
||||
"channel_refund_request_no": attempt.ChannelRefundRequestNo,
|
||||
"submitted_by_account_id": attempt.SubmittedByAccountID,
|
||||
"customer_account_info_present": attempt.CustomerAccountInfo != "",
|
||||
"customer_voucher_count": len(attempt.CustomerVoucherKeys),
|
||||
"created_at": attempt.CreatedAt,
|
||||
},
|
||||
})
|
||||
return resources, nil
|
||||
case constants.ApprovalBusinessTypeOfflineRecharge:
|
||||
var recharge model.AgentRechargeRecord
|
||||
if err := tx.WithContext(ctx).First(&recharge, businessID).Error; err != nil {
|
||||
return ResourceInput{}, errors.Wrap(errors.CodeDatabaseError, err, "查询审批关联充值单失败")
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询审批关联充值单失败")
|
||||
}
|
||||
return ResourceInput{
|
||||
return []ResourceInput{{
|
||||
Type: constants.AuditResourceAgentRecharge, ID: &id, Key: recharge.RechargeNo, DisplayName: recharge.RechargeNo,
|
||||
Relation: constants.AuditResourceRelationReference, Role: constants.AuditResourceRoleApprovalBusiness,
|
||||
IdentitySnapshot: map[string]any{
|
||||
@@ -114,13 +151,13 @@ func approvalBusinessResource(ctx context.Context, tx *gorm.DB, businessType str
|
||||
"payment_method": recharge.PaymentMethod, "payment_channel": recharge.PaymentChannel,
|
||||
"approval_instance_id": instanceID, "status": recharge.Status,
|
||||
},
|
||||
}, nil
|
||||
}}, nil
|
||||
case constants.ApprovalBusinessTypeEmployeeCollection:
|
||||
var attempt model.EmployeeCollectionApplicationAttempt
|
||||
if err := tx.WithContext(ctx).First(&attempt, businessID).Error; err != nil {
|
||||
return ResourceInput{}, errors.Wrap(errors.CodeDatabaseError, err, "查询审批关联核销审批尝试记录失败")
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询审批关联核销审批尝试记录失败")
|
||||
}
|
||||
return ResourceInput{
|
||||
return []ResourceInput{{
|
||||
Type: constants.AuditResourceEmployeeCollectionAttempt, ID: &id,
|
||||
Key: id, DisplayName: "审批尝试 " + id,
|
||||
Relation: constants.AuditResourceRelationReference, Role: constants.AuditResourceRoleApprovalBusiness,
|
||||
@@ -128,13 +165,13 @@ func approvalBusinessResource(ctx context.Context, tx *gorm.DB, businessType str
|
||||
"id": attempt.ID, "application_id": attempt.ApplicationID, "attempt_no": attempt.AttemptNo,
|
||||
"paid_amount": attempt.PaidAmount, "approval_instance_id": instanceID,
|
||||
},
|
||||
}, nil
|
||||
}}, nil
|
||||
case constants.ApprovalBusinessTypeAgentDistribution:
|
||||
var registration model.AgentDistributionRegistration
|
||||
if err := tx.WithContext(ctx).First(®istration, businessID).Error; err != nil {
|
||||
return ResourceInput{}, errors.Wrap(errors.CodeDatabaseError, err, "查询审批关联扫码注册记录失败")
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询审批关联扫码注册记录失败")
|
||||
}
|
||||
return ResourceInput{
|
||||
return []ResourceInput{{
|
||||
Type: constants.AuditResourceAgentDistributionRegistration, ID: &id,
|
||||
Key: id, DisplayName: "扫码注册记录 " + id,
|
||||
Relation: constants.AuditResourceRelationReference, Role: constants.AuditResourceRoleApprovalBusiness,
|
||||
@@ -142,13 +179,13 @@ func approvalBusinessResource(ctx context.Context, tx *gorm.DB, businessType str
|
||||
"id": registration.ID, "parent_shop_id": registration.ParentShopID,
|
||||
"status": registration.Status, "approval_instance_id": instanceID,
|
||||
},
|
||||
}, nil
|
||||
}}, nil
|
||||
case constants.ApprovalBusinessTypeWithdrawalQualification:
|
||||
var qualification model.WithdrawalQualification
|
||||
if err := tx.WithContext(ctx).First(&qualification, businessID).Error; err != nil {
|
||||
return ResourceInput{}, errors.Wrap(errors.CodeDatabaseError, err, "查询审批关联提现资料资格版本失败")
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询审批关联提现资料资格版本失败")
|
||||
}
|
||||
return ResourceInput{
|
||||
return []ResourceInput{{
|
||||
Type: constants.AuditResourceWithdrawalQualification, ID: &id,
|
||||
Key: id, DisplayName: "提现资料资格版本 " + id,
|
||||
Relation: constants.AuditResourceRelationReference, Role: constants.AuditResourceRoleApprovalBusiness,
|
||||
@@ -157,13 +194,13 @@ func approvalBusinessResource(ctx context.Context, tx *gorm.DB, businessType str
|
||||
"subject_type": qualification.SubjectType, "status": qualification.Status,
|
||||
"approval_instance_id": instanceID,
|
||||
},
|
||||
}, nil
|
||||
}}, nil
|
||||
case constants.ApprovalBusinessTypeCommissionWithdrawal:
|
||||
var attempt model.CommissionWithdrawalRequestAttempt
|
||||
if err := tx.WithContext(ctx).First(&attempt, businessID).Error; err != nil {
|
||||
return ResourceInput{}, errors.Wrap(errors.CodeDatabaseError, err, "查询审批关联提现审批尝试记录失败")
|
||||
return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询审批关联提现审批尝试记录失败")
|
||||
}
|
||||
return ResourceInput{
|
||||
return []ResourceInput{{
|
||||
Type: constants.AuditResourceCommissionWithdrawalAttempt, ID: &id,
|
||||
Key: id, DisplayName: "提现审批尝试 " + id,
|
||||
Relation: constants.AuditResourceRelationReference, Role: constants.AuditResourceRoleApprovalBusiness,
|
||||
@@ -171,12 +208,26 @@ func approvalBusinessResource(ctx context.Context, tx *gorm.DB, businessType str
|
||||
"id": attempt.ID, "request_id": attempt.RequestID, "attempt_no": attempt.AttemptNo,
|
||||
"amount": attempt.Amount, "approval_instance_id": instanceID,
|
||||
},
|
||||
}, nil
|
||||
}}, nil
|
||||
default:
|
||||
return ResourceInput{}, errors.New(errors.CodeInvalidParam, "审批业务类型尚未注册审计资源")
|
||||
return nil, errors.New(errors.CodeInvalidParam, "审批业务类型尚未注册审计资源")
|
||||
}
|
||||
}
|
||||
|
||||
// resolvePendingRefundAttempt 解析尚未回写审批实例的退款审批尝试记录。
|
||||
//
|
||||
// 只在共享解析器返回冲突时调用:审批申请审计与「尝试记录回写审批实例」同事务,
|
||||
// 但审计先执行,因此 business_id 指向的尝试记录此刻 approval_instance_id 仍为空。
|
||||
// 该形态由 refundapproval.ResolveRefundForApprovalRequestInTx 单独承认,其余情况
|
||||
// 原样返回解析器的冲突错误,不放宽为任意未回写记录。
|
||||
func resolvePendingRefundAttempt(ctx context.Context, tx *gorm.DB, businessID uint, cause error) (*model.RefundRequest, *model.RefundRequestAttempt, error) {
|
||||
refund, attempt, err := refundapproval.ResolveRefundForApprovalRequestInTx(ctx, tx, businessID)
|
||||
if err != nil {
|
||||
return nil, nil, cause
|
||||
}
|
||||
return refund, attempt, nil
|
||||
}
|
||||
|
||||
func approvalSubmitterResource(change approvalapp.AuditChange) ResourceInput {
|
||||
accountID := strconv.FormatUint(uint64(change.SubmitterAccountID), 10)
|
||||
identity := map[string]any{"id": change.SubmitterAccountID}
|
||||
|
||||
105
internal/infrastructure/audit/refund_channel.go
Normal file
105
internal/infrastructure/audit/refund_channel.go
Normal file
@@ -0,0 +1,105 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/auditcontext"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
)
|
||||
|
||||
// WriteRefundChannelResult 在调用方事务内写入渠道原路退款的调用、恢复与异常事实。
|
||||
//
|
||||
// 主资源固定为退款单,渠道原路退款事实作为引用资源;快照只记录业务标识、金额、状态与
|
||||
// 结构化失败分类,不记录商户密钥、渠道报文或客户收款信息原文。摘要由调用方提供,
|
||||
// 必须为不含凭证与渠道报文的简短中文说明。
|
||||
//
|
||||
// 渠道调用与恢复都由后台任务触发,因此操作者固定为系统任务;审计上下文提供了更具体的
|
||||
// 操作者标识时沿用,避免任务未装配审计上下文时审计被拒绝并连带回滚业务事务。
|
||||
func (w *Writer) WriteRefundChannelResult(ctx context.Context, tx *gorm.DB, refund *model.RefundRequest, action, message string) error {
|
||||
if refund == nil || refund.ID == 0 || refund.RefundNo == "" {
|
||||
return errors.New(errors.CodeInvalidParam, "退款渠道审计资源不完整")
|
||||
}
|
||||
summary := message
|
||||
if summary == "" {
|
||||
summary = "渠道原路退款结果更新"
|
||||
}
|
||||
refundID := strconv.FormatUint(uint64(refund.ID), 10)
|
||||
actorID, actorName := constants.AuditActorIDRefundChannel, "退款渠道原路退款任务"
|
||||
if linkage := auditcontext.From(ctx); linkage.ActorID != "" {
|
||||
actorID = linkage.ActorID
|
||||
if linkage.ActorName != "" {
|
||||
actorName = linkage.ActorName
|
||||
}
|
||||
}
|
||||
resources := refundChannelResources(refund, refundID, summary)
|
||||
// 用 AppendAndGet 而非 Append:渠道调用与恢复的审计属于「要求成功必达」的事实,
|
||||
// 必须与业务事实同事务原子提交,失败时向调用方显式返回错误。
|
||||
if _, err := w.AppendAndGet(ctx, tx, AppendInput{
|
||||
ActionCode: action, Summary: summary,
|
||||
Actor: ActorInput{Kind: constants.AuditActorSystemTask, ID: actorID, Name: actorName},
|
||||
Source: constants.AuditSourceWorker, ScopeType: constants.AuditScopePlatform,
|
||||
Result: constants.AuditResultSuccess, CorrelationID: refund.RefundNo, Resources: resources,
|
||||
}); err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "写入退款渠道审计失败")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// refundChannelResources 构造退款渠道审计资源:退款单为主资源,渠道原路退款事实为引用资源。
|
||||
func refundChannelResources(refund *model.RefundRequest, refundID, summary string) []ResourceInput {
|
||||
return []ResourceInput{
|
||||
{
|
||||
Type: constants.AuditResourceRefund, ID: &refundID, Key: refund.RefundNo, DisplayName: refund.RefundNo,
|
||||
Relation: constants.AuditResourceRelationPrimary, Role: constants.AuditResourceRoleRefundTarget,
|
||||
IdentitySnapshot: map[string]any{
|
||||
"id": refund.ID, "refund_no": refund.RefundNo, "method": refund.Method,
|
||||
"frozen_actual_received_amount": refund.FrozenActualReceivedAmount,
|
||||
"requested_refund_amount": refund.RequestedRefundAmount,
|
||||
"approved_refund_amount": refund.ApprovedRefundAmount,
|
||||
"status": refund.Status,
|
||||
"channel_refund_status": refund.ChannelRefundStatus,
|
||||
"channel_refund_no": refund.ChannelRefundNo,
|
||||
"channel_refund_request_no": refund.ChannelRefundRequestNo,
|
||||
"channel_refund_amount": refund.ChannelRefundAmount,
|
||||
"failure_reason": refund.FailureReason,
|
||||
"anomaly_flag": refund.AnomalyFlag,
|
||||
},
|
||||
AfterData: channelRefundState(refund),
|
||||
SubjectVisibility: constants.AuditSubjectResult, SubjectSummary: summary,
|
||||
},
|
||||
{
|
||||
Type: constants.AuditResourceRefundChannelRefund, ID: &refundID, Key: refund.RefundNo,
|
||||
DisplayName: "渠道原路退款 " + refund.RefundNo,
|
||||
Relation: constants.AuditResourceRelationReference, Role: constants.AuditResourceRoleRefundChannelRefund,
|
||||
IdentitySnapshot: map[string]any{
|
||||
"id": refund.ID, "refund_no": refund.RefundNo,
|
||||
"channel_refund_status": refund.ChannelRefundStatus,
|
||||
"channel_refund_no": refund.ChannelRefundNo,
|
||||
"channel_refund_request_no": refund.ChannelRefundRequestNo,
|
||||
"channel_refund_amount": refund.ChannelRefundAmount,
|
||||
"failure_reason": refund.FailureReason,
|
||||
"anomaly_flag": refund.AnomalyFlag,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// channelRefundState 构造渠道原路退款状态快照,只包含状态与结构化失败分类。
|
||||
func channelRefundState(refund *model.RefundRequest) map[string]any {
|
||||
state := map[string]any{
|
||||
"status": refund.Status,
|
||||
"channel_refund_status": refund.ChannelRefundStatus,
|
||||
"channel_refund_amount": refund.ChannelRefundAmount,
|
||||
"failure_reason": refund.FailureReason,
|
||||
"anomaly_flag": refund.AnomalyFlag,
|
||||
}
|
||||
if refund.ChannelRefundedAt != nil {
|
||||
state["channel_refunded_at"] = *refund.ChannelRefundedAt
|
||||
}
|
||||
return state
|
||||
}
|
||||
@@ -310,6 +310,14 @@ func NewRegistry() *Registry {
|
||||
refundResubmitted := refundAction(constants.AuditActionRefundResubmitted, "重新提交退款申请", false)
|
||||
refundCommissionInvalidated := refundSystemAction(constants.AuditActionRefundCommissionInvalidated, "退款失效佣金")
|
||||
refundAssetProcessed := refundSystemAction(constants.AuditActionRefundAssetProcessed, "完成退款资产后处理")
|
||||
// 退款审批尝试由后台账号提交与重提;终态与异常标记由企业微信审批消费任务写入(复用 refundAction 的 Worker 入口)。
|
||||
refundAttemptSubmitted := refundAction(constants.AuditActionRefundAttemptSubmitted, "提交退款审批尝试", false)
|
||||
refundAttemptApproved := refundAction(constants.AuditActionRefundAttemptApproved, "通过退款审批尝试", true)
|
||||
refundAttemptClosed := refundAction(constants.AuditActionRefundAttemptClosed, "关闭退款审批尝试", true)
|
||||
refundAnomalyFlagged := refundAction(constants.AuditActionRefundAnomalyFlagged, "标记退款审批异常", true)
|
||||
// 渠道原路退款的调用与恢复都由 Worker 触发,与既有的退款系统动作入口一致。
|
||||
refundChannelCalled := refundSystemAction(constants.AuditActionRefundChannelCalled, "发起渠道原路退款")
|
||||
refundChannelRecovered := refundSystemAction(constants.AuditActionRefundChannelRecovered, "恢复渠道原路退款结果")
|
||||
approvalRequested := approvalAction(constants.AuditActionApprovalRequested, "提交通用审批申请", []ActionOrigin{
|
||||
{Actor: constants.AuditActorAccount, Source: constants.AuditSourceAdminAPI},
|
||||
})
|
||||
@@ -631,6 +639,12 @@ func NewRegistry() *Registry {
|
||||
constants.AuditActionRefundResubmitted: refundResubmitted,
|
||||
constants.AuditActionRefundCommissionInvalidated: refundCommissionInvalidated,
|
||||
constants.AuditActionRefundAssetProcessed: refundAssetProcessed,
|
||||
constants.AuditActionRefundAttemptSubmitted: refundAttemptSubmitted,
|
||||
constants.AuditActionRefundAttemptApproved: refundAttemptApproved,
|
||||
constants.AuditActionRefundAttemptClosed: refundAttemptClosed,
|
||||
constants.AuditActionRefundAnomalyFlagged: refundAnomalyFlagged,
|
||||
constants.AuditActionRefundChannelCalled: refundChannelCalled,
|
||||
constants.AuditActionRefundChannelRecovered: refundChannelRecovered,
|
||||
constants.AuditActionApprovalRequested: approvalRequested,
|
||||
constants.AuditActionApprovalSubmissionSynced: approvalSubmissionSynced,
|
||||
constants.AuditActionApprovalSubmissionRecovered: approvalSubmissionRecovered,
|
||||
@@ -791,7 +805,16 @@ func NewRegistry() *Registry {
|
||||
},
|
||||
constants.AuditResourceRefund: {
|
||||
Type: constants.AuditResourceRefund, Name: "退款单",
|
||||
IdentityFields: []string{"id", "refund_no", "order_id", "order_no", "order_type", "package_usage_id", "asset_identifier", "shop_id", "requested_refund_amount", "actual_received_amount", "refund_reason", "approved_refund_amount", "approval_instance_id", "status", "commission_deducted", "asset_reset"},
|
||||
IdentityFields: []string{"id", "refund_no", "order_id", "order_no", "order_type", "package_usage_id", "asset_identifier", "shop_id", "requested_refund_amount", "actual_received_amount", "refund_reason", "approved_refund_amount", "method", "frozen_actual_received_amount", "latest_attempt_id", "channel_refund_status", "channel_refund_no", "channel_refund_request_no", "channel_refund_amount", "failure_reason", "anomaly_flag", "approval_instance_id", "status", "commission_deducted", "asset_reset"},
|
||||
},
|
||||
// 退款审批尝试记录只登记冻结金额、方式与凭证数量,客户收款信息原文与凭证内容不进审计快照。
|
||||
constants.AuditResourceRefundAttempt: {
|
||||
Type: constants.AuditResourceRefundAttempt, Name: "退款审批尝试记录",
|
||||
IdentityFields: []string{"id", "refund_id", "attempt_no", "method", "refund_amount", "frozen_actual_received_amount", "approval_instance_id", "channel_refund_request_no", "submitted_by_account_id", "customer_account_info_present", "customer_voucher_count", "created_at"},
|
||||
},
|
||||
constants.AuditResourceRefundChannelRefund: {
|
||||
Type: constants.AuditResourceRefundChannelRefund, Name: "渠道原路退款事实",
|
||||
IdentityFields: []string{"id", "refund_no", "channel_refund_status", "channel_refund_no", "channel_refund_request_no", "channel_refund_amount", "failure_reason", "anomaly_flag"},
|
||||
},
|
||||
constants.AuditResourceEnterprise: {
|
||||
Type: constants.AuditResourceEnterprise, Name: "企业",
|
||||
|
||||
462
internal/infrastructure/payment/refund_adapter.go
Normal file
462
internal/infrastructure/payment/refund_adapter.go
Normal file
@@ -0,0 +1,462 @@
|
||||
package payment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/ArtisanCloud/PowerWeChat/v3/src/kernel"
|
||||
"go.uber.org/zap"
|
||||
|
||||
refundchannel "github.com/break/junhong_cmp_fiber/internal/application/refundchannel"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/alipay"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/fuiou"
|
||||
wechatpay "github.com/break/junhong_cmp_fiber/pkg/wechat"
|
||||
)
|
||||
|
||||
// fuiouShanghaiLocation 富友要求按上海时区回传原交易日期。
|
||||
var fuiouShanghaiLocation = time.FixedZone("CST", 8*3600)
|
||||
|
||||
// RefundAdapter 按冻结商户的服务商类型分派渠道原路退款与退款查询。
|
||||
//
|
||||
// 本适配器只做渠道原始调用与结果映射:不生成请求号、不写数据库、不写审计。
|
||||
// 渠道适配按官方契约实现,且不向任何渠道传递退款结果通知地址——退款终态只由
|
||||
// 同步响应与主动退款查询确认。
|
||||
type RefundAdapter struct {
|
||||
cache kernel.CacheInterface
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewRefundAdapter 创建渠道原路退款适配器。
|
||||
func NewRefundAdapter(cache kernel.CacheInterface, logger *zap.Logger) *RefundAdapter {
|
||||
return &RefundAdapter{cache: cache, logger: logger}
|
||||
}
|
||||
|
||||
var _ refundchannel.Refunder = (*RefundAdapter)(nil)
|
||||
|
||||
// Refund 按服务商类型提交一次渠道退款请求。
|
||||
// 凭证取自 Target.Config(冻结商户的当前凭证),只用于构造渠道客户端,绝不记录或持久化。
|
||||
// 渠道明确表态时返回结果且不报错;传输或解析失败返回 error,由调用方按结果未知处理。
|
||||
func (a *RefundAdapter) Refund(ctx context.Context, target refundchannel.Target) (refundchannel.Result, error) {
|
||||
switch target.ProviderType {
|
||||
case model.ProviderTypeWechat:
|
||||
return a.refundWechatV3(ctx, target)
|
||||
case model.ProviderTypeWechatV2:
|
||||
return a.refundWechatV2(ctx, target)
|
||||
case model.ProviderTypeFuiou:
|
||||
return a.refundFuiou(target)
|
||||
case "alipay":
|
||||
return a.refundAlipay(ctx, target)
|
||||
default:
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateFailed,
|
||||
FailureReason: constants.RefundFailureCredentialInvalid,
|
||||
FailureMessage: "该商户支付渠道的退款凭证不完整,无法执行原路退款",
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Query 按服务商类型查询渠道退款状态,绝不发起资金动作。
|
||||
func (a *RefundAdapter) Query(ctx context.Context, target refundchannel.Target) (refundchannel.Result, error) {
|
||||
switch target.ProviderType {
|
||||
case model.ProviderTypeWechat:
|
||||
service, err := a.wechatService(target.Config)
|
||||
if err != nil {
|
||||
return refundchannel.Result{}, err
|
||||
}
|
||||
result, err := service.QueryRefund(ctx, target.ChannelRefundRequestNo)
|
||||
if err != nil {
|
||||
return refundchannel.Result{}, err
|
||||
}
|
||||
return mapWechatRefundResult(result), nil
|
||||
case model.ProviderTypeWechatV2:
|
||||
service, err := wechatpay.NewPaymentV2ServiceFromConfig(target.Config, target.Config.OaAppID, a.logger)
|
||||
if err != nil {
|
||||
return refundchannel.Result{}, errors.Wrap(errors.CodeNoPaymentConfig, err, "微信 v2 退款查询配置不可用")
|
||||
}
|
||||
result, err := service.QueryRefund(ctx, target.ChannelRefundRequestNo)
|
||||
if err != nil {
|
||||
return refundchannel.Result{}, err
|
||||
}
|
||||
return mapWechatV2RefundResult(result, target.RefundAmount), nil
|
||||
case model.ProviderTypeFuiou:
|
||||
client, err := newFuiouClient(target.Config, a.logger)
|
||||
if err != nil {
|
||||
return refundchannel.Result{}, err
|
||||
}
|
||||
resp, err := client.RefundQuery(target.ChannelRefundRequestNo)
|
||||
if err != nil {
|
||||
return refundchannel.Result{}, err
|
||||
}
|
||||
return mapFuiouRefundQuery(resp), nil
|
||||
case "alipay":
|
||||
result, err := alipay.QueryRefund(ctx, target.Config, alipay.RefundRequest{
|
||||
OutTradeNo: target.PaymentNo,
|
||||
TradeNo: target.ChannelTradeNo,
|
||||
OutRequestNo: target.ChannelRefundRequestNo,
|
||||
RefundAmount: target.RefundAmount,
|
||||
})
|
||||
if err != nil {
|
||||
return refundchannel.Result{}, err
|
||||
}
|
||||
return mapAlipayRefundResult(result, target.RefundAmount), nil
|
||||
default:
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateFailed,
|
||||
FailureReason: constants.RefundFailureCredentialInvalid,
|
||||
FailureMessage: "该商户支付渠道的退款凭证不完整,无法查询退款结果",
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// refundWechatV3 执行微信支付 v3 原路退款。
|
||||
func (a *RefundAdapter) refundWechatV3(ctx context.Context, target refundchannel.Target) (refundchannel.Result, error) {
|
||||
service, err := a.wechatService(target.Config)
|
||||
if err != nil {
|
||||
return refundchannel.Result{}, err
|
||||
}
|
||||
result, err := service.RefundOrder(ctx, wechatpay.RefundOrderRequest{
|
||||
OutTradeNo: target.PaymentNo,
|
||||
OutRefundNo: target.ChannelRefundRequestNo,
|
||||
Amount: target.FrozenActualReceivedAmount,
|
||||
Refund: target.RefundAmount,
|
||||
})
|
||||
if err != nil {
|
||||
return refundchannel.Result{}, err
|
||||
}
|
||||
return mapWechatRefundResult(result), nil
|
||||
}
|
||||
|
||||
// wechatService 用商户当前凭证构造微信 v3 支付服务。
|
||||
func (a *RefundAdapter) wechatService(config *model.WechatConfig) (*wechatpay.PaymentService, error) {
|
||||
if config == nil {
|
||||
return nil, errors.New(errors.CodeNoPaymentConfig, "商户支付凭证不可用")
|
||||
}
|
||||
app, err := wechatpay.NewPaymentAppFromConfig(config, config.OaAppID, a.cache, a.logger)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeNoPaymentConfig, err, "微信支付退款配置不可用")
|
||||
}
|
||||
return wechatpay.NewPaymentService(app, a.logger), nil
|
||||
}
|
||||
|
||||
// refundFuiou 执行富友原路退款。
|
||||
// 回传原交易日期才能覆盖 30 天以上的原交易;不回传仅支持 30 天内,因此始终回传。
|
||||
func (a *RefundAdapter) refundFuiou(target refundchannel.Target) (refundchannel.Result, error) {
|
||||
client, err := newFuiouClient(target.Config, a.logger)
|
||||
if err != nil {
|
||||
return refundchannel.Result{}, err
|
||||
}
|
||||
origiDt := ""
|
||||
if target.PaidAt != nil {
|
||||
origiDt = target.PaidAt.In(fuiouShanghaiLocation).Format("20060102")
|
||||
}
|
||||
resp, err := client.CommonRefund(&fuiou.CommonRefundRequest{
|
||||
OrderType: target.ChannelOrderType,
|
||||
MchntOrderNo: target.PaymentNo,
|
||||
RefundOrderNo: target.ChannelRefundRequestNo,
|
||||
TotalAmt: strconv.FormatInt(target.FrozenActualReceivedAmount, 10),
|
||||
RefundAmt: strconv.FormatInt(target.RefundAmount, 10),
|
||||
ReservedOrigiDt: origiDt,
|
||||
})
|
||||
if err != nil {
|
||||
return refundchannel.Result{}, err
|
||||
}
|
||||
return mapFuiouRefundResponse(resp), nil
|
||||
}
|
||||
|
||||
// refundAlipay 执行支付宝原路退款。
|
||||
func (a *RefundAdapter) refundAlipay(ctx context.Context, target refundchannel.Target) (refundchannel.Result, error) {
|
||||
result, err := alipay.Refund(ctx, target.Config, alipay.RefundRequest{
|
||||
OutTradeNo: target.PaymentNo,
|
||||
TradeNo: target.ChannelTradeNo,
|
||||
OutRequestNo: target.ChannelRefundRequestNo,
|
||||
RefundAmount: target.RefundAmount,
|
||||
})
|
||||
if err != nil {
|
||||
return refundchannel.Result{}, err
|
||||
}
|
||||
return mapAlipayRefundResult(result, target.RefundAmount), nil
|
||||
}
|
||||
|
||||
// refundWechatV2 执行微信支付 v2 原路退款(双向证书接口)。
|
||||
//
|
||||
// 渠道契约规定申请接口的返回仅代表受理情况,退款是否成功必须由退款查询确认,
|
||||
// 因此受理成功在此按「结果未知」返回,由恢复任务查询收敛;渠道明确拒绝时按失败分类返回。
|
||||
func (a *RefundAdapter) refundWechatV2(ctx context.Context, target refundchannel.Target) (refundchannel.Result, error) {
|
||||
service, err := wechatpay.NewPaymentV2ServiceFromConfig(target.Config, target.Config.OaAppID, a.logger)
|
||||
if err != nil {
|
||||
return refundchannel.Result{}, errors.Wrap(errors.CodeNoPaymentConfig, err, "微信 v2 退款配置不可用")
|
||||
}
|
||||
result, err := service.RefundOrderV2(ctx, wechatpay.V2RefundRequest{
|
||||
OutTradeNo: target.PaymentNo,
|
||||
OutRefundNo: target.ChannelRefundRequestNo,
|
||||
TotalFee: target.FrozenActualReceivedAmount,
|
||||
RefundFee: target.RefundAmount,
|
||||
})
|
||||
if err != nil {
|
||||
return refundchannel.Result{}, err
|
||||
}
|
||||
return mapWechatV2RefundResult(result, target.RefundAmount), nil
|
||||
}
|
||||
|
||||
// mapWechatV2RefundResult 映射微信 v2 退款申请或退款查询结果。
|
||||
// Accepted 为真表示渠道已受理但结果待查询确认,按结果未知处理;受理接口不返回退款状态。
|
||||
func mapWechatV2RefundResult(result *wechatpay.V2RefundResult, requestedAmount int64) refundchannel.Result {
|
||||
if result == nil {
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateUnknown,
|
||||
FailureReason: constants.RefundFailureTimeoutUnknown,
|
||||
FailureMessage: "渠道返回空响应,退款结果未知",
|
||||
}
|
||||
}
|
||||
if result.Success {
|
||||
amount := result.RefundFee
|
||||
if amount <= 0 {
|
||||
amount = requestedAmount
|
||||
}
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateSuccess,
|
||||
ChannelRefundNo: result.RefundID,
|
||||
ChannelRefundAmount: amount,
|
||||
}
|
||||
}
|
||||
if result.Accepted {
|
||||
// 渠道已受理:终态必须由退款查询确认,不得在此标记成功。
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateUnknown,
|
||||
FailureReason: constants.RefundFailureTimeoutUnknown,
|
||||
FailureMessage: "微信 v2 已受理退款申请,等待退款查询确认结果",
|
||||
}
|
||||
}
|
||||
if result.ErrCode != "" {
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateFailed,
|
||||
FailureReason: classifyWechatRejection(result.ErrCode),
|
||||
FailureMessage: safeChannelMessage(result.ErrCode + " " + result.Message),
|
||||
}
|
||||
}
|
||||
switch strings.ToUpper(strings.TrimSpace(result.Status)) {
|
||||
case "REFUNDCLOSE", "CHANGE":
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateFailed,
|
||||
FailureReason: constants.RefundFailureChannelRejected,
|
||||
FailureMessage: safeChannelMessage(result.Message),
|
||||
}
|
||||
default:
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateUnknown,
|
||||
FailureReason: constants.RefundFailureTimeoutUnknown,
|
||||
FailureMessage: safeChannelMessage(result.Message),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// mapWechatRefundResult 映射微信 v3 退款结果。
|
||||
// 渠道业务错误码表示退款单未被受理,按错误码分类;处理中或状态为空表示渠道尚未给出终态,
|
||||
// 保持结果未知交由恢复任务查询。
|
||||
func mapWechatRefundResult(result *wechatpay.RefundOrderResult) refundchannel.Result {
|
||||
if result == nil {
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateUnknown,
|
||||
FailureReason: constants.RefundFailureTimeoutUnknown,
|
||||
FailureMessage: "渠道返回空响应,退款结果未知",
|
||||
}
|
||||
}
|
||||
if result.Success {
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateSuccess,
|
||||
ChannelRefundNo: result.RefundID,
|
||||
ChannelRefundAmount: result.RefundFee,
|
||||
}
|
||||
}
|
||||
if result.ChannelCode != "" {
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateFailed,
|
||||
FailureReason: classifyWechatRejection(result.ChannelCode),
|
||||
FailureMessage: safeChannelMessage(result.Message),
|
||||
}
|
||||
}
|
||||
switch strings.ToUpper(strings.TrimSpace(result.Status)) {
|
||||
case "CLOSED", "ABNORMAL":
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateFailed,
|
||||
FailureReason: constants.RefundFailureChannelRejected,
|
||||
FailureMessage: safeChannelMessage(result.Message),
|
||||
}
|
||||
default:
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateUnknown,
|
||||
FailureReason: constants.RefundFailureTimeoutUnknown,
|
||||
FailureMessage: safeChannelMessage(result.Message),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// classifyWechatRejection 把微信拒绝类错误码映射为稳定失败分类。
|
||||
// 系统异常与限频不代表渠道已明确拒绝,保持结果未知交恢复任务查询。
|
||||
func classifyWechatRejection(code string) string {
|
||||
switch strings.ToUpper(strings.TrimSpace(code)) {
|
||||
case "SYSTEM_ERROR", "FREQUENCY_LIMITED", "RATELIMIT_EXCEED":
|
||||
return constants.RefundFailureTimeoutUnknown
|
||||
case "NOT_ENOUGH", "BALANCE_NOT_ENOUGH":
|
||||
return constants.RefundFailureInsufficientBalance
|
||||
case "NO_AUTH", "SIGN_ERROR":
|
||||
return constants.RefundFailureCredentialInvalid
|
||||
default:
|
||||
return constants.RefundFailureChannelRejected
|
||||
}
|
||||
}
|
||||
|
||||
// mapFuiouRefundResponse 映射富友退款申请响应。
|
||||
func mapFuiouRefundResponse(resp *fuiou.CommonRefundResponse) refundchannel.Result {
|
||||
if resp == nil {
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateUnknown,
|
||||
FailureReason: constants.RefundFailureTimeoutUnknown,
|
||||
FailureMessage: "渠道返回空响应,退款结果未知",
|
||||
}
|
||||
}
|
||||
if resp.ResultCode != fuiou.ResultCodeSuccess {
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateFailed,
|
||||
FailureReason: classifyFuiouRejection(resp.ResultMsg),
|
||||
FailureMessage: safeChannelMessage(resp.ResultMsg),
|
||||
}
|
||||
}
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateSuccess,
|
||||
ChannelRefundNo: resp.RefundId,
|
||||
ChannelRefundAmount: parseFuiouAmount(resp.ReservedRefundAmt),
|
||||
SettledAt: resp.ReservedFySettleDt,
|
||||
}
|
||||
}
|
||||
|
||||
// mapFuiouRefundQuery 映射富友退款查询响应。
|
||||
// trans_stat 只取 SUCCESS 或 PAYERROR:PAYERROR 视为渠道明确失败,其余保持未知。
|
||||
func mapFuiouRefundQuery(resp *fuiou.RefundQueryResponse) refundchannel.Result {
|
||||
if resp == nil {
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateUnknown,
|
||||
FailureReason: constants.RefundFailureTimeoutUnknown,
|
||||
FailureMessage: "渠道返回空响应,退款结果未知",
|
||||
}
|
||||
}
|
||||
if resp.ResultCode != fuiou.ResultCodeSuccess {
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateFailed,
|
||||
FailureReason: classifyFuiouRejection(resp.ResultMsg),
|
||||
FailureMessage: safeChannelMessage(resp.ResultMsg),
|
||||
}
|
||||
}
|
||||
switch strings.ToUpper(strings.TrimSpace(resp.TransStat)) {
|
||||
case fuiou.TransStatSuccess:
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateSuccess,
|
||||
ChannelRefundNo: resp.RefundId,
|
||||
ChannelRefundAmount: parseFuiouAmount(resp.ReservedRefundAmt),
|
||||
SettledAt: resp.ReservedFySettleDt,
|
||||
}
|
||||
case fuiou.TransStatPayError:
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateFailed,
|
||||
FailureReason: constants.RefundFailureChannelRejected,
|
||||
FailureMessage: "富友退款交易状态为失败",
|
||||
}
|
||||
default:
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateUnknown,
|
||||
FailureReason: constants.RefundFailureTimeoutUnknown,
|
||||
FailureMessage: "富友退款交易仍在办理中",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// classifyFuiouRejection 按富友错误文案粗分类;无法识别时归为渠道明确拒绝。
|
||||
func classifyFuiouRejection(message string) string {
|
||||
text := strings.TrimSpace(message)
|
||||
switch {
|
||||
case strings.Contains(text, "余额") || strings.Contains(text, "不足"):
|
||||
return constants.RefundFailureInsufficientBalance
|
||||
case strings.Contains(text, "签名") || strings.Contains(text, "验签") || strings.Contains(text, "密钥"):
|
||||
return constants.RefundFailureCredentialInvalid
|
||||
default:
|
||||
return constants.RefundFailureChannelRejected
|
||||
}
|
||||
}
|
||||
|
||||
// mapAlipayRefundResult 映射支付宝退款或退款查询结果。
|
||||
func mapAlipayRefundResult(result *alipay.RefundResult, requestedAmount int64) refundchannel.Result {
|
||||
if result == nil {
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateUnknown,
|
||||
FailureReason: constants.RefundFailureTimeoutUnknown,
|
||||
FailureMessage: "渠道返回空响应,退款结果未知",
|
||||
}
|
||||
}
|
||||
if result.Success {
|
||||
amount := result.RefundFee
|
||||
if amount == 0 {
|
||||
amount = requestedAmount
|
||||
}
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateSuccess,
|
||||
ChannelRefundNo: result.TradeNo,
|
||||
ChannelRefundAmount: amount,
|
||||
}
|
||||
}
|
||||
return refundchannel.Result{
|
||||
State: refundchannel.StateFailed,
|
||||
FailureReason: classifyAlipayRejection(result.Message),
|
||||
FailureMessage: safeChannelMessage(result.Message),
|
||||
}
|
||||
}
|
||||
|
||||
// classifyAlipayRejection 按支付宝错误码粗分类;无法识别时归为渠道明确拒绝。
|
||||
func classifyAlipayRejection(message string) string {
|
||||
text := strings.ToUpper(strings.TrimSpace(message))
|
||||
switch {
|
||||
case strings.Contains(text, "BALANCE_NOT_ENOUGH") || strings.Contains(text, "余额不足"):
|
||||
return constants.RefundFailureInsufficientBalance
|
||||
case strings.Contains(text, "SIGN") || strings.Contains(text, "AUTH"):
|
||||
return constants.RefundFailureCredentialInvalid
|
||||
case strings.Contains(text, "SYSTEM_ERROR"):
|
||||
return constants.RefundFailureTimeoutUnknown
|
||||
default:
|
||||
return constants.RefundFailureChannelRejected
|
||||
}
|
||||
}
|
||||
|
||||
// safeChannelMessage 截断渠道文案并去掉换行,避免把渠道报文原文写入失败摘要。
|
||||
func safeChannelMessage(message string) string {
|
||||
text := strings.TrimSpace(strings.ReplaceAll(strings.ReplaceAll(message, "\n", " "), "\r", " "))
|
||||
if len(text) > 200 {
|
||||
return text[:200]
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
// parseFuiouAmount 把富友返回的金额字符串精确转换为分;空值或不可解析时按 0 处理。
|
||||
func parseFuiouAmount(amount string) int64 {
|
||||
text := strings.TrimSpace(amount)
|
||||
if text == "" {
|
||||
return 0
|
||||
}
|
||||
value, err := strconv.ParseInt(text, 10, 64)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// newFuiouClient 用商户当前凭证构造富友客户端。
|
||||
func newFuiouClient(config *model.WechatConfig, logger *zap.Logger) (*fuiou.Client, error) {
|
||||
if config == nil {
|
||||
return nil, errors.New(errors.CodeNoPaymentConfig, "商户支付凭证不可用")
|
||||
}
|
||||
return fuiou.NewClient(config.FyInsCd, config.FyMchntCd, config.FyTermID, config.FyAPIURL,
|
||||
config.FyNotifyURL, config.FyPrivateKey, config.FyPublicKey, logger)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package payment
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
|
||||
refundchannel "github.com/break/junhong_cmp_fiber/internal/application/refundchannel"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/auditcontext"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
)
|
||||
|
||||
// RefundChannelRecoveryTaskHandler 执行渠道原路退款结果恢复任务。
|
||||
type RefundChannelRecoveryTaskHandler struct {
|
||||
service *refundchannel.Service
|
||||
}
|
||||
|
||||
// NewRefundChannelRecoveryTaskHandler 创建渠道原路退款结果恢复任务 Handler。
|
||||
func NewRefundChannelRecoveryTaskHandler(service *refundchannel.Service) *RefundChannelRecoveryTaskHandler {
|
||||
return &RefundChannelRecoveryTaskHandler{service: service}
|
||||
}
|
||||
|
||||
// Handle 扫描原路处理中的退款并只查询渠道回填结果,绝不重复发起资金动作。
|
||||
func (h *RefundChannelRecoveryTaskHandler) Handle(ctx context.Context, task *asynq.Task) error {
|
||||
if h == nil || h.service == nil {
|
||||
return errors.New(errors.CodeServiceUnavailable, "渠道原路退款恢复任务未配置")
|
||||
}
|
||||
taskType := constants.TaskTypeRefundChannelRecovery
|
||||
if task != nil && task.Type() != "" {
|
||||
taskType = task.Type()
|
||||
}
|
||||
ctx = auditcontext.With(ctx, auditcontext.Context{
|
||||
ActorKind: constants.AuditActorScheduledJob, ActorID: taskType,
|
||||
ActorName: "渠道原路退款结果恢复计划任务", Source: constants.AuditSourceScheduler,
|
||||
})
|
||||
_, err := h.service.ProcessBatch(ctx)
|
||||
return err
|
||||
}
|
||||
Reference in New Issue
Block a user