SuperAPI AI Directory

alipay-delegation-pay

Agents & models

View repository

Updated 10-15 16:47

About this skill

Delegated Payment Integration Guide

Product Introduction

Delegated Payment is an agent (Agent) proxy payment solution provided by Alipay for merchants. The user pre-authorizes (including amount, number of times, and validity period limits), and subsequently the agent automatically executes payments within the authorized scope. It is suitable for automated scenarios such as proxy purchasing, ticket grabbing, and monitored purchases.

Capability Description Applicable Scenarios API Documentation
Delegated Payment The user pre-authorizes, and subsequently the agent automatically executes Automated scenarios such as proxy purchasing, ticket grabbing, and monitored purchases references/delegation/

⚠️ Must-read before integration: Integration Checklist (for unfamiliar merchants starting from scratch)

Merchants integrating for the first time must complete preparations according to this checklist first; otherwise, they will get stuck at "no appId/key/product permission" and be unable to call any API. For detailed steps, see Integration Preparation。

# Preparation Item Key Point
1 Create an application to obtain APPID Log in to Open Platform to create an application
2 Generate an RSA2 key and configure signing Obtain 应用私钥 + 支付宝公钥(required for fund-related APIs)
3 Enable the "Agent Proxy Payment" product Invite-only testing product; you must contact BD to enable it; delegation scenarios also require enabling App Payment(for pre-order use)
4 Application Launch Web/mobile applications must be submitted for review
5 Integrate the server-side SDK Java/PHP/Node/Python/.NET; initialize AlipayClient
6 Verify signatures and connectivity in the sandbox Run it through in the sandbox before production

✅ For a complete runnable end-to-end example, see examples/sandbox-demo/(official SDK; you can run it by modifying it accordingly).

Quick Navigation

Choose the corresponding section according to your needs:

Delegated Payment

Requirement Section
Understand the overall process Delegated Payment Business Process
Initiate delegation signing Step 2: Initiate a delegated proxy purchase application
Client invokes Alipay Step 3: Invoke the Alipay client
Query delegation status Step 4: Query the delegation task status
Merchant pre-order (obtain prepay_id) Step 5: Merchant pre-order
Execute deduction Step 6: Execute delegated payment
Cancel delegation Step 7: Cancel the delegation task

General Configuration

Requirement Section
API Invocation Method API Invocation Method
API Chaining Relationship Interface Chaining Relationship
State Transition State Transition
Asynchronous Message Asynchronous Message
Idempotency Control Idempotency Control
SDK Configuration SDK Configuration
Error Handling Common Error Codes
Encountering "Invalid Signature"/Integration Troubleshooting Troubleshooting

To view detailed interface parameter descriptions, please refer to references/ interface documentation in the directory.


Integration Overview

Interface Invocation Methods

Entrusted payment involves three interface invocation methods. Integrators need to choose the correct invocation method based on the scenario:

Invocation Method Description Applicable Interfaces Caller
Server-side Interface Merchant server directly calls Alipay gateway Entrusted payment, agreement query, entrusted cancellation Merchant server
SDK Signature Interface Server generates signature string and returns it to the client to invoke Alipay Entrusted purchase application, initiate entrusted payment Merchant server generates → client uses
Client SDK Client directly calls Alipay SDK Invoke Alipay client Android/iOS client

Interface Chaining Relationship

Entrusted Payment Interface Chaining

┌─────────────────────────────────────────────────────────────────────────────┐
│                            委托支付接口调用链路                               │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  ┌──────────────────┐    ┌──────────────────┐    ┌──────────────────┐      │
│  │ 1. 委托代买申请   │───?│ 2. 唤起支付宝    │───?│ 3. 用户授权签约   │      │
│  │ (服务端SDK签名)   │    │ (客户端SDK)      │    │ (支付宝客户端)    │      │
│  │                  │    │                  │    │                  │      │
│  │ 输出: orderStr   │    │ 输入: orderStr   │    │ 输出: agreement_no│      │
│  │                  │    │                  │    │       delegation_id│     │
│  └──────────────────┘    └──────────────────┘    └────────┬─────────┘      │
│                                                           │                 │
│         ┌─────────────────────────────────────────────────┘                 │
│         ▼                                                                   │
│  ┌──────────────────┐    ┌──────────────────┐    ┌──────────────────┐      │
│  │ 4. 查询委托状态   │?──?│ 5. 商户预下单     │───?│ 6. 执行委托支付   │      │
│  │ (服务端接口)      │    │ (商户·服务端接口) │    │ (服务端接口)      │      │
│  │                  │    │                  │    │                  │      │
│  │ 输入: agreement_no│   │ 输入: out_trade_no│   │ 输入: prepay_id  │      │
│  │       delegation_id│  │   payment_type   │    │       agreement_no│      │
│  │ 输出: status     │    │ =agent_pay       │    │       delegation_id│     │
│  │                  │    │ 输出: prepay_id  │    │ 输出: trade_no   │      │
│  └──────────────────┘    └──────────────────┘    └────────┬─────────┘      │
│                                                           │                 │
│         ┌─────────────────────────────────────────────────┘                 │
│         ▼                                                                   │
│  ┌──────────────────┐                                                       │
│  │ 7. 异步通知      │   可选: ┌──────────────────┐                          │
│  │ (支付宝推送)     │         │ 8. 取消委托任务   │                          │
│  │ 输出: trade_status│        │ (服务端接口)      │                          │
│  │       trade_no   │        └──────────────────┘                          │
│  └──────────────────┘                                                       │
└─────────────────────────────────────────────────────────────────────────────┘

