# Shop API v1

This API lets an account list products, create orders, pay from its CNY balance, and read its own orders and delivery results. The existing owner key remains available for the Telegram bot and trusted payment integrations.

**Quick start:** Sign in to the shop, then [add funds and create your personal API credentials](/en/account). Once your deposit is credited, sign requests with your personal `API Key` and `API Secret` as described below. Set `"payment_method": "balance"` when calling `POST /orders` to pay directly from your account balance, without submitting an email address or order lookup password. Personal credentials can only access your own orders.

Base URL: `https://shop.newzoe.cloud/api/v1`

Personal credentials are generated on the [account page](/account). The secret is displayed once; rotating it immediately invalidates the old key and secret. The owner integration instead configures a dedicated key and secret in the shop environment:

```dotenv
DUJIAOKA_API_KEY=YOUR_API_KEY
DUJIAOKA_API_SECRET=YOUR_API_SECRET
DUJIAOKA_API_TIMESTAMP_TOLERANCE=300
DUJIAOKA_API_IDEMPOTENCY_TTL=86400
```

Generate both values with a cryptographically secure random generator. Keep them outside source control and rotate them together when an integration is replaced.

## Authentication

Every v1 request uses these headers:

| Header | Description |
| --- | --- |
| `X-Api-Key` | The configured API key. |
| `X-Api-Timestamp` | Unix timestamp in seconds. The default acceptance window is 5 minutes. |
| `X-Api-Nonce` | A unique 8-128 character value for this request. |
| `X-Api-Signature` | Lowercase hexadecimal HMAC-SHA256 signature. |
| `Content-Type` | `application/json` for requests with a body. |

Sign this exact five-line string with your personal API Secret, or `DUJIAOKA_API_SECRET` for the owner integration:

```text
HTTP_METHOD\n
/api/v1/path[?query]\n
X-Api-Timestamp\n
X-Api-Nonce\n
RAW_REQUEST_BODY
```

The path includes `/api/v1`, the method is uppercase, and the body is the exact byte sequence sent on the wire. GET requests use an empty final line. A nonce is accepted once only.

Example signing helper in Python:

```python
import hashlib
import hmac
import secrets
import time

def api_headers(method, path, body, api_key, api_secret):
    timestamp = str(int(time.time()))
    nonce = secrets.token_urlsafe(18)
    canonical = "\n".join([method.upper(), path, timestamp, nonce, body])
    signature = hmac.new(
        api_secret.encode(), canonical.encode(), hashlib.sha256
    ).hexdigest()
    return {
        "X-Api-Key": api_key,
        "X-Api-Timestamp": timestamp,
        "X-Api-Nonce": nonce,
        "X-Api-Signature": signature,
        "Content-Type": "application/json",
    }
```

All responses use this envelope:

```json
{ "ok": true, "data": {} }
```

Errors use `ok: false` and a stable `error.code`:

```json
{ "ok": false, "error": { "code": "order_not_found", "message": "The order does not exist." } }
```

## Products

### `GET /products`

Returns currently listed products and payment methods. Card contents and provider credentials are never included.

```json
{
  "ok": true,
  "data": {
    "products": [
      {
        "id": 12,
        "name": "Example product",
        "description": "Short description",
        "price": "9.90",
        "stock": 42,
        "type": "automatic",
        "max_quantity": 5,
        "requires_slot_activation_email": false,
        "requires_customer_accounts": false,
        "customer_account_max_length": null,
        "fulfillment_kind": "account",
        "wholesale_prices": [],
        "input_fields": []
      }
    ],
    "payment_methods": [
      { "id": 30, "code": "binancepay", "name": "币安支付", "method": 2, "client": 3 }
    ]
  }
}
```

For an activation product, `requires_slot_activation_email` is `true` and
`max_quantity` is `1`. Collect the customer's activation email and submit it as
the top-level `slot_activation_email` field when creating the order. For an account upgrade, `requires_customer_accounts` is `true`; collect one account identifier for each unit and apply the numeric `customer_account_max_length` limit.

### `GET /payment-methods`

Returns the same payment method list without product data. Scheduled payment pauses are applied. Personal keys also receive the `balance` method.

