StablePay Docs
产品开发者联系我们
首页产品文档快速开始APISaaS平台
首页
产品文档
支付产品能力自动货币转换
快速开始
快速开始身份认证支付会话商户交易退款
API
API 参考版本控制身份认证请求与响应分页频率限制错误处理支付服务退款服务Webhook 通知
SaaS平台
ShopifyWooCommerceShoplazza 店匠
  • API 参考
  • 版本控制
  • 身份认证
  • 请求与响应
  • 分页
  • 频率限制
  • 错误处理

支付平台 API

  • 支付服务
  • 退款服务
  • Webhook 通知
StablePay 开发者文档
Home
Product
Quick Start
API
SaaS
Login
Register
GitHub
Home
Product
Quick Start
API
SaaS
Login
Register
GitHub
  • API 概览 / Overview

    • API 参考 / Reference
    • 版本控制 / Versioning
    • 身份认证 / Authentication
    • 请求与响应 / Requests & Responses
    • 分页 / Pagination
    • 频率限制 / Rate Limits
    • 错误处理 / Errors
  • 支付平台 API / Payment API

    • 支付服务 / Payment Service
    • 退款服务 / Refund Service
    • Webhook 通知 / Webhook

退款

Refund Service 提供退款的创建、查询、取消等核心功能。

Refund Service provides core functionality for creating, querying, and canceling refunds.

端点

方法端点描述
POST/api/v1/refunds/create创建退款
GET/api/v1/refunds/:refund_id获取退款信息
POST/api/v1/refunds/:refund_id/cancel取消退款
MethodEndpointDescription
POST/api/v1/refunds/createCreate refund
GET/api/v1/refunds/:refund_idGet refund information
POST/api/v1/refunds/:refund_id/cancelCancel refund

概述

StablePay 退款接口提供完整的退款管理能力,支持对已完成的支付进行退款操作。

基础信息

  • Base URL: https://api.stablepay.co (生产环境)
  • API路径前缀: /api/v1
  • 协议: HTTPS
  • 数据格式: JSON
  • 字符编码: UTF-8

退款限制

  • 只有已完成的支付才能申请退款
  • 退款金额不能超过原支付金额
  • 退款必须在支付完成后的指定时间内申请(具体时间限制请咨询客服)
  • 每个支付会话可以多次退款,但累计退款金额不能超过原支付金额

StablePay refund API provides complete refund management capabilities, supporting refund operations for completed payments.

Basic Information

  • Base URL: https://api.stablepay.co (Production environment)
  • API Path Prefix: /api/v1
  • Protocol: HTTPS
  • Data Format: JSON
  • Character Encoding: UTF-8

Refund Limitations

  • Only completed payments can be refunded
  • Refund amount cannot exceed the original payment amount
  • Refunds must be requested within a specified time after payment completion (please contact customer service for specific time limits)
  • Multiple refunds can be made for each payment session, but the total refund amount cannot exceed the original payment amount

认证方式

所有API请求都需要在HTTP请求头中包含以下认证信息:

必需请求头

请求头类型必填说明
Content-Typestring是固定为 application/json,GET请求不必携带
Authorizationstring是API密钥,格式:Bearer {api_key}
X-StablePay-Timestampstring是请求时间戳(Unix时间戳,秒级)
X-StablePay-Noncestring是随机数(用于防重放攻击)
X-StablePay-Signaturestring是请求签名(HMAC-SHA256)

注意:

  • 商户ID和API密钥由StablePay平台分配,请妥善保管,不要泄露
  • API密钥格式:Bearer sk_live_xxx(生产环境)或 Bearer sk_test_xxx(测试环境)

请求签名

为了确保请求的安全性,所有API请求都需要包含签名信息。签名使用HMAC-SHA256算法计算。