Key Identifier Description

Multiple key identifiers are involved in the integration process. It is very important to understand their relationships:

Identifier Generator Function Lifecycle
external_agreement_no Merchant Merchant-side unique identifier for signing, used for idempotency control Merchant-defined
agreement_no Alipay Alipay agreement number, required for subsequent interface calls Returned after successful signing
external_delegation_id Merchant Merchant-side unique identifier for entrusted task (entrusted payment only) Merchant-defined
delegation_id Alipay Alipay entrusted task number (entrusted payment only) Returned after successful signing
prepay_id Alipay Pre-order ID, obtained through the pre-order interface Obtained before payment
out_trade_no Merchant Merchant order number, used for transaction idempotency control Merchant-defined
trade_no Alipay Alipay transaction number Returned after successful payment

Entrusted Payment Capability

Business Process

sequenceDiagram
    participant User as 用户
    participant Agent as 助理智能体
    participant Merchant as 商户服务端
    participant Alipay as 支付宝

    User->>Agent: 1. 输入原始意图
    Agent->>Agent: 2. 解析用户意图,提取关键信息
    Agent->>Merchant: 3. 发起委托代买申请
    Merchant->>Alipay: 4. 调用委托代买申请接口
    Alipay-->>Merchant: 5. 返回签名字符串orderStr
    Merchant-->>Agent: 6. 返回orderStr
    Agent->>User: 7. 唤起支付宝客户端
    User->>Alipay: 8. 确认授权签约
    Alipay-->>Agent: 9. 返回签约结果
    
    Note over Agent,Alipay: 后续智能体自动执行
    
    Agent->>Merchant: 10. 监控到符合条件,发起支付
    Merchant->>Alipay: 11. 调用委托支付接口
    Alipay-->>Merchant: 12. 返回支付结果
    Merchant-->>Agent: 13. 通知支付结果
    Agent->>User: 14. 推送购买成功通知

Integration Steps

Step 1: User Intent Parsing

When a user inputs the original intent into the assistant agent, the agent needs to parse and extract the following key information:

Extracted Field Description Example
delegation_desc Entrusted task description Monitor high-speed rail second-class seats from Beijing to Harbin on January 20
delegation_tag Entrusted tag/scenario Purchase train tickets
max_total_amount Maximum authorized amount 500.00
validity_start_time Effective start time 2026-01-15
validity_end_time Effective end time 2026-01-20

Step 2: Initiate the entrusted purchase application

Call the alipay.user.agreement.delegation.apply API to generate the signature string, which is used to invoke the Alipay client to complete user authorization.

// 初始化SDK
AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

// 构造请求
AlipayUserAgreementDelegationApplyRequest request = new AlipayUserAgreementDelegationApplyRequest();
AlipayUserAgreementDelegationApplyModel model = new AlipayUserAgreementDelegationApplyModel();

// 设置智能体id
model.setAgentId("your_agent_id");

// 设置商户签约号(需在商户系统中唯一)
model.setExternalAgreementNo("agreement_" + System.currentTimeMillis());

// 设置个人签约产品码(固定值)
model.setPersonalProductCode("UAM_AGENT_AUTH_P");

// 设置对话历史(用于展示给用户确认)
List<Conversation> conversationHistory = new ArrayList<>();
Conversation userMsg = new Conversation();
userMsg.setRole("USER");
userMsg.setContent("帮我抢一张1月20号回哈尔滨的票,二等座。");
userMsg.setCreateTime("2025-12-23 10:28:00");
conversationHistory.add(userMsg);

