# 余额购买

`POST /account/api/v1/orders/create`

## 授权

`Authorization: Bearer YOUR_ARNPROXY_API_KEY`

`Accept: application/json`

所需权限: `purchases`

`Content-Type: application/json`

`Idempotency-Key` · 16–100 个字母、数字、_ 或 -。保存并对同一操作重复使用相同值。

## 参数

| 名称 | 类型 | 必填 / 条件必填 | 默认值 | 说明 |
|---|---|---|---|---|
| `Idempotency-Key` (header) | string | 必填 | — | 16–100 个字母/数字/_/-。操作及状态查询使用同一值，不可用于不同请求体。 |
| `product_id` (body) | integer | 必填 | — | products 返回的产品 ID，1–2147483647。 |
| `lines` (body) | object[] | 必填 | — | 同一产品的 1–20 条不同位置行；location_id 不可重复，代理总数最多 100000。 |
| `lines[].location_id` (body) | integer | 必填 | — | 所选产品目录中的位置 ID。 |
| `lines[].time_id` (body) | integer | 必填 | — | 此位置提供的租期 ID。 |
| `lines[].quantity` (body) | integer | 必填 | — | 1–100000；同时受 product.minimum_quantity 限制。 |
| `lines[].purpose_id` (body) | integer | 必填 | — | 当前用途流程请发送 201。 |
| `lines[].subpurpose_id` (body) | integer | 必填 | — | 201 下的有效子用途，其他用途使用 -1。 |
| `lines[].other_purpose` (body) | string | 条件必填 | — | subpurpose_id=-1 时必填，1–30 个 UTF-8 字符；其他情况忽略。 |
| `currency` (body) | string | 必填 | — | 同一报价中的 TRY 或 USD，必须与账户币种一致。 |
| `expected_total_minor` (body) | integer | 必填 | — | 同一报价中的 total_minor，必须为整数，不能用小数金额或字符串。范围 1–999999999999。 |
| `terms` (body) | boolean | 必填 | — | 明确确认必须发送 JSON 布尔值 true，不能发送字符串 "true"。 |
| `promo_code` (body) | string | 可选 | `""` | 可选优惠码，最多 100 字节。报价与购买/续期时必须保持相同。 |
| `auth` (body) | object | 可选 | — | 交付认证，默认为 {"mode":"username_password"}。不会授予主凭据管理权限。 |
| `auth.mode` (body) | string | 条件必填 | — | 提供 auth 时必须填写 username_password 或 ip；不要在此指定用户名/密码。 |
| `auth.ip` (body) | string | 条件必填 | — | 仅 auth.mode=ip 时需要 IPv4；username_password 时省略。 |

## 请求体

请用相应目录、报价或范围中的值替换 YOUR_/FROM_。示例中的确认值为 false；只有明确同意真实操作时才确认。

```json
{
  "product_id": "FROM_PRODUCTS",
  "lines": [
    {
      "location_id": "FROM_CATALOG",
      "time_id": "FROM_CATALOG",
      "quantity": 1,
      "purpose_id": 201,
      "subpurpose_id": "FROM_CATALOG_CHILDREN"
    }
  ],
  "currency": "FROM_QUOTE",
  "expected_total_minor": "FROM_QUOTE_TOTAL_MINOR",
  "promo_code": "",
  "terms": false
}
```

## 更多使用示例

ID 和价格仅供示例，请使用目录及同一次报价中的实际值。JSON ID 和 expected_total_minor 必须是数字。示例刻意保留 terms=false；只有客户明确同意实际付费操作后才应发送 terms=true。

### 同一产品类型的两个国家

一个 product_id 下最多可包含 20 个不同的 location_id。每个国家生成独立订单，关联结账按一张发票处理。数量折扣按每个国家自己的数量计算。

```json
{
  "product_id": 5,
  "lines": [
    {
      "location_id": 10,
      "time_id": 101,
      "quantity": 1,
      "purpose_id": 201,
      "subpurpose_id": 202
    },
    {
      "location_id": 11,
      "time_id": 102,
      "quantity": 1,
      "purpose_id": 201,
      "subpurpose_id": 202
    }
  ],
  "currency": "TRY",
  "expected_total_minor": 2000,
  "promo_code": "",
  "terms": false
}
```

### “其他”用途

选择“其他”时，发送 subpurpose_id=-1 和包含 1–30 个字符的 other_purpose。其他选项无需 other_purpose。purpose_id 仍为 201。

```json
{
  "product_id": 5,
  "lines": [
    {
      "location_id": 10,
      "time_id": 101,
      "quantity": 1,
      "purpose_id": 201,
      "subpurpose_id": -1,
      "other_purpose": "Custom purpose"
    }
  ],
  "currency": "TRY",
  "expected_total_minor": 1000,
  "promo_code": "",
  "terms": false
}
```