签名计算步骤

  1. 准备签名参数:

    • timestamp: 当前Unix时间戳(秒级)
    • nonce: 随机字符串(建议使用UUID)
    • requestBody: 请求体的JSON字符串(GET请求为空字符串)
  2. 构建签名字符串:

    signString = timestamp + "." + nonce + "." + requestBody
    
  3. 计算签名:

    signature = HMAC-SHA256(api_secret, signString)
    

    其中 api_secret 是API密钥对应的密钥(从API密钥中提取或单独提供)

  4. 设置请求头:

    X-StablePay-Timestamp: {timestamp}
    X-StablePay-Nonce: {nonce}
    X-StablePay-Signature: {signature}
    

All API requests must include the following authentication information in the HTTP request headers:

Required Request Headers

HeaderTypeRequiredDescription
Content-TypestringYesFixed as application/json
X-Merchant-IdstringYesMerchant ID assigned by StablePay platform
AuthorizationstringYesAPI key, format: Bearer {api_key}
X-StablePay-TimestampstringYesRequest timestamp (Unix timestamp, seconds)
X-StablePay-NoncestringYesRandom nonce (for replay attack prevention)
X-StablePay-SignaturestringYesRequest signature (HMAC-SHA256)

Note:

  • Merchant ID and API key are assigned by the StablePay platform. Please keep them safe and do not disclose them
  • API key format: Bearer sk_live_xxx (production) or Bearer sk_test_xxx (test environment)

Request Signature

To ensure request security, all API requests must include signature information. The signature is calculated using the HMAC-SHA256 algorithm.

Signature Calculation Steps

  1. Prepare signature parameters:

    • timestamp: Current Unix timestamp (seconds)
    • nonce: Random string (UUID recommended)
    • requestBody: JSON string of the request body (empty string for GET requests)
  2. Build signature string:

    signString = timestamp + "." + nonce + "." + requestBody
    
  3. Calculate signature:

    signature = HMAC-SHA256(api_secret, signString)
    

    Where api_secret is the secret key corresponding to the API key (extracted from the API key or provided separately)

  4. Set request headers:

    X-StablePay-Timestamp: {timestamp}
    X-StablePay-Nonce: {nonce}
    X-StablePay-Signature: {signature}
    

签名示例代码

JavaScript/Node.js:

const crypto = require('crypto');

function calculateSignature(apiSecret, timestamp, nonce, requestBody) {
  const signString = `${timestamp}.${nonce}.${requestBody}`;
  const signature = crypto
    .createHmac('sha256', apiSecret)
    .update(signString)
    .digest('hex');
  return signature;
}

// 使用示例 / Usage example
const timestamp = Math.floor(Date.now() / 1000).toString();
const nonce = require('uuid').v4();
const requestBody = JSON.stringify({
  order_id: 'sess_xxxxxxxxxxxx',
  refund_id: 'refund_20250101001',
  amount: '50.00',
  currency: 'USDT'
});

const signature = calculateSignature(apiSecret, timestamp, nonce, requestBody);

// 设置请求头 / Set request headers
headers['X-StablePay-Timestamp'] = timestamp;
headers['X-StablePay-Nonce'] = nonce;
headers['X-StablePay-Signature'] = signature;

Python:

import hmac
import hashlib
import time
import uuid
import json

def calculate_signature(api_secret, timestamp, nonce, request_body):
    """计算请求签名 / Calculate request signature"""
    sign_string = f"{timestamp}.{nonce}.{request_body}"
    signature = hmac.new(
        api_secret.encode('utf-8'),
        sign_string.encode('utf-8'),
        hashlib.sha256
    ).hexdigest()
    return signature

# 使用示例 / Usage example
timestamp = str(int(time.time()))
nonce = str(uuid.uuid4())
request_body = json.dumps({
    'order_id': 'sess_xxxxxxxxxxxx',
    'refund_id': 'refund_20250101001',
    'amount': '50.00',
    'currency': 'USDT'
})

signature = calculate_signature(api_secret, timestamp, nonce, request_body)

# 设置请求头 / Set request headers
headers['X-StablePay-Timestamp'] = timestamp
headers['X-StablePay-Nonce'] = nonce
headers['X-StablePay-Signature'] = signature