Conversation assistantMsg = new Conversation();
assistantMsg.setRole("ASSISTANT");
assistantMsg.setContent("好的,我将为您监控1月20日北京到哈尔滨的高铁二等座车票。");
assistantMsg.setCreateTime("2025-12-23 10:28:05");
conversationHistory.add(assistantMsg);

model.setConversationHistory(conversationHistory);

// 设置委托参数
DelegationParams delegationParams = new DelegationParams();
delegationParams.setExternalDelegationId("delegation_" + System.currentTimeMillis());
delegationParams.setDelegationDesc("监控1月20日北京去哈尔滨的高铁二等座");
delegationParams.setDelegationTag("购买火车票");
delegationParams.setMaxTotalAmount("500.00");
delegationParams.setTimesLimit("3");
delegationParams.setValidityStartTime("2026-01-15");
delegationParams.setValidityEndTime("2026-01-20");
model.setDelegationParams(delegationParams);

// 设置接入渠道(固定值)
AccessParams accessParams = new AccessParams();
accessParams.setChannel("ALIPAYAPP");
model.setAccessParams(accessParams);

request.setBizModel(model);

// 执行请求,获取签名字符串
AlipayUserAgreementDelegationApplyResponse response = alipayClient.sdkExecute(request);
String orderStr = response.getBody();

// 将orderStr返回给客户端,用于唤起支付宝
return orderStr;

Step 3: Invoke the Alipay client

After the client receives orderStr , it calls the Alipay SDK to invoke the Alipay client:

Android:

// 调用支付宝SDK
PayTask payTask = new PayTask(activity);
Map<String, String> result = payTask.payV2(orderStr, true);

// 解析结果
String resultStatus = result.get("resultStatus");
if ("9000".equals(resultStatus)) {
    // 签约成功,获取agreement_no和delegation_id
    String resultContent = result.get("result");
    // 解析resultContent获取签约信息
}

iOS:

[[AlipaySDK defaultService] payOrder:orderStr fromScheme:@"yourAppScheme" callback:^(NSDictionary *resultDic) {
    NSString *resultStatus = resultDic[@"resultStatus"];
    if ([resultStatus isEqualToString:@"9000"]) {
        // 签约成功
        NSString *result = resultDic[@"result"];
        // 解析result获取签约信息
    }
}];

Step 4: Query the entrusted task status

After the user signs successfully, you can query the entrusted task details through the alipay.user.agreement.delegation.query API:

// 初始化SDK
AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

// 构造请求
AlipayUserAgreementDelegationQueryRequest request = new AlipayUserAgreementDelegationQueryRequest();
AlipayUserAgreementDelegationQueryModel model = new AlipayUserAgreementDelegationQueryModel();

// 设置协议标识(二选一)
model.setAgreementNo("20265005004910872660");
// 或使用外部签约号
// model.setExternalAgreementNo("agreement_xxx");

// 设置委托标识(二选一)
model.setDelegationId("2026001");
// 或使用外部委托号
// model.setExternalDelegationId("delegation_xxx");

request.setBizModel(model);

// 执行请求
AlipayUserAgreementDelegationQueryResponse response = alipayClient.execute(request);

if (response.isSuccess()) {
    String status = response.getStatus();           // 委托状态:NORMAL-正常
    String remainingAmount = response.getRemainingAmount();  // 剩余可用金额
    String remainingTimes = response.getRemainingTimes();    // 剩余次数
    String validityEndTime = response.getValidityEndTime();  // 有效期结束时间
    
    System.out.println("委托状态: " + status);
    System.out.println("剩余金额: " + remainingAmount + "元");
    System.out.println("剩余次数: " + remainingTimes);
}

Step 5: Merchant pre-order (obtain prepay_id)

Execute entrusted deductionBefore, themerchant servermust first call alipay.trade.order.prepay(Unified Acquiring Transaction Order Prepayment API) to obtain prepay_id. The entrusted payment API itself does not create an order; it only deducts payment for an order that has already been pre-ordered.

Prerequisite permission: The merchant must first enable the App Payment product (otherwise it returns ACCESS_FORBIDDEN 40006)。 Key configuration: In the agent scenario, it must payment_type=agent_pay、product_code=QUICK_MSECURITY_PAY, otherwise it does not return prepay_id。

// 初始化SDK(商户服务端)
AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