## 请求示例

### curl

```curl
printf 'Authorization: Bearer %s\n' "$ARNPROXY_API_KEY" |
  curl --silent --show-error --header @- \
    --header 'Accept: application/json' \
    --connect-timeout 10 --max-time 30 \
    --header 'Idempotency-Key: YOUR_SAVED_OPERATION_KEY' \
    --request POST --header 'Content-Type: application/json' \
    --data-binary @request.json \
    'https://www.arnproxy.com/account/api/v1/orders/create'
```

### python

```python
import os, requests

headers = {"Authorization": "Bearer " + os.environ["ARNPROXY_API_KEY"]}
headers["Idempotency-Key"] = "YOUR_SAVED_OPERATION_KEY"
import json
with open("request.json", encoding="utf-8") as f:
    payload = json.load(f)
response = requests.post(
    "https://www.arnproxy.com/account/api/v1/orders/create",
    headers=headers, json=payload,
    timeout=(10, 30), allow_redirects=False
)
print(response.status_code, response.text)
# No automatic write retry.
```

### javascript

```javascript
const headers = { Authorization: `Bearer ${process.env.ARNPROXY_API_KEY}` };
headers['Idempotency-Key'] = 'YOUR_SAVED_OPERATION_KEY';
const { readFile } = await import('node:fs/promises');
headers['Content-Type'] = 'application/json';
const body = await readFile('request.json', 'utf8');
const response = await fetch("https://www.arnproxy.com/account/api/v1/orders/create", {
  method: 'POST', headers, redirect: 'error',
  signal: AbortSignal.timeout(30000), body
});
console.log(response.status, await response.text());
// A write timeout is ambiguous; query its saved operation.
```

### php

```php
<?php
$headers = ['Accept: application/json',
    'Authorization: Bearer '.getenv('ARNPROXY_API_KEY')];
$headers[] = 'Idempotency-Key: YOUR_SAVED_OPERATION_KEY';
$headers[] = 'Content-Type: application/json';
$ch = curl_init('https://www.arnproxy.com/account/api/v1/orders/create');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2,
    CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_TIMEOUT => 30,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => file_get_contents('request.json'),
]);
$result = curl_exec($ch);
if ($result === false) {
    // Do not repeat a write; use the original operation key.
    throw new RuntimeException('Transport result unknown');
}
echo curl_getinfo($ch, CURLINFO_HTTP_CODE).PHP_EOL.$result;
curl_close($ch);
```

### go

```go
package main

import (
  "fmt"
  "io"
  "net/http"
  "os"
  "time"
)

func main() {
  client := &http.Client{Timeout: 30*time.Second,
    CheckRedirect: func(req *http.Request, via []*http.Request) error {
      return http.ErrUseLastResponse
    }}
  var body io.Reader
  file, err := os.Open("request.json"); if err != nil { panic(err) }
  defer file.Close(); body = file
  req, err := http.NewRequest("POST", "https://www.arnproxy.com/account/api/v1/orders/create", body)
  if err != nil { panic(err) }
  req.Header.Set("Authorization", "Bearer "+os.Getenv("ARNPROXY_API_KEY"))
  req.Header.Set("Idempotency-Key", "YOUR_SAVED_OPERATION_KEY")
  req.Header.Set("Content-Type", "application/json")
  res, err := client.Do(req); if err != nil { panic(err) }
  defer res.Body.Close()
  data, err := io.ReadAll(res.Body); if err != nil { panic(err) }
  fmt.Println(res.StatusCode, string(data))
}
```

### csharp

```csharp
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

using var handler = new HttpClientHandler { AllowAutoRedirect = false };
using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(30) };
using var request = new HttpRequestMessage(HttpMethod.Post,
    "https://www.arnproxy.com/account/api/v1/orders/create");
request.Headers.Authorization = new AuthenticationHeaderValue(
    "Bearer", Environment.GetEnvironmentVariable("ARNPROXY_API_KEY"));
request.Headers.Add("Idempotency-Key", "YOUR_SAVED_OPERATION_KEY");
request.Content = new StringContent(
    await File.ReadAllTextAsync("request.json"), Encoding.UTF8, "application/json");
using var response = await client.SendAsync(request);
Console.WriteLine((int)response.StatusCode);
Console.WriteLine(await response.Content.ReadAsStringAsync());
// Never automatically retry an ambiguous write.
```

### java

```java
import java.net.URI;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;

// Inside your application method:
var client = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder(URI.create("https://www.arnproxy.com/account/api/v1/orders/create"))
    .header("Authorization", "Bearer " + System.getenv("ARNPROXY_API_KEY"))
    .header("Accept", "application/json")
    .header("Idempotency-Key", System.getenv("ARNPROXY_OPERATION_KEY"))
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString(
        Files.readString(Path.of("request.json"), StandardCharsets.UTF_8)))
    .build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
```