Go:

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/hex"
    "fmt"
    "time"
    "github.com/google/uuid"
)

func calculateSignature(apiSecret, timestamp, nonce, requestBody string) string {
    signString := fmt.Sprintf("%s.%s.%s", timestamp, nonce, requestBody)
    mac := hmac.New(sha256.New, []byte(apiSecret))
    mac.Write([]byte(signString))
    return hex.EncodeToString(mac.Sum(nil))
}

// 使用示例 / Usage example
timestamp := fmt.Sprintf("%d", time.Now().Unix())
nonce := uuid.New().String()
requestBody := `{"order_id":"sess_xxxxxxxxxxxx","refund_id":"refund_20250101001","amount":"50.00","currency":"USDT"}`

signature := calculateSignature(apiSecret, timestamp, nonce, requestBody)

// 设置请求头 / Set request headers
headers["X-StablePay-Timestamp"] = timestamp
headers["X-StablePay-Nonce"] = nonce
headers["X-StablePay-Signature"] = signature

签名验证说明

  • 服务端会验证时间戳是否在允许的范围内(通常为5分钟)
  • 服务端会验证nonce是否已被使用(防重放攻击)
  • 服务端会重新计算签名并与请求头中的签名进行比对
  • The server will verify that the timestamp is within the allowed range (typically 5 minutes)
  • The server will verify that the nonce has not been used (replay attack prevention)
  • The server will recalculate the signature and compare it with the signature in the request header

接口列表

1. 创建退款

为指定的支付会话创建退款请求。

重要说明:

  • order_id 参数必须是支付会话ID,格式为 sess_xxxxxxxxxxxx
  • 支付会话ID可以通过创建支付会话接口返回的 id 字段获取
  • 只有已完成(paid)的支付会话才能申请退款

Create a refund request for a specified payment session.

Important Notes:

  • The order_id parameter must be the payment session ID in the format sess_xxxxxxxxxxxx
  • The payment session ID can be obtained from the id field returned by the create payment session API
  • Only completed (paid) payment sessions can request refunds

接口地址

POST /api/v1/refunds/create

请求头

Content-Type: application/json
Authorization: Bearer sk_live_xxxxxxxxxx
X-StablePay-Timestamp: 1735123456
X-StablePay-Nonce: 550e8400-e29b-41d4-a716-446655440000
X-StablePay-Signature: 3c8f9d2a7b6e5d4c3b2a1f0e9d8c7b6a5f4e3d2c1b0a9f8e7d6c5b4a3f2e1d0

请求参数

参数类型必填说明
order_idstring是要退款的订单ID(格式:sess_xxxxxxxxxxxx,即支付会话ID)
refund_idstring是退款ID(商户侧唯一,用于幂等性控制)
amountstring是退款金额(面额字符串,如 "10.50")
currencystring是货币类型:USDT 或 USDC
reasonstring否退款原因
descriptionstring否退款描述
metadataobject否元数据(键值对)
ParameterTypeRequiredDescription
order_idstringYesOrder ID to refund (format: sess_xxxxxxxxxxxx, i.e., payment session ID)
refund_idstringYesRefund ID (unique on merchant side, for idempotency control)
amountstringYesRefund amount (decimal string, e.g., "10.50")
currencystringYesCurrency type: USDT or USDC
reasonstringNoRefund reason
descriptionstringNoRefund description
metadataobjectNoMetadata (key-value pairs)

退款原因枚举

值说明
requested_by_customer客户要求退款
duplicate重复支付
fraudulent欺诈交易
expired_uncaptured过期未捕获
ValueDescription
requested_by_customerCustomer requested refund
duplicateDuplicate payment
fraudulentFraudulent transaction
expired_uncapturedExpired uncaptured

请求示例

{
  "order_id": "sess_xxxxxxxxxxxx",
  "refund_id": "refund_20250101001",
  "amount": "50.00",
  "currency": "USDT",
  "reason": "requested_by_customer",
  "description": "客户申请退款",
  "metadata": {
    "customer_id": "customer_123",
    "refund_note": "商品质量问题"
  }
}

