# Wallet Auto-Order API Guide

Version: `v2.1`  
Updated: `2026-10-14`  
Production base URL: `https://98-xj.com`  
Settlement currency: use the `currency` returned by the API; currently `CNY`

[简体中文](/docs/cardnet-upstream-api-v2.zh-CN.md) | [繁體中文](/docs/cardnet-upstream-api-v2.zh-TW.md) | [English](/docs/cardnet-upstream-api-v2.en-US.md) | [Tiếng Việt](/docs/cardnet-upstream-api-v2.vi-VN.md) | [Русский](/docs/cardnet-upstream-api-v2.ru-RU.md) | [Türkçe](/docs/cardnet-upstream-api-v2.tr-TR.md)

## 1. Integration overview

This API is available to customers whose API credentials have been approved and enabled.

- Fund your wallet balance on this site before placing orders.
- The wallet balance is debited immediately when an order is placed.
- Only automatic-fulfillment products and `wallet` balance payment are supported.
- No payment link or USDT receiving address is returned.
- Order placement, wallet debit, inventory reservation, wallet ledger entry, order creation, and automatic fulfillment run in a single transaction; if any step fails, no partial order or standalone debit is produced.
- After an order is created successfully, retrieve the card secrets through the order query endpoint.
- Keep the API Key and API Secret on the server side only. Never put them in web pages, app front ends, or public repositories.

The platform provides the customer with:

```text
API_BASE_URL=https://98-xj.com
API_KEY=<provided by the platform>
API_SECRET=<provided by the platform>
```

> **Important: use the API Secret exactly as the complete original text displayed on the page, as a UTF-8 string.**  
> Even if the current Secret looks like 128-character hexadecimal text, do not hex-decode it, Base64-decode it, or change its case. Decoding it into 64 bytes before computing the HMAC produces an incorrect signature. The API Key and API Secret must come from the same credential; regenerating the Secret invalidates the old Secret immediately.

### 1.1 Credential security

- **Generating or regenerating a Secret requires re-verification**: when you do this in Personal Center under "API Integration", you must enter your current Login password; accounts with two-factor authentication enabled must also enter the Two-factor authentication code. Accounts that have never set a Login password (for example, accounts auto-registered through Telegram) must first set one under "Security".
- **Changing or resetting the Login password invalidates the Secret**: after the password changes, the old API Secret is invalidated immediately and all requests return `401 authentication_failed`. Sign in to Personal Center to regenerate the Secret, and update your server configuration accordingly.
- **IP allowlist (strongly recommended)**: in Personal Center, go to "API Integration → IP allowlist" to set the source IPs allowed to call the API yourself. Enter one IP or CIDR per line (such as `203.0.113.10` or `203.0.113.0/24`), up to 20 entries; `0.0.0.0/0` is not allowed. Saving also requires re-verification and takes effect immediately. Requests from a source IP that is not on the allowlist return `403 authentication_failed`; leaving it empty means no restriction. Enter your server's fixed egress IP so that, even if the Key and Secret leak, they cannot be used anywhere else.
- **Rate limits on sensitive operations**: a single account may generate a Secret or modify the IP allowlist at most 10 times within 10 minutes; exceeding this suspends these operations for 15 minutes.

## 2. Endpoints

| Method | Path | Purpose |
| --- | --- | --- |
| `POST` | `/api/v1/upstream/ping` | Verify credentials and read the wallet balance |
| `GET` | `/api/v1/upstream/categories` | List product categories |
| `GET` | `/api/v1/upstream/products` | List products |
| `GET` | `/api/v1/upstream/products/:id` | Get a single product |
| `POST` | `/api/v1/upstream/orders` | Create a wallet-funded order |
| `GET` | `/api/v1/upstream/orders/:id` | Query an order and its card secrets |
| `POST` | `/api/v1/upstream/orders/:id/cancel` | Cancel an eligible order |

All credentials accept only the HMAC-SHA256 v2 signature described below; legacy three-part signatures without a nonce always return `401 authentication_failed`.

## 3. Request signing

### 3.1 Required headers