### `GET /account/balance`

Personal key only. Returns the account's available CNY balance, for example `{ "ok": true, "data": { "balance": "20.00", "currency": "CNY" } }`.

### `GET /account/orders`

Personal key only. Returns the 20 most recent orders belonging to this account.

## Orders

### `POST /orders`

Creates one order through the same pricing, coupon, stock, and expiry path as the web checkout. `Idempotency-Key` is required and must be reused when retrying a timed-out request.

Request fields:

| Field | Required | Description |
| --- | --- | --- |
| `product_id` | yes | Product id from `/products`. `gid` is accepted as a legacy alias. |
| `quantity` | yes | Positive integer. `by_amount` is accepted as a legacy alias. |
| `email` | owner key only | Delivery and notification address. A personal key always uses its account email. |
| `payment_method` | yes | Payment `code` or numeric `id`; personal keys can use `balance`. |
| `search_password` | owner key, depending on shop setting | Password for guest order lookup. Personal keys do not need it. |
| `coupon_code` | no | Coupon assigned to this product. For a personal key, an explicit code overrides saved coupons. |
| `slot_activation_email` | activation products only | Valid email of the account to activate; separate from the order notification `email`. For products with `requires_slot_activation_email: true`, set `quantity` to `1`. |
| `fulfillment_input` | account upgrades only | Use `{ "kind": "upgrade_account", "customer_accounts": ["account1", "account2"] }`. Each trimmed identifier must be nonempty, unique, single-line and within the product's `customer_account_max_length`; the array length must equal `quantity`. |
| `inputs` | no | Object containing manual-processing fields listed by the product. |

Example:

```http
POST /api/v1/orders
Idempotency-Key: order-cart-20260824-0001
```

```json
{
  "product_id": 12,
  "quantity": 1,
  "email": "customer@example.com",
  "payment_method": "binancepay",
  "search_password": "ORDER_PASSWORD",
  "inputs": {}
}
```