重要说明:

  • order_id 必须是支付会话ID,格式为 sess_xxxxxxxxxxxx(即创建支付会话时返回的 id 字段)
  • 只有已完成的支付会话才能申请退款

Important Notes:

  • order_id must be the payment session ID, in the format sess_xxxxxxxxxxxx (i.e., the id field returned when creating a payment session)
  • Only completed payment sessions can request refunds

响应示例

{
  "refund_id": "refund_20250101001",
  "session_id": "cs_xxxxxxxxxxxx",
  "order_id": "order_20250101001",
  "amount": "50.00",
  "currency": "USDT",
  "status": "pending",
  "reason": "requested_by_customer",
  "description": "客户申请退款",
  "created_at": 1735123456,
  "metadata": {
    "customer_id": "customer_123",
    "refund_note": "商品质量问题"
  }
}

响应字段说明

字段类型说明
refund_idstring退款ID(商户提供的退款ID)
session_idstring支付会话ID
order_idstring订单ID
amountstring退款金额(面额字符串)
currencystring货币类型
statusstring退款状态
reasonstring退款原因
descriptionstring退款描述
created_atnumber创建时间戳(Unix时间戳)
metadataobject元数据
FieldTypeDescription
refund_idstringRefund ID (provided by merchant)
session_idstringPayment session ID
order_idstringOrder ID
amountstringRefund amount (decimal string)
currencystringCurrency type
statusstringRefund status
reasonstringRefund reason
descriptionstringRefund description
created_atnumberCreation timestamp (Unix timestamp)
metadataobjectMetadata

状态码

  • 201 Created: 退款创建成功
  • 400 Bad Request: 请求参数错误
  • 401 Unauthorized: 认证失败
  • 403 Forbidden: 无权访问该支付会话
  • 404 Not Found: 支付会话不存在
  • 429 Too Many Requests: 超过每日退款限制

2. 获取退款信息

根据退款ID获取退款详情。

Get refund details by refund ID.

接口地址

GET /api/v1/refunds/{refund_id}

请求头

Authorization: Bearer sk_live_xxxxxxxxxx
X-StablePay-Timestamp: 1735123456
X-StablePay-Nonce: 550e8400-e29b-41d4-a716-446655440000
X-StablePay-Signature: 3c8f9d2a7b6e5d4c3b2a1f0e9d8c7b6a5f4e3d2c1b0a9f8e7d6c5b4a3f2e1d0

路径参数

参数类型必填说明
refund_idstring是退款ID
ParameterTypeRequiredDescription
refund_idstringYesRefund ID

请求示例

curl -X GET "https://api.stablepay.co/api/v1/refunds/refund_20250101001" \
  -H "Authorization: Bearer sk_live_xxxxxxxxxx" \
  -H "X-StablePay-Timestamp: 1735123456" \
  -H "X-StablePay-Nonce: 550e8400-e29b-41d4-a716-446655440000" \
  -H "X-StablePay-Signature: 3c8f9d2a7b6e5d4c3b2a1f0e9d8c7b6a5f4e3d2c1b0a9f8e7d6c5b4a3f2e1d0"

响应示例

{
  "refund_id": "refund_20250101001",
  "session_id": "cs_xxxxxxxxxxxx",
  "order_id": "order_20250101001",
  "amount": "50.00",
  "currency": "USDT",
  "status": "completed",
  "reason": "requested_by_customer",
  "description": "客户申请退款",
  "failure_reason": null,
  "transaction_hash": "0xfedcba0987654321fedcba0987654321fedcba0987654321fedcba0987654321",
  "receipt_number": "RCPT_xxxxxxxxxxxx",
  "created_at": 1735123456,
  "processed_at": 1735123600,
  "metadata": {
    "customer_id": "customer_123",
    "refund_note": "商品质量问题"
  }
}

状态码

  • 200 OK: 查询成功
  • 400 Bad Request: 请求参数错误
  • 401 Unauthorized: 认证失败
  • 403 Forbidden: 无权访问该退款
  • 404 Not Found: 退款不存在