AlipayTradeOrderPrepayRequest request = new AlipayTradeOrderPrepayRequest();
AlipayTradeOrderPrepayModel model = new AlipayTradeOrderPrepayModel();

// 必填:订单信息
model.setOutTradeNo("20150320010101001");
model.setTotalAmount("88.88");
model.setSubject("早餐盲盒");

// 智能体代理支付场景的关键配置
model.setProductCode("QUICK_MSECURITY_PAY");
model.setPaymentType("agent_pay");

request.setBizModel(model);
AlipayTradeOrderPrepayResponse response = alipayClient.execute(request);

String prepayId = response.getPrepayId();   // 有效期 2 小时,交给智能体发起委托支付

For detailed fields, see Pre-order API.md。

Step 6: Execute entrusted payment

After the merchant pre-orders and obtains prepay_id , when the agent detects a qualifying product, it calls the alipay.trade.agent.delegation.pay API to complete the deduction:

Prerequisite: Already passedStep 5: Merchant pre-orderto obtain prepay_id(default validity period 2 hours).

// 初始化SDK
AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

// 构造请求
AlipayTradeAgentDelegationPayRequest request = new AlipayTradeAgentDelegationPayRequest();
AlipayTradeAgentDelegationPayModel model = new AlipayTradeAgentDelegationPayModel();

// 设置预下单ID(通过 alipay.trade.order.prepay 接口获取)
model.setPrepayId("your_prepay_id");

// 设置Agent签约协议号(用户签约成功后获得)
model.setAgreementNo("20170322450983769228");

// 设置代买委托id(用户签约成功后获得)
model.setDelegationId("2026001123456789");

request.setBizModel(model);

// 执行请求
AlipayTradeAgentDelegationPayResponse response = alipayClient.execute(request);

if (response.isSuccess()) {
    String tradeNo = response.getTradeNo();
    System.out.println("支付成功,支付宝交易号: " + tradeNo);
    // TODO: 通知用户购买成功
} else {
    String errorCode = response.getSubCode();
    String errorMsg = response.getSubMsg();
    System.out.println("支付失败: " + errorCode + " - " + errorMsg);
    // TODO: 根据错误码处理异常情况
}

Step 7: Cancel the entrusted task (optional)

If you need to cancel an in-progress entrusted task, call the alipay.user.agreement.delegation.cancel API:

// 初始化SDK
AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

// 构造请求
AlipayUserAgreementDelegationCancelRequest request = new AlipayUserAgreementDelegationCancelRequest();
AlipayUserAgreementDelegationCancelModel model = new AlipayUserAgreementDelegationCancelModel();

// 设置协议号
model.setAgreementNo("20265002005167619007");

// 设置代买委托号
model.setDelegationId("20260202002630110000070000000001");

request.setBizModel(model);

// 执行请求
AlipayUserAgreementDelegationCancelResponse response = alipayClient.execute(request);

if (response.isSuccess()) {
    System.out.println("委托任务取消成功");
} else {
    System.out.println("取消失败: " + response.getSubCode() + " - " + response.getSubMsg());
}

SDK configuration

AlipayClient initialization

private AlipayConfig getAlipayConfig() {
    AlipayConfig alipayConfig = new AlipayConfig();
    
    // 支付宝网关地址
    alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
    
    // 应用ID
    alipayConfig.setAppId("your_app_id");
    
    // 应用私钥
    alipayConfig.setPrivateKey("your_private_key");
    
    // 支付宝公钥
    alipayConfig.setAlipayPublicKey("alipay_public_key");
    
    // 字符集
    alipayConfig.setCharset("UTF-8");
    
    // 签名类型
    alipayConfig.setSignType("RSA2");
    
    return alipayConfig;
}

Maven dependency

<dependency>
    <groupId>com.alipay.sdk</groupId>
    <artifactId>alipay-sdk-java</artifactId>
    <version>4.40.852.ALL</version>
</dependency>

Common error codes

Entrusted purchase application API

Error code Description Handling suggestion
SYSTEM_ERROR System busy Retry the request
INVALID_PARAMETER Invalid parameter Check the request parameters

Entrusted payment API

Error code Description Handling suggestion
ACQ.AGREEMENT_NOT_EXIST Agreement does not exist or has been terminated Guide the user to sign again
ACQ.AGREEMENT_INVALID User agreement has expired Guide the user to sign again
ACQ.BUYER_BALANCE_NOT_ENOUGH Buyer has insufficient balance Prompt the user to top up
ACQ.ORDER_NOT_EXIST Order does not exist Check whether prepay_id is correct
ACQ.TRADE_HAS_SUCCESS Transaction has been paid successfully Avoid duplicate payment
ACQ.TRADE_HAS_CLOSE Transaction has been closed Create a new pre-order