| Header | Description |
| --- | --- |
| `Dujiao-Next-Api-Key` | API Key provided by the platform |
| `Dujiao-Next-Timestamp` | Current Unix timestamp in seconds |
| `Dujiao-Next-Nonce` | Random string unique to this request; UUID v4 is recommended |
| `Dujiao-Next-Signature` | HMAC-SHA256 signature in lowercase hexadecimal |

For a JSON request body, also send:

```http
Content-Type: application/json
```

### 3.2 Canonical string

```text
METHOD\nPATH\nTIMESTAMP\nNONCE\nSHA256(RAW_BODY)
```

Rules:

1. `METHOD`: the uppercase HTTP method, for example `GET` or `POST`.
2. `PATH`: only the URL path, excluding the domain, query parameters, and `#fragment`.
3. `TIMESTAMP`: the Unix timestamp in seconds, exactly the same as in the request header.
4. `NONCE`: the random string, exactly the same as in the request header.
5. `SHA256(RAW_BODY)`: the lowercase hexadecimal SHA-256 of the raw bytes of the body actually sent.
6. Join the five fields with a single line feed `\n`, and do not append a trailing line feed.
7. Final signature:

```text
hex_lower(HMAC_SHA256(API_SECRET, canonical_string))
```

For GET requests and POST requests without a request body, `RAW_BODY` is an empty byte string:

```text
SHA256("") = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
```

Important constraints:

- The server accepts a clock skew of up to `60` seconds in either direction; the customer's server must keep its clock synchronized.
- Every request must use a new `nonce`; network retries must not reuse an old nonce either.
- Do not modify JSON whitespace, field order, encoding, or line breaks after signing.
- Query parameters are not signed, but the path must be signed.
- Requests must not use gzip or any other compression encoding.
- The maximum size of a single request body is `65,536` bytes.
- UTF-8 encode `API_SECRET` directly and use the result as the HMAC key; do not decode a hex-looking Secret into binary.
- The API Key and Secret must be used as a pair; after the Secret is rotated, update the client configuration atomically and restart or hot-reload the calling processes.

### 3.3 Fixed test vector

Before sending real requests to the production API, the client must first pass the following offline test vector. The Secret here is a public test value and must not be used in production:

```text
API_SECRET = 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
METHOD     = POST
PATH       = /api/v1/upstream/ping
TIMESTAMP  = 1709625600
NONCE      = 550e8400-e29b-41d4-a716-446655440000
RAW_BODY   = empty byte string
BODY_HASH  = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
SIGNATURE  = 09cf5cedb04ba4b32552c7e9d8c533368eeb48dd9ba1b72fd1e2c151e9487819
```

If your locally computed result is not the `SIGNATURE` above, do not call the production API. Check these first: whether the Secret was hex/Base64-decoded, whether line breaks are `\n`, whether an extra trailing line feed was appended, and whether PATH includes the domain or query parameters.

### 3.4 Python signing and request example

Dependency:

```bash
pip install requests
```

Example:

```python
import hashlib
import hmac
import json
import os
import time
import uuid
from urllib.parse import urlencode

import requests

BASE_URL = "https://98-xj.com"
API_KEY = os.environ["CARDNET_API_KEY"]
API_SECRET = os.environ["CARDNET_API_SECRET"]


def api_request(method, path, *, query=None, payload=None, timeout=15):
    method = method.upper()
    raw_body = b""
    if payload is not None:
        raw_body = json.dumps(
            payload,
            ensure_ascii=False,
            separators=(",", ":"),
        ).encode("utf-8")

    timestamp = int(time.time())
    nonce = str(uuid.uuid4())
    body_hash = hashlib.sha256(raw_body).hexdigest()
    canonical = (
        f"{method}\n{path}\n{timestamp}\n{nonce}\n{body_hash}"
    ).encode("utf-8")
    signature = hmac.new(
        API_SECRET.encode("utf-8"),
        canonical,
        hashlib.sha256,
    ).hexdigest()

    headers = {
        "Dujiao-Next-Api-Key": API_KEY,
        "Dujiao-Next-Timestamp": str(timestamp),
        "Dujiao-Next-Nonce": nonce,
        "Dujiao-Next-Signature": signature,
    }
    if payload is not None:
        headers["Content-Type"] = "application/json"

    url = BASE_URL + path
    if query:
        url += "?" + urlencode(query)

    response = requests.request(
        method,
        url,
        data=raw_body if payload is not None else None,
        headers=headers,
        timeout=timeout,
    )
    return response.status_code, response.json()


# Verify credentials and balance
status, result = api_request("POST", "/api/v1/upstream/ping")
print(status, result)

# Create an order
status, result = api_request(
    "POST",
    "/api/v1/upstream/orders",
    payload={
        "sku_id": 123,
        "quantity": 1,
        "downstream_order_no": "merchant-20260718-0001",
        "payment_mode": "wallet",
    },
)
print(status, result)

# Query the order and card secrets
if result.get("order_id"):
    order_id = result["order_id"]
    status, detail = api_request(
        "GET",
        f"/api/v1/upstream/orders/{order_id}",
    )
    print(status, detail)
```