3. 取消退款

取消正在处理中的退款请求。

注意事项:

  • 只有状态为 processing(处理中)的退款才能取消
  • 已完成的退款(completed、failed、canceled)无法取消

Cancel a refund request that is being processed.

Notes:

  • Only refunds with status processing can be canceled
  • Completed refunds (completed, failed, canceled) cannot be canceled

接口地址

POST /api/v1/refunds/{refund_id}/cancel

请求头

Content-Type: application/json
Authorization: Bearer sk_live_xxxxxxxxxx
X-StablePay-Timestamp: 1735123456
X-StablePay-Nonce: 550e8400-e29b-41d4-a716-446655440000
X-StablePay-Signature: 3c8f9d2a7b6e5d4c3b2a1f0e9d8c7b6a5f4e3d2c1b0a9f8e7d6c5b4a3f2e1d0

路径参数

参数类型必填说明
refund_idstring是退款ID
ParameterTypeRequiredDescription
refund_idstringYesRefund ID

请求示例

curl -X POST "https://api.stablepay.co/api/v1/refunds/refund_20250101001/cancel" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk_live_xxxxxxxxxx" \
  -H "X-StablePay-Timestamp: 1735123456" \
  -H "X-StablePay-Nonce: 550e8400-e29b-41d4-a716-446655440000" \
  -H "X-StablePay-Signature: 3c8f9d2a7b6e5d4c3b2a1f0e9d8c7b6a5f4e3d2c1b0a9f8e7d6c5b4a3f2e1d0"

响应示例

{
  "refund_id": "refund_20250101001",
  "status": "canceled",
  "canceled_at": 1735123500
}

状态码

  • 200 OK: 取消成功
  • 400 Bad Request: 请求参数错误或当前状态不允许取消
  • 401 Unauthorized: 认证失败
  • 403 Forbidden: 无权取消该退款
  • 404 Not Found: 退款不存在

数据结构

Refund 退款对象

interface Refund {
  refund_id: string;              // Refund ID (provided by merchant)
  session_id: string;             // Payment session ID
  order_id: string;               // Order ID
  amount: string;                 // Refund amount (decimal string)
  currency: "USDT" | "USDC";      // Currency type
  status: RefundStatus;           // Refund status
  reason?: RefundReason;          // Refund reason
  description?: string;           // Refund description
  failure_reason?: string;        // Refund failure reason (only when failed)
  transaction_hash?: string;       // Blockchain transaction hash (only when completed)
  receipt_number?: string;        // Refund receipt number (only when completed)
  created_at: number;             // Creation timestamp
  processed_at?: number;          // Processing completion timestamp
  metadata?: Record<string, any>; // Metadata
}

退款状态

退款状态流转图:

pending → processing → completed
   ↓           ↓           ↓
   └───────────┴───────────┘
              ↓
          failed/canceled

状态说明

状态值说明
等待退款pending退款请求已提交,等待处理
处理中processing退款正在处理中
退款完成completed退款已成功完成,资金已退回
退款失败failed退款处理失败
已取消canceled退款已被取消

状态转换规则

  • pending → processing: 系统开始处理退款
  • pending → failed: 退款请求被拒绝
  • pending → canceled: 退款被取消
  • processing → completed: 退款处理成功
  • processing → failed: 退款处理失败
  • processing → canceled: 退款被取消

终态状态: completed、failed、canceled 为终态,无法再转换。

Refund status flow diagram:

pending → processing → completed
   ↓           ↓           ↓
   └───────────┴───────────┘
              ↓
          failed/canceled

Status Description

StatusValueDescription
PendingpendingRefund request submitted, waiting for processing
ProcessingprocessingRefund is being processed
CompletedcompletedRefund completed successfully, funds returned
FailedfailedRefund processing failed
CanceledcanceledRefund has been canceled

