iPayXXAPI 文档

示例代码

多语言 SDK 示例与最佳实践

cURL 示例

创建订单

curl -X POST https://api.ipayxx.cn/v1/orders \
  -H "Authorization: Bearer sk_test_xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "product_id": "prod_pro_license",
    "amount": 29900,
    "currency": "CNY",
    "description": "专业版许可证"
  }'

查询订单

curl https://api.ipayxx.cn/v1/orders/ORD20260308100001 \
  -H "Authorization: Bearer sk_test_xxxxxxxxxxxx"

激活授权

curl -X POST https://api.ipayxx.cn/v1/licenses/activate \
  -H "Content-Type: application/json" \
  -d '{
    "license_key": "LIC-ABCD-EFGH-IJKL-MNOP",
    "device_id": "hw_fingerprint_abc123",
    "device_name": "MacBook Pro"
  }'

移除设备

curl -X DELETE https://api.ipayxx.cn/v1/licenses/LIC-ABCD-EFGH-IJKL-MNOP/devices/hw_fingerprint_abc123 \
  -H "Authorization: Bearer sk_test_xxxxxxxxxxxx"

Node.js / TypeScript

安装

# SDK 即将发布,当前可直接使用 HTTP 请求
npm install node-fetch  # Node.js < 18

完整示例

const API_BASE = 'https://api.ipayxx.cn/v1';
const API_KEY = 'sk_test_xxxxxxxxxxxx';

// 创建订单
async function createOrder() {
  const response = await fetch(`${API_BASE}/orders`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      product_id: 'prod_pro_license',
      amount: 29900,
      currency: 'CNY',
      description: '专业版许可证',
      buyer_email: '[email protected]',
    }),
  });

  const result = await response.json();

  if (result.code === 0) {
    console.log('订单创建成功:', result.data.order_no);
    console.log('收银台链接:', result.data.pay_url);
  } else {
    console.error('创建失败:', result.message);
  }

  return result;
}

// 查询订单
async function getOrder(orderNo: string) {
  const response = await fetch(`${API_BASE}/orders/${orderNo}`, {
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
    },
  });

  return response.json();
}

// 激活授权
async function activateLicense(
  licenseKey: string,
  deviceId: string,
  deviceName?: string
) {
  const response = await fetch(`${API_BASE}/licenses/activate`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      license_key: licenseKey,
      device_id: deviceId,
      device_name: deviceName,
    }),
  });

  return response.json();
}

// 使用示例
async function main() {
  // 1. 创建订单
  const order = await createOrder();

  // 2. 用户完成支付后,查询订单获取 license_key
  const orderDetail = await getOrder(order.data.order_no);

  if (orderDetail.data.status === 'paid') {
    // 3. 激活授权
    const activation = await activateLicense(
      orderDetail.data.license_key,
      'device_001',
      'My Computer'
    );
    console.log('激活结果:', activation);
  }
}

main().catch(console.error);

Webhook 处理示例 (Express)

import express from 'express';
import crypto from 'crypto';

const app = express();
const WEBHOOK_SECRET = 'whsec_xxxxxxxxxxxx';

app.post('/webhook/ipayxx', express.json(), (req, res) => {
  // 验证签名
  const signature = req.headers['x-webhook-signature'] as string;
  const timestamp = req.headers['x-webhook-timestamp'] as string;
  const body = JSON.stringify(req.body);

  const expected = crypto
    .createHmac('sha256', WEBHOOK_SECRET)
    .update(`${timestamp}.${body}`)
    .digest('hex');

  if (signature !== expected) {
    return res.status(401).json({ error: '签名验证失败' });
  }

  // 处理事件
  const { type, data } = req.body;

  switch (type) {
    case 'order.paid':
      console.log('订单已支付:', data.order_no);
      // 发送发货通知、更新数据库等
      break;

    case 'license.activated':
      console.log('授权已激活:', data.license_key);
      break;

    case 'license.revoked':
      console.log('授权已吊销:', data.license_key);
      break;
  }

  // 快速返回 200
  res.json({ received: true });
});

app.listen(3000);

Python

安装依赖

pip install requests

基础用法

import requests

API_BASE = "https://api.ipayxx.cn/v1"
API_KEY = "sk_test_xxxxxxxxxxxx"

headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json",
}


def create_order(product_id: str, amount: int, description: str):
    """创建订单"""
    response = requests.post(
        f"{API_BASE}/orders",
        headers=headers,
        json={
            "product_id": product_id,
            "amount": amount,
            "currency": "CNY",
            "description": description,
        },
    )
    return response.json()


def get_order(order_no: str):
    """查询订单"""
    response = requests.get(
        f"{API_BASE}/orders/{order_no}",
        headers=headers,
    )
    return response.json()


def activate_license(license_key: str, device_id: str, device_name: str = None):
    """激活授权"""
    payload = {
        "license_key": license_key,
        "device_id": device_id,
    }
    if device_name:
        payload["device_name"] = device_name

    response = requests.post(
        f"{API_BASE}/licenses/activate",
        headers={"Content-Type": "application/json"},
        json=payload,
    )
    return response.json()


# 使用示例
if __name__ == "__main__":
    # 创建订单
    order = create_order("prod_pro_license", 29900, "专业版许可证")
    print(f"订单号: {order['data']['order_no']}")
    print(f"收银台: {order['data']['pay_url']}")

    # 查询订单
    detail = get_order(order["data"]["order_no"])
    print(f"订单状态: {detail['data']['status']}")

注意事项

  • 以上示例使用测试密钥 (sk_test_),不会产生实际交易
  • 生产环境请替换为生产密钥 (sk_live_)
  • 所有金额单位为分(如 29900 = 299.00 元)
  • 建议在服务端调用 API,切勿在客户端暴露密钥
  • 官方 SDK 即将发布,届时将提供更便捷的调用方式