Entrusted task query API

Error code Description Handling suggestion
DELEGATION_NOT_EXIST Entrusted task does not exist Check whether the entrusted number is correct
USER_AGREEMENT_NOT_EXIST User agreement does not exist Check the agreement number or guide the user to sign again

Signature-related errors

Error code Description Handling Suggestions
Invalid signature / INVALID_SIGNATURE Signature verification failed This generally does not occur when using the official SDK; if you manually assemble the signature string, check whether the signed content and the request parameters actually sent are exactly consistent (sign whatever you send), for details see Troubleshooting §1

Status Transitions

Entrusted Task Status Transitions

stateDiagram-v2
    [*] --> SIGNING: 发起委托申请
    SIGNING --> NORMAL: 用户授权成功
    SIGNING --> INVALID: 用户拒绝/超时
    NORMAL --> NORMAL: 执行支付(次数/金额未用完)
    NORMAL --> FINISHED: 次数/金额用完
    NORMAL --> CANCELLED: 商户取消
    NORMAL --> EXPIRED: 有效期到期
    NORMAL --> TERMINATE: 用户解约
    FINISHED --> [*]
    CANCELLED --> [*]
    EXPIRED --> [*]
    TERMINATE --> [*]
    INVALID --> [*]
Status Description Available Actions
SIGNING Signing in progress, waiting for user authorization Waiting for user action
NORMAL Normal, payment can be executed Execute payment, query, cancel
FINISHED Completed, number of times or amount used up Query only
CANCELLED Cancelled, merchant actively cancelled Query only
EXPIRED Expired, validity period exceeded Query only
TERMINATE Terminated, user terminated the agreement Query only
INVALID Invalid, user rejected or timed out None

Transaction Status Transitions

stateDiagram-v2
    [*] --> WAIT_BUYER_PAY: 创建预下单
    WAIT_BUYER_PAY --> TRADE_SUCCESS: 支付成功
    WAIT_BUYER_PAY --> TRADE_CLOSED: 超时关闭
    TRADE_SUCCESS --> TRADE_FINISHED: 交易完结(不可退款)
    TRADE_SUCCESS --> TRADE_CLOSED: 全额退款
Status Description Merchant Handling
WAIT_BUYER_PAY Waiting for payment Waiting for payment result
TRADE_SUCCESS Payment successful Ship goods/provide services
TRADE_FINISHED Transaction completed Transaction ended, non-refundable
TRADE_CLOSED Transaction closed Closed due to timeout or refund

Asynchronous Messages

Message Types

Message Type Trigger Timing Notification Address Configuration
Signing Success Notification User completes signing authorization Application gateway
Signing Termination Notification User or merchant terminates the agreement Application gateway
Payment Result Notification Payment completed (success/failure) Specify notify_url in the API
Entrusted Task Status Change Entrusted task status change Application gateway

Asynchronous Notification Integration Process

sequenceDiagram
    participant Alipay as 支付宝
    participant Merchant as 商户服务端
    participant DB as 商户数据库

    Alipay->>Merchant: 1. POST 异步通知
    Merchant->>Merchant: 2. 验证签名
    alt 验签成功
        Merchant->>DB: 3. 查询订单状态
        alt 订单未处理
            Merchant->>DB: 4. 更新订单状态
            Merchant->>Merchant: 5. 执行业务逻辑
            Merchant-->>Alipay: 6. 返回 "success"
        else 订单已处理(幂等)
            Merchant-->>Alipay: 6. 返回 "success"
        end
    else 验签失败
        Merchant-->>Alipay: 返回 "failure"
    end
    
    Note over Alipay,Merchant: 支付宝会重试直到收到 "success"

Key Points for Notification Handling

  1. Signature verification is mandatory: all asynchronous notifications must have their signatures verified to prevent forged requests
  2. Idempotent processing: the same notification may be sent repeatedly, and an idempotency check must be performed based on the order number
  3. Fast response: return immediately after processing is complete success, and handle business logic asynchronously
  4. Retry mechanism: Alipay will retry at certain intervals until it receives success or the retry count is exceeded

Entrusted Payment Asynchronous Notification Handling