Status Transition Rules

  • pending → processing: System starts processing refund
  • pending → failed: Refund request rejected
  • pending → canceled: Refund canceled
  • processing → completed: Refund processed successfully
  • processing → failed: Refund processing failed
  • processing → canceled: Refund canceled

Final States: completed, failed, canceled are final states and cannot be transitioned further.


退款原因

原因值说明使用场景
requested_by_customer客户要求退款客户主动申请退款
duplicate重复支付客户重复支付了同一订单
fraudulent欺诈交易检测到欺诈行为
expired_uncaptured过期未捕获支付过期但未捕获
Reason ValueDescriptionUse Case
requested_by_customerCustomer requested refundCustomer proactively requests refund
duplicateDuplicate paymentCustomer made duplicate payment for the same order
fraudulentFraudulent transactionFraudulent activity detected
expired_uncapturedExpired uncapturedPayment expired but not captured

错误码

错误响应格式

{
  "error": {
    "type": "invalid_request_error",
    "code": "REFUND_AMOUNT_EXCEEDED",
    "message": "退款金额超过原支付金额",
    "param": "amount",
    "doc_url": "https://docs.stablepay.co/errors#REFUND_AMOUNT_EXCEEDED"
  },
  "request_id": "req_xxxxxxxxxxxx",
  "timestamp": 1735123456
}

常见错误码

错误码HTTP状态码说明
invalid_api_key401API密钥无效
MISSING_CHARGE400缺少支付会话ID
MISSING_REFUND_ID400缺少退款ID
INVALID_JSON400请求参数格式错误
INVALID_CURRENCY400不支持的货币类型
INVALID_AMOUNT400无效的金额格式或金额必须大于零
SESSION_NOT_FOUND404支付会话不存在
session_access_denied403无权访问该支付会话
REFUND_NOT_FOUND404退款不存在
FORBIDDEN403无权访问该退款
INVALID_SESSION_STATUS400只有已完成的支付才能退款
REFUND_AMOUNT_EXCEEDED400退款金额超过原支付金额
REFUND_TIME_EXPIRED400退款时间已过期
CANNOT_CANCEL_REFUND400当前状态不允许取消退款
DAILY_REFUND_LIMIT_EXCEEDED429超过每日退款限制
Error CodeHTTP StatusDescription
invalid_api_key401Invalid API key
MISSING_CHARGE400Missing payment session ID
MISSING_REFUND_ID400Missing refund ID
INVALID_JSON400Invalid request parameters format
INVALID_CURRENCY400Unsupported currency type
INVALID_AMOUNT400Invalid amount format or amount must be greater than zero
SESSION_NOT_FOUND404Payment session does not exist
session_access_denied403Access to payment session denied
REFUND_NOT_FOUND404Refund does not exist
FORBIDDEN403Access to refund denied
INVALID_SESSION_STATUS400Only completed payments can be refunded
REFUND_AMOUNT_EXCEEDED400Refund amount exceeds original payment amount
REFUND_TIME_EXPIRED400Refund time expired
CANNOT_CANCEL_REFUND400Current status does not allow refund cancellation
DAILY_REFUND_LIMIT_EXCEEDED429Daily refund limit exceeded

示例代码

cURL 示例

创建退款

curl -X POST "https://api.stablepay.co/api/v1/refunds/create" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk_live_xxxxxxxxxx" \
  -d '{
    "order_id": "sess_xxxxxxxxxxxx",
    "refund_id": "refund_20250101001",
    "amount": "50.00",
    "currency": "USDT",
    "reason": "requested_by_customer",
    "description": "客户申请退款"
  }'

获取退款信息

curl -X GET "https://api.stablepay.co/api/v1/refunds/refund_20250101001" \

取消退款

curl -X POST "https://api.stablepay.co/api/v1/refunds/refund_20250101001/cancel" \
  -H "Content-Type: application/json" \

JavaScript/Node.js 示例

const axios = require('axios');

const API_BASE_URL = 'https://api.stablepay.co/api/v1';
const API_KEY = 'sk_live_xxxxxxxxxx';