### 3.5 Node.js signing example

Works with Node.js 18 and later. Pass `API_SECRET` directly to HMAC as UTF-8 text:

```javascript
import crypto from "node:crypto";

function signV2(secret, method, path, timestamp, nonce, rawBody = Buffer.alloc(0)) {
  const bodyHash = crypto.createHash("sha256").update(rawBody).digest("hex");
  const canonical = `${method.toUpperCase()}\n${path}\n${timestamp}\n${nonce}\n${bodyHash}`;
  return crypto.createHmac("sha256", Buffer.from(secret, "utf8"))
    .update(Buffer.from(canonical, "utf8"))
    .digest("hex");
}

const method = "POST";
const path = "/api/v1/upstream/ping";
const timestamp = Math.floor(Date.now() / 1000);
const nonce = crypto.randomUUID();
const rawBody = Buffer.alloc(0);
const signature = signV2(
  process.env.CARDNET_API_SECRET,
  method,
  path,
  timestamp,
  nonce,
  rawBody,
);

const response = await fetch(`https://98-xj.com${path}`, {
  method,
  headers: {
    "Dujiao-Next-Api-Key": process.env.CARDNET_API_KEY,
    "Dujiao-Next-Timestamp": String(timestamp),
    "Dujiao-Next-Nonce": nonce,
    "Dujiao-Next-Signature": signature,
  },
});
console.log(response.status, await response.json());
```

### 3.6 Go signing example

```go
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"strings"
)