@RequestMapping("/delegation/notify")
public String handleDelegationNotify(HttpServletRequest request) {
    Map<String, String> params = getAllRequestParams(request);
    
    // 1. 验签
    boolean signVerified = AlipaySignature.rsaCheckV1(
        params, alipayPublicKey, "UTF-8", "RSA2"
    );
    
    if (!signVerified) {
        return "failure";
    }
    
    // 2. 获取通知类型
    String notifyType = params.get("notify_type");
    
    // 3. 根据通知类型处理
    switch (notifyType) {
        case "dut_user_sign":  // 签约成功
            handleSignSuccess(params);
            break;
        case "dut_user_unsign":  // 解约通知
            handleUnsign(params);
            break;
        case "dut_delegation_status_change":  // 委托状态变更
            handleDelegationStatusChange(params);
            break;
        default:
            log.warn("未知通知类型: " + notifyType);
    }
    
    return "success";
}

private void handleSignSuccess(Map<String, String> params) {
    String agreementNo = params.get("agreement_no");
    String externalAgreementNo = params.get("external_agreement_no");
    String delegationId = params.get("delegation_id");
    
    // 更新签约状态
    delegationService.updateSignStatus(externalAgreementNo, agreementNo, delegationId, "SIGNED");
}

private void handleDelegationStatusChange(Map<String, String> params) {
    String delegationId = params.get("delegation_id");
    String status = params.get("status");
    
    // 更新委托任务状态
    delegationService.updateDelegationStatus(delegationId, status);
}

Idempotency Control

Idempotency Design Principles

Scenario Idempotency Key Handling Strategy
Signing Application external_agreement_no Return the existing agreement for the same signing number
Entrust Creation external_delegation_id Return the existing entrust for the same entrust number
Payment Request out_trade_no Same order number returns the existing transaction
Asynchronous notification trade_no + trade_status Processed notifications directly return success

Merchant-side idempotency implementation

/**
 * 委托支付幂等处理示例
 */
public PayResult executePayWithIdempotent(String outTradeNo, String agreementNo, 
                                           String delegationId, String amount) {
    // 1. 先查询本地订单状态
    Order order = orderRepository.findByOutTradeNo(outTradeNo);
    
    if (order != null) {
        // 订单已存在,检查状态
        if ("PAID".equals(order.getStatus())) {
            // 已支付成功,直接返回
            return PayResult.success(order.getTradeNo());
        } else if ("PAYING".equals(order.getStatus())) {
            // 支付中,查询支付宝交易状态
            return queryAndSyncTradeStatus(outTradeNo);
        }
    }
    
    // 2. 创建本地订单(状态:PAYING)
    order = createOrder(outTradeNo, amount, "PAYING");
    
    try {
        // 3. 调用支付宝支付接口
        AlipayTradeAgentDelegationPayResponse response = executePayment(
            outTradeNo, agreementNo, delegationId, amount
        );
        
        if (response.isSuccess()) {
            // 4. 更新订单状态
            order.setTradeNo(response.getTradeNo());
            order.setStatus("PAID");
            orderRepository.save(order);
            return PayResult.success(response.getTradeNo());
        } else {
            // 处理失败情况
            order.setStatus("FAILED");
            order.setErrorCode(response.getSubCode());
            orderRepository.save(order);
            return PayResult.fail(response.getSubCode(), response.getSubMsg());
        }
    } catch (Exception e) {
        // 异常情况,需要查询确认
        return queryAndSyncTradeStatus(outTradeNo);
    }
}

Delegated payment best practices

  1. Idempotency handling: Use a unique external_agreement_no and external_delegation_idto avoid duplicate creation
  2. Status validation: Query the delegation task status before payment to ensure the status is NORMAL
  3. Amount validation: Check before payment whether remaining_amount is sufficient
  4. Count validation: Check before payment whether remaining_times is greater than 0
  5. Validity period validation: Check before payment whether the current time is within the validity period
  6. Exception handling: Properly handle various error codes and provide friendly prompts to users
  7. Logging: Record complete request and response logs to facilitate troubleshooting

API documentation reference

When you need to view detailed API parameters and request/response field descriptions, please read the following reference documents:

Integration preparation (required reading for first-time integration)

Document Reference document path
Integration preparation (registration/keys/product activation/sandbox) references/00-接入准备.md

Delegated payment (Delegation)

API Reference document path
Delegated purchase request references/delegation/委托代买申请接口.md
Merchant pre-order references/delegation/预下单接口.md
Delegated payment references/delegation/委托支付接口.md
Delegation task query references/delegation/委托任务查询接口.md
Delegation task cancellation references/delegation/委托任务取消接口.md
Troubleshooting (invalid signature, integration debugging) references/故障排查.md