// 创建退款
async function createRefund(orderId, refundId, amount, currency, reason) {
  try {
    const response = await axios.post(
      `${API_BASE_URL}/refunds/create`,
      {
        order_id: orderId,
        refund_id: refundId,
        amount: amount,
        currency: currency,
        reason: reason,
        description: '客户申请退款'
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${API_KEY}`
        }
      }
    );

    console.log('退款创建成功:', response.data);
    return response.data;
  } catch (error) {
    console.error('创建退款失败:', error.response?.data || error.message);
    throw error;
  }
}

// 获取退款信息
async function getRefund(refundId) {
  try {
    const response = await axios.get(
      `${API_BASE_URL}/refunds/${refundId}`,
      {
        headers: {
          'Authorization': `Bearer ${API_KEY}`
        }
      }
    );

    console.log('退款详情:', response.data);
    return response.data;
  } catch (error) {
    console.error('获取退款失败:', error.response?.data || error.message);
    throw error;
  }
}

// 取消退款
async function cancelRefund(refundId) {
  try {
    const response = await axios.post(
      `${API_BASE_URL}/refunds/${refundId}/cancel`,
      {},
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${API_KEY}`
        }
      }
    );

    console.log('退款已取消:', response.data);
    return response.data;
  } catch (error) {
    console.error('取消退款失败:', error.response?.data || error.message);
    throw error;
  }
}

// 使用示例
(async () => {
  const orderId = 'sess_xxxxxxxxxxxx'; // 支付会话ID,格式:sess_xxxxxxxxxxxx
  const refundId = `refund_${Date.now()}`;

  // 创建退款
  const refund = await createRefund(
    orderId,
    refundId,
    '50.00',
    'USDT',
    'requested_by_customer'
  );

  // 查询退款状态
  const refundDetail = await getRefund(refundId);

  // 如果退款还在处理中,可以取消
  if (refundDetail.status === 'processing') {
    await cancelRefund(refundId);
  }
})();

Python 示例

import requests
import time

API_BASE_URL = 'https://api.stablepay.co/api/v1'
API_KEY = 'sk_live_xxxxxxxxxx'

def create_refund(order_id, refund_id, amount, currency, reason='requested_by_customer'):
    """创建退款"""
    url = f'{API_BASE_URL}/refunds/create'
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {API_KEY}'
    }
    data = {
        'order_id': order_id,
        'refund_id': refund_id,
        'amount': amount,
        'currency': currency,
        'reason': reason,
        'description': '客户申请退款'
    }

    response = requests.post(url, headers=headers, json=data)
    response.raise_for_status()
    return response.json()

def get_refund(refund_id):
    """获取退款信息"""
    url = f'{API_BASE_URL}/refunds/{refund_id}'
    headers = {
        'Authorization': f'Bearer {API_KEY}'
    }

    response = requests.get(url, headers=headers)
    response.raise_for_status()
    return response.json()

def cancel_refund(refund_id):
    """取消退款"""
    url = f'{API_BASE_URL}/refunds/{refund_id}/cancel'
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {API_KEY}'
    }

    response = requests.post(url, headers=headers)
    response.raise_for_status()
    return response.json()

# 使用示例
if __name__ == '__main__':
    order_id = 'sess_xxxxxxxxxxxx'  # 支付会话ID,格式:sess_xxxxxxxxxxxx
    refund_id = f'refund_{int(time.time())}'

    # 创建退款
    refund = create_refund(
        order_id,
        refund_id,
        '50.00',
        'USDT',
        'requested_by_customer'
    )
    print('退款创建成功:', refund)

    # 查询退款状态
    refund_detail = get_refund(refund_id)
    print('退款详情:', refund_detail)

    # 如果退款还在处理中,可以取消
    if refund_detail['status'] == 'processing':
        canceled_refund = cancel_refund(refund_id)
        print('退款已取消:', canceled_refund)
最后更新 / Last Updated: 2025/12/16 08:50
Prev
支付服务 / Payment Service
Next
Webhook 通知 / Webhook Notifications