func signV2(secret, method, path, timestamp, nonce string, rawBody []byte) string {
	bodyHash := sha256.Sum256(rawBody)
	canonical := strings.Join([]string{
		strings.ToUpper(method),
		path,
		timestamp,
		nonce,
		hex.EncodeToString(bodyHash[:]),
	}, "\n")
	mac := hmac.New(sha256.New, []byte(secret)) // raw UTF-8 bytes of the Secret
	_, _ = mac.Write([]byte(canonical))
	return fmt.Sprintf("%x", mac.Sum(nil))
}
```

## 4. Verify credentials and read the balance

```http
POST /api/v1/upstream/ping
```

The request body is empty.

Success response:

```json
{
  "ok": true,
  "site_name": "Site name",
  "protocol_version": "1.0",
  "user_id": 1001,
  "balance": "500.00",
  "currency": "CNY",
  "member_level": null
}
```

`balance` is the currently posted, available balance. Check the balance before placing an order, but the create-order response is authoritative for whether the debit finally succeeds.

## 5. List product categories

```http
GET /api/v1/upstream/categories
```

Success response:

```json
{
  "ok": true,
  "categories": [
    {
      "id": 1,
      "parent_id": 0,
      "slug": "example",
      "name": {
        "zh-CN": "Example category"
      },
      "icon": "",
      "sort_order": 0
    }
  ]
}
```

## 6. Query products

### 6.1 Product list

```http
GET /api/v1/upstream/products?page=1&page_size=50
```

Query parameters:

| Parameter | Required | Description |
| --- | --- | --- |
| `page` | No | Page number; default `1` |
| `page_size` | No | Items per page; default and maximum `50` |
| `include_inactive` | No | Includes delisted products when `true` |
| `updated_after` | No | RFC3339 time, for example `2026-07-18T00:00:00Z` |

Success response structure:

```json
{
  "ok": true,
  "items": [
    {
      "id": 10,
      "slug": "example-product",
      "title": {
        "zh-CN": "Example product"
      },
      "price_amount": "20.00",
      "fulfillment_type": "auto",
      "is_active": true,
      "category_id": 1,
      "wholesale_prices": [
        {
          "min_quantity": 10,
          "unit_price": "18.00"
        }
      ],
      "skus": [
        {
          "id": 123,
          "sku_code": "SKU-001",
          "spec_values": {},
          "price_amount": "20.00",
          "stock_status": "in_stock",
          "stock_quantity": 50,
          "is_active": true
        }
      ],
      "created_at": "2026-07-18T00:00:00Z",
      "updated_at": "2026-07-18T00:00:00Z"
    }
  ],
  "total": 1,
  "page": 1,
  "page_size": 50,
  "includes_inactive": false
}
```

Stock states:

| `stock_status` | Description |
| --- | --- |
| `in_stock` | In stock |
| `low_stock` | Low stock |
| `out_of_stock` | Out of stock |
| `unlimited` | Unlimited stock; `stock_quantity` is `-1` |

Wallet API orders support only available automatic-fulfillment SKUs with `fulfillment_type=auto`. The actual price, purchase limits, and stock are revalidated inside the order transaction; the `amount` returned by order creation is the final transaction amount.

### 6.2 Single product

```http
GET /api/v1/upstream/products/10
```

Success response:

```json
{
  "ok": true,
  "product": {
    "id": 10,
    "title": {
      "zh-CN": "Example product"
    },
    "price_amount": "20.00",
    "fulfillment_type": "auto",
    "is_active": true,
    "skus": [
      {
        "id": 123,
        "sku_code": "SKU-001",
        "price_amount": "20.00",
        "stock_status": "in_stock",
        "stock_quantity": 50,
        "is_active": true
      }
    ]
  }
}
```

## 7. Create a wallet-funded order

```http
POST /api/v1/upstream/orders
Content-Type: application/json
```

Request fields:

| Field | Required | Description |
| --- | --- | --- |
| `sku_id` | Yes | SKU ID returned by the product API |
| `quantity` | Yes | Positive integer; the current API maximum is `100`, and the product's own limits also apply |
| `downstream_order_no` | Yes | Your own unique order number, which also serves as the idempotency key |
| `payment_mode` | No | Omit it, send `null`, or send `"wallet"`; nothing else is accepted |
| `trace_id` | No | Customer trace ID |
| `callback_url` | No | Not currently supported; omit it, send `null`, or send an empty string |
| `manual_form_data` | No | Not currently supported; omit it, send `null`, or send an empty object `{}` |

`downstream_order_no` and any non-empty `trace_id` must match:

```regex
^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$
```

Recommended request body:

```json
{
  "sku_id": 123,
  "quantity": 2,
  "downstream_order_no": "merchant-20260718-0001",
  "payment_mode": "wallet",
  "trace_id": "trace-20260718-0001"
}
```

Success response:

```json
{
  "ok": true,
  "order_id": 456,
  "order_no": "EXAMPLE-ORDER-NO",
  "status": "completed",
  "amount": "40.00",
  "currency": "CNY",
  "downstream_order_no": "merchant-20260718-0001",
  "trace_id": "trace-20260718-0001"
}
```

The create endpoint does not return card secrets directly. After receiving a success response, use `order_id` to query the order details.

### 7.1 Idempotency rules

The idempotency scope is:

```text
(current API credential, downstream_order_no)
```

- Same `downstream_order_no` with the same `sku_id` and `quantity`: the original order is returned, with no duplicate debit or duplicate inventory reservation.
- Same `downstream_order_no` but a different `sku_id` or `quantity`: `idempotency_conflict` is returned.
- Omitting `payment_mode`, sending `null`, and sending `wallet` are equivalent.
- When a network timeout or 5xx error leaves the result uncertain, you must retry with the original `downstream_order_no` and the original business parameters, but generate a new timestamp, nonce, and signature every time.
- Do not change the `downstream_order_no` just because the first response timed out; otherwise a second real order may be created.

## 8. Query an order and card secrets

```http
GET /api/v1/upstream/orders/456
```

Success response:

```json
{
  "ok": true,
  "order_id": 456,
  "order_no": "EXAMPLE-ORDER-NO",
  "status": "completed",
  "amount": "40.00",
  "refunded_amount": "0.00",
  "currency": "CNY",
  "refund_records": [],
  "items": [
    {
      "product_id": 10,
      "sku_id": 123,
      "title": {
        "zh-CN": "Example product"
      },
      "quantity": 2,
      "unit_price": "20.00",
      "total_price": "40.00",
      "fulfillment_type": "auto"
    }
  ],
  "fulfillment": {
    "type": "auto",
    "status": "delivered",
    "payload": "<card secret content>",
    "delivery_data": {},
    "delivered_at": "2026-07-18T00:00:00Z"
  }
}
```

`fulfillment.payload` and `fulfillment.delivery_data` may contain card secrets and must be handled as sensitive data:

- Transmit them only over HTTPS.
- Never write them to ordinary access logs, error logs, or monitoring labels.
- Never return them to unauthorized users.

Common order states:

| State | Description |
| --- | --- |
| `paid` | Paid |
| `fulfilling` | Fulfillment in progress |
| `partially_delivered` | Partially delivered |
| `delivered` | Delivered |
| `completed` | Completed |
| `partially_refunded` | Partially refunded |
| `refunded` | Refunded |
| `canceled` | Canceled |

A normal wallet-funded automatic card-secret order usually returns `completed` directly.

## 9. Cancel an order

```http
POST /api/v1/upstream/orders/456/cancel
```

The request body is empty.

Success response:

```json
{
  "ok": true,
  "order_id": 456,
  "order_no": "EXAMPLE-ORDER-NO",
  "status": "canceled"
}
```

Orders that have already been automatically fulfilled or completed usually cannot be canceled and return `cancel_not_allowed`.

## 10. Error responses

Error envelope:

```json
{
  "ok": false,
  "error_code": "invalid_request",
  "error_message": "request rejected"
}
```

Handle errors based on the HTTP status code and `error_code`; do not rely on the `error_message` text.

| HTTP | `error_code` | Meaning and handling |
| --- | --- | --- |
| `400` | `bad_request` | Malformed path parameter (for example, an order ID or product ID that is not purely numeric); correct it before sending the request again |
| `400` | `invalid_request` | Invalid JSON format, field name, field type, or value (including unknown fields and a malformed `downstream_order_no`) |
| `400` | `payment_mode_not_supported` | `payment_mode` must be omitted, `null`, or `"wallet"` |
| `400` | `callback_not_supported` | `callback_url` must be omitted, `null`, or an empty string |
| `400` | `product_not_supported` | The SKU does not exist, has been delisted, is not automatic-fulfillment, or the quantity does not meet the purchase limits; choose another SKU or adjust the quantity |
| `401` | `authentication_failed` | Returned for every authentication failure: missing request headers, an invalid or disabled API Key, a disabled account, an incorrect signature, a timestamp outside ±60 seconds or not an integer number of seconds, a missing nonce, a Secret invalidated by a password change, and so on. Pause automatic requests and raise an alert, check each item, then manually retry `/ping` once |
| `403` | `authentication_failed` | The signature is valid, but the source IP is not on this credential's IP allowlist; verify the server's egress IP, or update the allowlist in Personal Center |
| `403` | `wallet_order_not_enabled` | Wallet ordering is not enabled for this credential; contact the platform |
| `403` | `member_level_required` | This product can only be purchased by specified member levels |
| `403` | `credential_paused` | API calls for this credential have been paused; contact the platform |
| `404` | `product_not_found` | The product does not exist |
| `404` | `order_not_found` | The order does not exist or does not belong to the current account |
| `409` | `replay_detected` | The nonce has already been used; generate a new nonce and re-sign, keeping the business parameters unchanged |
| `409` | `idempotency_conflict` | The same `downstream_order_no` is bound to a different product or quantity; stop automatic retries |
| `409` | `insufficient_balance` | Insufficient wallet balance; top up first and confirm the funds have been credited |
| `409` | `insufficient_stock` | Insufficient stock; choose another product, reduce the quantity, or retry later |
| `409` | `cancel_not_allowed` | The current order state does not allow cancellation |
| `413` | `invalid_request` | The request body exceeds `65,536` bytes |
| `415` | `invalid_request` | The request uses gzip or another compression encoding |
| `429` | `rate_limited` | Rate limit exceeded; back off according to `Retry-After` (if present), then retry with a new timestamp, nonce, and signature |
| `500` | `internal_error` | Internal error on a query endpoint; back off and retry |
| `503` | `service_unavailable` | Service temporarily unavailable or concurrency limit reached; keep the original idempotency parameters, back off, and retry with a new signature |

> `401` and `403` indicate a credential, signature, or account configuration problem; the client must pause automatic requests and raise an alert. After fixing the configuration, first retry `/ping` manually only once; never retry authentication failures indefinitely.

## 11. Rate limits and retries

- The total request limit per credential is **60 requests/minute**; exceeding it blocks the credential for `30` seconds, during which `429 rate_limited` is returned.
- The pre-authentication request limit per source IP is **120 requests/minute**; exceeding it blocks that IP for `5` minutes.
- Keep write requests such as create and cancel at a concurrency of no more than `2`, and query requests at no more than `8`; excess requests return `503 service_unavailable`.
- We recommend keeping order creation within **5 requests/10 seconds**.
- Only `429`, `503`, and network timeouts may use exponential backoff, for example **1, 2, 4, 8** seconds.
- On `401` or `403`, immediately pause automatic calls and raise an alert; automatic retries are forbidden, so that a misconfiguration cannot turn into a request storm.
- When retrying order creation, keep the same `downstream_order_no`, `sku_id`, and `quantity`, but always generate a new timestamp, nonce, and signature.
- `insufficient_balance`, `insufficient_stock`, `sku_unavailable`, `product_unavailable`, and `idempotency_conflict` should not be retried blindly.

## 12. Go-live checklist

Before going live, the customer should confirm that:

1. The API credential has been approved and enabled.
2. The API Key is the 64-character Key shown in the dashboard, and the API Secret is the complete 128-character original text shown when it was generated.
3. The fixed offline test vector passes, confirming that the Secret has not been hex/Base64-decoded.
4. `POST /api/v1/upstream/ping` returns `ok=true`.
5. The wallet `balance` is sufficient to pay for a test order.
6. The customer's server clock is synchronized.
7. The API Secret is stored only in server-side environment variables or a secrets management system.
8. Signatures are computed over the raw body that is actually sent.
9. Order creation implements idempotent retries keyed on `downstream_order_no`.
10. The client never automatically retries `401` or `403`, and card secrets never enter ordinary logs.
11. An IP allowlist containing only the server's fixed egress IP has been configured in Personal Center (recommended).
12. A process is in place to update the Secret on the server after the Login password is changed or the Secret is regenerated.

## 13. Changelog

### 2026-10-14 · v2.1

- Added "1.1 Credential security": generating or regenerating a Secret requires re-verification; changing or resetting the Login password invalidates the Secret; the IP allowlist can be configured self-service.
- Rewrote the error code table to match actual responses: all authentication failures return `401 authentication_failed`, an IP not on the allowlist returns `403 authentication_failed`, and insufficient balance returns `409 insufficient_balance`; added `member_level_required`, `wallet_order_not_enabled`, `credential_paused`, `product_not_found`, and `internal_error`.
- Added block durations and per-IP limits to the rate limits.
- Added Vietnamese, Russian, and Turkish versions.

### 2026-08-27 · v2.0

- Clarified the five-part canonical format of HMAC-SHA256 v2.
- Clarified that the 128-character API Secret is used as raw UTF-8 text; hex/Base64 decoding is prohibited.
- Added a fixed test vector that can be verified offline, plus Python, Node.js, and Go examples.
- Completed the actual authentication error codes and specified that `401` and `403` must not be retried automatically.