Personal balance payment example (first deposit at `/account` using the shop's WeChat Pay, Alipay, or Binance Pay checkout):

Personal keys can save multiple coupon codes at `/account`. If `coupon_code` is omitted or empty, the server chooses the eligible saved code that gives the largest discount for the selected product and quantity. Disabled, exhausted, and inapplicable codes are skipped. Only one code applies per order; the final `order.amount` and balance debit include the discount. Reusing an `Idempotency-Key` returns the original order and its original price, even if saved codes have changed since then.

```json
{
  "product_id": 12,
  "quantity": 1,
  "payment_method": "balance"
}
```

The order is bound to the personal key's account. The server calculates the actual price, checks the balance under a database lock, debits it once, and starts the normal delivery flow. Insufficient balance returns `422 validation_error` without creating an order. Save and reuse the `Idempotency-Key` when retrying; it prevents a duplicate purchase.

Response status is `201` for a new order and `200` when the same idempotency key replays the original result. For external payment methods, the response includes `data.payment.url`, which is the existing checkout page:

```json
{
  "ok": true,
  "data": {
    "replayed": false,
    "order": {
      "id": "ORDER_SN",
      "status": "wait_pay",
      "status_code": 1,
      "payment_received": false,
      "fulfilled": false,
      "quantity": 1,
      "amount": "9.90",
      "currency": "CNY",
      "expires_at": "2026-08-24T12:25:00+08:00"
    },
    "payment": {
      "required": true,
      "url": "https://shop.newzoe.cloud/pay-gateway/...",
      "method": "binancepay",
      "expires_at": "2026-08-24T12:25:00+08:00"
    }
  }
}
```

### `POST /orders/{order_id}/pay`

Returns a payment URL for an existing unpaid order. The optional JSON field `payment_method` can select another currently available channel. This endpoint only starts checkout; it does not mark an order paid.

```json
{ "payment_method": "binancepay" }
```

When `payment_method` is `binancepay`, this response also creates or reuses the
active collision-free quote and includes the verified receiving deep link for
QR rendering:

```json
{
  "payment_required": true,
  "payment": {
    "method": "binancepay",
    "url": "https://shop.newzoe.cloud/pay-gateway/...",
    "qr_payload": "https://app.binance.com/uni-qr/RECEIVE_CODE",
    "expected_usdt": "1.38",
    "currency": "USDT",
    "quote_expires_at": "2026-08-24T12:15:00+08:00"
  }
}
```

The Telegram bot renders `qr_payload` into an image and sends it in the chat;
it does not add a URL button for Binance. WeChat and Alipay continue to use the
normal `payment.url` button. The `POST /orders` response stays URL-only until
the integration explicitly opens `/pay`, so an unused order does not consume a
Binance quote window.

Payment callbacks from the configured provider call the same settlement service used by the browser checkout. A paid order returns `409 order_already_paid` from this endpoint.

Balance payment is selected at order creation, so a successful balance order is already paid and does not need `/pay`.

### `GET /orders/{order_id}`

Returns status, amount, payment method, transaction id, timestamps, and the live payment deadline. Personal keys can access only their own orders. Card contents are excluded; use `/delivery` after payment.

Status values are `wait_pay`, `pending`, `processing`, `completed`, `failure`, `expired`, and `abnormal`.

For activation products, `processing` means payment was received and activation
is still in progress. Poll this endpoint; `completed` means the supplier has
confirmed activation. If the status is `abnormal` or `failure`, contact the
shop rather than creating another paid order.

### `GET /orders/{order_id}/delivery`

Returns delivery state. Personal keys can access only their own orders. For an automatic order, `items` and `content` are present only after the order reaches `completed`. Manual orders stay `pending` until the back office finishes them.

For an activation product, the completed delivery content is an activation
confirmation, not account credentials; check the activation email for the
supplier's invitation or notification.

```json
{
  "ok": true,
  "data": {
    "delivery": {
      "available": true,
      "status": "completed",
      "type": "automatic",
      "items": ["CARD-CONTENT"],
      "content": "CARD-CONTENT"
    }
  }
}
```

### `POST /orders/{order_id}/deliver`

**Owner key only.** For a trusted payment integration, submits the provider's verified settlement and triggers the normal stock claim, automatic delivery, email, Telegram, and product-hook jobs. The exact order amount and a non-empty provider transaction id are required.

```json
{
  "amount": "9.90",
  "transaction_id": "PROVIDER_TRANSACTION_ID"
}
```

`amount_fen` can be used instead of `amount` for integer cents:

```json
{ "amount_fen": 990, "transaction_id": "PROVIDER_TRANSACTION_ID" }
```

This endpoint is intended for a server-side payment verifier. A client should use `/pay` and wait for the provider callback. Repeating the same transaction id and amount is idempotent; a different transaction id or amount is rejected. An expired unpaid order is not settled by this endpoint.

## Error codes

| HTTP | Code | Meaning |
| --- | --- | --- |
| 401 | `unauthorized` | API key is invalid. |
| 401 | `invalid_timestamp` | Request timestamp is outside the configured window. |
| 401 | `invalid_signature` | HMAC does not match the raw request. |
| 401 | `request_replayed` | Nonce has already been consumed. |
| 403 | `account_required` | A personal API key is required for account or balance operations. |
| 403 | `forbidden` | An owner-only endpoint was called with a personal key. |
| 409 | `idempotency_conflict` | Same idempotency key was used with another body. |
| 409 | `payment_method_unavailable` | Channel is closed or paused. |
| 409 | `order_already_paid` | The order has left `wait_pay`. |
| 410 | `order_expired` | Payment or settlement window has ended. |
| 422 | `validation_error` | Request fields failed validation. |
| 422 | `amount_mismatch` | Settlement amount differs from the order. |
| 404 | `order_not_found` | No order matches the supplied id. |

## Recommended flow

1. Call `GET /products` and choose a product and payment code.
2. Call `POST /orders` with a fresh `Idempotency-Key` and save `order.id`.
3. For `balance`, the order is paid immediately; otherwise redirect the customer to `data.payment.url`.
4. Poll `GET /orders/{order_id}` or wait for the configured payment callback.
5. When `status` is `completed`, call `GET /orders/{order_id}/delivery` and read the card items.
6. For a separate payment provider, verify its server callback and call `/deliver` exactly once with the exact amount and transaction id.