## 响应 · HTTP 201, 200

```json
{
  "ok": true,
  "data": {
    "state": "accepted",
    "delivery_state_at_acceptance": "queued",
    "currency": "TRY",
    "total": "10.00",
    "total_minor": 1000,
    "checkout_group_id": null,
    "orders": [
      {
        "id": 10001,
        "number": "1000010001",
        "location_id": 10,
        "time_id": 101,
        "quantity": 1,
        "total": "10.00"
      }
    ],
    "accepted_at": "2030-01-01T12:00:00+00:00",
    "automatic_renewal": false,
    "replayed": false
  },
  "meta": {
    "request_id": "000000000000000000000001",
    "phase": "public_v1",
    "source": "arnproxy_records"
  }
}
```

| 名称 | 类型 | 条件必填 | 说明 |
|---|---|---|---|
| `ok` | boolean | — | 成功标志；为 false 时请检查 error.code。 |
| `data` | object | — | 操作特定结果；示例均为演示用合成数据。 |
| `data.state` | string | — | 记录/操作状态。accepted 不表示已交付，completed 不表示连接测试成功。 |
| `data.delivery_state_at_acceptance` | string | — | delivery state at acceptance 的操作特定值。请保留返回类型并查阅行为说明。 |
| `data.currency` | string | — | 账户交易币种：TRY 或 USD。 |
| `data.total` | string | — | 金额；为避免精度损失，请保留返回的字符串/整数类型。 |
| `data.total_minor` | integer | — | 最小货币单位整数：1000 表示 10.00 TRY/USD。 |
| `data.checkout_group_id` | integer|null | — | checkout group id 的操作特定值。请保留返回类型并查阅行为说明。 |
| `data.orders` | array | — | orders 的操作特定值。请保留返回类型并查阅行为说明。 |
| `data.orders[]` | object | — | orders 的操作特定值。请保留返回类型并查阅行为说明。 |
| `data.orders[].id` | integer | — | 相关 ARNPROXY 记录 ID，请勿替换为上游内部 ID。 |
| `data.orders[].number` | string | — | 显示订单号，不能替代要求 id 的字段。 |
| `data.orders[].location_id` | integer | — | 本地目录的位置或产品类型 ID。 |
| `data.orders[].time_id` | integer | — | 本地租期/GB 方案记录 ID，不是天数或 GB 数量。 |
| `data.orders[].quantity` | integer | — | 所选或订购的代理数量。 |
| `data.orders[].total` | string | — | 金额；为避免精度损失，请保留返回的字符串/整数类型。 |
| `data.accepted_at` | string | — | API 返回格式的时间戳；示例日期为合成数据。 |
| `data.automatic_renewal` | boolean | — | automatic renewal 的操作特定值。请保留返回类型并查阅行为说明。 |
| `data.replayed` | boolean | — | 返回同一操作已保存的结果，不代表发生新的扣款或操作。 |
| `meta` | object | — | 请求关联与数据来源元信息。 |
| `meta.request_id` | string | — | 此 HTTP 请求的跟踪 ID，不是操作键或订单 ID。 |
| `meta.phase` | string | — | phase 的操作特定值。请保留返回类型并查阅行为说明。 |
| `meta.source` | string | — | 数据来源；本地记录与实时上游查询属于不同证据。 |

## 行为与重要说明

- 从 products/catalog 获取 ID。quote 行仅含 location_id、time_id、quantity。purchase 行还必须有 purpose_id=201 和所选 subpurpose_id。
- 多国购买生成独立订单和一张多行发票，折扣按国家计算。accepted 不表示已交付，请跟踪 order_delivery 和 order_proxies。
- 超时/5xx 不能证明写操作失败。请使用原始 Idempotency-Key 查询状态，不要换新键重试；GET 不会重发更改。
- 标准订单不应让客户选择两次。请在 catalog.purposes 中找到 id=201，并仅展示其 children。purchase 中的 purpose_id 固定为整数 201，subpurpose_id 为所选子项的 ID。保留层级结构是为了兼容现有集成。
- 选择“其他”时，发送 subpurpose_id=-1 和包含 1–30 个字符的 other_purpose。其他选项无需 other_purpose。purpose_id 仍为 201。
- 一个 product_id 下最多可包含 20 个不同的 location_id。每个国家生成独立订单，关联结账按一张发票处理。数量折扣按每个国家自己的数量计算。

身份验证和参数校验可能在执行前拒绝请求。请查阅错误参考，联系支持时保留 request_id。切勿发送密钥或密码。

[错误与限制](https://docs.arnproxy.com/zh/api-v1/errors)

[跟踪同一操作: 查询购买状态](https://docs.arnproxy.com/zh/api-v1/orders/create/status)
