Source: https://cryptanio.com/ja/docs/reference/simulate/
Contract / release / updated: v1 / 1.1.3 5 / 2026-11-17

[API リファレンス](https://cryptanio.com/ja/docs.html#reference)

# Sandbox決済をシミュレーション

POST `/v1/simulate`

契約 v1 / 1.1.3 5 / 2026-11-17

[Markdown](https://cryptanio.com/ja/docs/reference/simulate/index.md) [OpenAPI](https://cryptanio.com/openapi.json)

書き込み可能なテストキーとsimulation権限で決済シナリオを実行します。Idempotency-Keyが必要です。同一の再試行では状態変更や送信を重ねず保存結果を返します。同じキーで異なるパラメーターを送ると409です。データ、受信先、枠、残高はLiveと分離されます。ブロックチェーン取引は作成しません。expireとlateをサポートし、Payとサブスクリプションは対象外です。

キー権限：`simulation` / write。

## パラメーター

| パラメーター | 入金 | 必須 | 説明 |
| --- | --- | --- | --- |
| `Idempotency-Key` | header | はい | 16–80文字のASCII英数字、ハイフン、アンダースコア。再試行では同じキーと正確な本文を維持してください。別の状態変更には新しいキーを使います。; `string` minLength: `16`; maxLength: `80`; pattern: `^[A-Za-z0-9_-]+$` |

## リクエスト本文

| フィールド | 型 | 必須 | 説明 |
| --- | --- | --- | --- |
| `operation_id` | `string` | いいえ | 本文に含める任意のIdempotency-Keyのコピー。ヘッダーと完全一致する必要があります。ヘッダーだけの使用を推奨します。; minLength: `16`; maxLength: `80`; pattern: `^[A-Za-z0-9_-]+$` |
| `invoice_id` | `string` | いいえ | キーのアカウントと許可されたプロジェクトに属するSandbox請求書。invoice_idかwatch_idのどちらか一方を指定します。; minLength: `1` |
| `watch_id` | `string` | いいえ | キーのアカウントと許可されたプロジェクト・サービスに属する有効なSandboxアドレス。対象を一つだけ指定します。; minLength: `1` |
| `transaction_id` | `string` | いいえ | 新しいテスト決済では省略します。返されたsimulated_識別子を同じ決済の次の状態変更で使います。不明な識別子は404となり、資産と金額は変更できません。; pattern: `^simulated_[0-9]+$` |
| `event_type` | `string` | いいえ | テストトランザクションの状態変更。同じtransaction_idを確定または取り消してライフサイクルを検証します。; `payment.pending`, `payment.confirmed`, `payment.rolled_back`; 既定値: `payment.confirmed` |
| `amount_raw` | `string` | いいえ | 資産の最小単位で表した正の整数金額。既定値は請求書金額、既存トランザクション金額、または新しいアドレス決済ではカタログ資産の一単位です。別の追加支払いには新規トランザクションを使います。; minLength: `1`; maxLength: `78`; pattern: `^[0-9]+$` |
| `asset` | `string` | いいえ | 請求書の資産は固定です。複数の資産ルールがあるアドレスでは、許可されたカタログ資産を明示的に選択してください。不明なトークンの精度は推測できません。 |
| `decimals` | `integer` | いいえ | 任意の整合性確認値。請求書またはカタログで固定された資産精度と一致する必要があり、精度自体は変更しません。; minimum: `0`; maximum: `255` |
| `occurred_at` | `string` | いいえ | 任意のイベント時刻。現在の30日前から7日と1分後まで指定できます。他のオブジェクトやシステム時刻は変更しません。lateは専用の時刻を設定します。; `date-time` |
| `action` | `string` | いいえ | 請求書専用のシナリオです。expireはイベントやWebhookを作らず、対象請求書を期限切れ処理します。lateは期限切れ処理後、その一秒後の確定決済をシミュレーションします。invoice_statusは通常の受付ルールに従い、lateは特定の状態を保証しません。; `expire`, `late` |



### application/json

```json
{
  "invoice_id": "2001",
  "event_type": "payment.pending",
  "amount_raw": "1000000"
}
```



## リクエスト例

サンプルはお客様のアカウントで実際の操作を行います。コードで指定された環境変数を設定してください。キーは秘密に保管します。書き込みリクエストは自動再試行されません。



### Shell / cURL

```bash
#!/usr/bin/env bash
set -euo pipefail
: "${CRYPTANIO_API_KEY:?Set CRYPTANIO_API_KEY}"
: "${CRYPTANIO_OPERATION_ID:?Set CRYPTANIO_OPERATION_ID}"
response_file="$(mktemp)"
trap 'rm -f "$response_file"' EXIT
transfer_status=0
http_status="$(curl \
  --silent --show-error --max-time 30 --request POST \
  --header "Authorization: Bearer $CRYPTANIO_API_KEY" \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --header "Idempotency-Key: $CRYPTANIO_OPERATION_ID" \
  --data-binary '{"invoice_id":"2001","event_type":"payment.pending","amount_raw":"1000000"}' \
  "https://api.cryptanio.com/v1/simulate" \
  --output "$response_file" --write-out '%{http_code}')" || transfer_status=$?
if [[ "$http_status" == 2?? ]]; then
  cat "$response_file"
  exit "$transfer_status"
fi
printf 'HTTP %s\n' "$http_status" >&2
cat "$response_file" >&2
exit 1
```



[サンプルをダウンロード](https://cryptanio.com/files/examples/api/simulate.sh)



### Go

```go
// Go; standard library only. Run: go run request.go
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "time"
)

func env(name string) string {
    value := os.Getenv(name)
    if value == "" { fmt.Fprintln(os.Stderr, "Set", name); os.Exit(1) }
    return value
}
func run() error {
    path := "/v1/simulate"

    endpoint, err := url.Parse("https://api.cryptanio.com" + path)
    if err != nil { return err }
    query := endpoint.Query()

    endpoint.RawQuery = query.Encode()
    var payload map[string]any
    if err := json.Unmarshal([]byte("{\"invoice_id\":\"2001\",\"event_type\":\"payment.pending\",\"amount_raw\":\"1000000\"}"), &payload); err != nil { return err }

    body, err := json.Marshal(payload)
    if err != nil { return err }
    request, err := http.NewRequest("POST", endpoint.String(), bytes.NewReader(body))
    if err != nil { return err }
    request.Header.Set("Authorization", "Bearer " + env("CRYPTANIO_API_KEY"))
    request.Header.Set("Accept", "application/json")
    request.Header.Set("Content-Type", "application/json")
    request.Header.Set("Idempotency-Key", env("CRYPTANIO_OPERATION_ID"))
    client := &http.Client{Timeout: 30 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
    response, err := client.Do(request)
    if err != nil { return err }
    defer response.Body.Close()
    if response.StatusCode < 200 || response.StatusCode >= 300 {
        body, err := io.ReadAll(response.Body)
        if err != nil { return err }
        return fmt.Errorf("HTTP %d: %s", response.StatusCode, body)
    }
    _, err = io.Copy(os.Stdout, response.Body)
    return err
}
func main() {
    if err := run(); err != nil { fmt.Fprintln(os.Stderr, err); os.Exit(1) }
}
```



[サンプルをダウンロード](https://cryptanio.com/files/examples/api/simulate.go)



### Rust

```rust
// Cargo.toml dependencies:
// reqwest = { version = "=0.12.24", features = ["blocking", "json"] }
// serde_json = "=1.0.145"
use std::{error::Error, io, time::Duration};
use reqwest::{blocking::Client, redirect::Policy, Method, Url};

fn env(name: &str) -> Result<String, Box<dyn Error>> {
    let value = std::env::var(name)?;
    if value.is_empty() { return Err(format!("Set {name}").into()); }
    Ok(value)
}
fn run() -> Result<(), Box<dyn Error>> {
    let mut url = Url::parse("https://api.cryptanio.com")?;
    {
        let mut segments = url.path_segments_mut().map_err(|_| "Invalid base URL")?;
        segments.clear();
        segments.push("v1");
        segments.push("simulate");
    }
    let client = Client::builder().timeout(Duration::from_secs(30)).redirect(Policy::none()).build()?;
    let request = client.request(Method::POST, url)
        .header("Authorization", format!("Bearer {}", env("CRYPTANIO_API_KEY")?))
        .header("Accept", "application/json".to_owned())
        .header("Content-Type", "application/json".to_owned())
        .header("Idempotency-Key", env("CRYPTANIO_OPERATION_ID")?);
    let mut body: serde_json::Value = serde_json::from_str("{\"invoice_id\":\"2001\",\"event_type\":\"payment.pending\",\"amount_raw\":\"1000000\"}")?;

    let request = request.json(&body);
    let mut response = request.send()?;
    let status = response.status();
    if !status.is_success() { return Err(format!("HTTP {}: {}", status.as_u16(), response.text()?).into()); }
    io::copy(&mut response, &mut io::stdout())?;
    Ok(())
}
fn main() {
    if let Err(error) = run() { eprintln!("{error}"); std::process::exit(1); }
}
```



[サンプルをダウンロード](https://cryptanio.com/files/examples/api/simulate.rs)



### PHP

```php
<?php
// PHP 8 with the cURL extension. Run this on your server.
function env(string $name): string {
    $value = getenv($name);
    if ($value === false || $value === '') throw new RuntimeException('Set ' . $name);
    return $value;
}
try {
    $path = '/v1/simulate';

    $query = [

    ];
    $url = 'https://api.cryptanio.com' . $path . ($query ? '?' . http_build_query($query, '', '&', PHP_QUERY_RFC3986) : '');
    $headers = [
        'Authorization: ' . 'Bearer ' . env('CRYPTANIO_API_KEY'),
        'Accept: ' . 'application/json',
        'Content-Type: ' . 'application/json',
        'Idempotency-Key: ' . env('CRYPTANIO_OPERATION_ID'),
    ];
    $body = json_decode('{"invoice_id":"2001","event_type":"payment.pending","amount_raw":"1000000"}', true, 512, JSON_THROW_ON_ERROR);

    $curl = curl_init($url);
    curl_setopt_array($curl, [
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => false,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_POSTFIELDS => json_encode($body, JSON_THROW_ON_ERROR),
    ]);
    $response = curl_exec($curl);
    if ($response === false) throw new RuntimeException(curl_error($curl));
    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    if ($status < 200 || $status >= 300) throw new RuntimeException('HTTP ' . $status . ': ' . $response);
    echo $response;
} catch (Throwable $error) {
    fwrite(STDERR, $error->getMessage() . PHP_EOL);
    exit(1);
}
```



[サンプルをダウンロード](https://cryptanio.com/files/examples/api/simulate.php)



### Python

```python
# Python 3; standard library only.
import json
import os
import sys
from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlencode
from urllib.request import HTTPRedirectHandler, Request, build_opener

def env(name):
    result = os.environ.get(name)
    if not result:
        raise ValueError("Set " + name)
    return result

class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None

try:
    path = "/v1/simulate"

    query = {

    }
    url = "https://api.cryptanio.com" + path + ("?" + urlencode(query) if query else "")
    headers = {
        "Authorization": "Bearer " + env("CRYPTANIO_API_KEY"),
        "Accept": "application/json",
        "Content-Type": "application/json",
        "Idempotency-Key": env("CRYPTANIO_OPERATION_ID"),
    }
    body = json.loads("{\"invoice_id\":\"2001\",\"event_type\":\"payment.pending\",\"amount_raw\":\"1000000\"}")

    data = json.dumps(body).encode("utf-8")
    request = Request(url, data=data, headers=headers, method="POST")
    with build_opener(NoRedirect()).open(request, timeout=30) as response:
        if not 200 <= response.status < 300:
            raise ValueError("HTTP " + str(response.status))
        sys.stdout.buffer.write(response.read())
except HTTPError as error:
    print("HTTP " + str(error.code) + ": " + error.read().decode("utf-8", errors="replace"), file=sys.stderr)
    sys.exit(1)
except (ValueError, URLError, OSError) as error:
    print(str(error), file=sys.stderr)
    sys.exit(1)
```



[サンプルをダウンロード](https://cryptanio.com/files/examples/api/simulate.py)



### Node.js

```javascript
// Node.js 18+. Run on your server, never in a browser.
const env = name => {
  const result = process.env[name];
  if (!result) throw new Error(`Set ${name}`);
  return result;
};
try {
  let path = "/v1/simulate";

  const url = new URL(path, "https://api.cryptanio.com");

  const headers = {
    "Authorization": "Bearer " + env("CRYPTANIO_API_KEY"),
    "Accept": "application/json",
    "Content-Type": "application/json",
    "Idempotency-Key": env("CRYPTANIO_OPERATION_ID"),
  };
  const body = {
    "invoice_id": "2001",
    "event_type": "payment.pending",
    "amount_raw": "1000000"
  };

  const response = await fetch(url, {
    method: "POST", headers, redirect: "manual",
    signal: AbortSignal.timeout(30_000), body: JSON.stringify(body),
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
  if (response.body) {
    for await (const chunk of response.body) process.stdout.write(chunk);
  }
} catch (error) {
  console.error(error.message);
  process.exitCode = 1;
}
```



[サンプルをダウンロード](https://cryptanio.com/files/examples/api/simulate.mjs)

## 応答とエラー

### 202 シナリオを受け付けたか、同一再試行の保存結果を返しました。

| フィールド | 型 | 必須 | 説明 |
| --- | --- | --- | --- |
| `event_id` | `string` | いいえ | 記録されたイベントID。イベントを作らないexpireでは省略されます。 |
| `event_type` | `string` | いいえ | 記録された決済の状態変更。expireでは省略されます。 |
| `watch_id` | `string` | はい | このシナリオで使うSandboxアドレス。 |
| `transaction_id` | `string` | いいえ | 次の状態変更にも使う安定したテスト決済ID。expireでは省略されます。 |
| `invoice_id` | `string` | いいえ | 請求書を対象にしたシナリオで変更されたSandbox請求書。 |
| `invoice_status` | `string` | いいえ | 操作後の実際の請求書状態。期限後や期限切れという結果を決めつけないでください。 |
| `action` | `string` | いいえ | 明示的に指定された請求書シナリオ。; `expire`, `late` |
| `queued` | `boolean` | はい | イベント通知の処理をキューに登録しました。外部送信の受け付け完了を意味しません。 |
| `replayed` | `boolean` | はい | 新たな状態変更やイベントなしに同一の冪等操作の結果を返した場合は真。 |



### 202 application/json

```json
{
  "event_id": "2301",
  "event_type": "payment.pending",
  "watch_id": "2000",
  "transaction_id": "simulated_2300",
  "invoice_id": "2001",
  "invoice_status": "pending",
  "queued": true,
  "replayed": false
}
```



### 400 無効なリクエスト（bad_request、unsupported_asset）。

| フィールド | 型 | 必須 | 説明 |
| --- | --- | --- | --- |
| `error` | `object` | はい |  |



### 400 application/json

```json
{
  "error": {
    "code": "forbidden",
    "message": "this API key is read-only"
  }
}
```



### 401 有効で使用可能な API キーがありません（unauthorized）。

| フィールド | 型 | 必須 | 説明 |
| --- | --- | --- | --- |
| `error` | `object` | はい |  |



### 401 application/json

```json
{
  "error": {
    "code": "forbidden",
    "message": "this API key is read-only"
  }
}
```



### 403 キーが操作、プロジェクト、サービス、IP を許可していないか、メールアドレスが未確認です。

| フィールド | 型 | 必須 | 説明 |
| --- | --- | --- | --- |
| `error` | `object` | はい |  |



### 403 application/json

```json
{
  "error": {
    "code": "forbidden",
    "message": "this API key is read-only"
  }
}
```



### 404 キーのアクセス範囲にオブジェクトが見つかりません（not_found）。

| フィールド | 型 | 必須 | 説明 |
| --- | --- | --- | --- |
| `error` | `object` | はい |  |



### 404 application/json

```json
{
  "error": {
    "code": "forbidden",
    "message": "this API key is read-only"
  }
}
```



### 409 状態の競合、再試行パラメーターの不一致、または支払いリソースの上限（conflict、limit_reached、service_inactive）。

| フィールド | 型 | 必須 | 説明 |
| --- | --- | --- | --- |
| `error` | `object` | はい |  |



### 409 application/json

```json
{
  "error": {
    "code": "forbidden",
    "message": "this API key is read-only"
  }
}
```



### 429 リクエストが多すぎます（rate_limited）。Retry-After の後に再試行してください。

| フィールド | 型 | 必須 | 説明 |
| --- | --- | --- | --- |
| `error` | `object` | はい |  |



### 429 application/json

```json
{
  "error": {
    "code": "forbidden",
    "message": "this API key is read-only"
  }
}
```



### 500 内部エラー（internal）。

| フィールド | 型 | 必須 | 説明 |
| --- | --- | --- | --- |
| `error` | `object` | はい |  |



### 500 application/json

```json
{
  "error": {
    "code": "forbidden",
    "message": "this API key is read-only"
  }
}
```



### 503 一時的に利用できません（unavailable）。バックオフを設けて再試行してください。

| フィールド | 型 | 必須 | 説明 |
| --- | --- | --- | --- |
| `error` | `object` | はい |  |



### 503 application/json

```json
{
  "error": {
    "code": "forbidden",
    "message": "this API key is read-only"
  }
}
```



[エラー処理と安全な再試行](https://cryptanio.com/ja/docs.html#errors)

## 入れ子のオブジェクト

### `SimulateRequest`

| フィールド | 型 | 必須 | 説明 |
| --- | --- | --- | --- |
| `operation_id` | `string` | いいえ | 本文に含める任意のIdempotency-Keyのコピー。ヘッダーと完全一致する必要があります。ヘッダーだけの使用を推奨します。; minLength: `16`; maxLength: `80`; pattern: `^[A-Za-z0-9_-]+$` |
| `invoice_id` | `string` | いいえ | キーのアカウントと許可されたプロジェクトに属するSandbox請求書。invoice_idかwatch_idのどちらか一方を指定します。; minLength: `1` |
| `watch_id` | `string` | いいえ | キーのアカウントと許可されたプロジェクト・サービスに属する有効なSandboxアドレス。対象を一つだけ指定します。; minLength: `1` |
| `transaction_id` | `string` | いいえ | 新しいテスト決済では省略します。返されたsimulated_識別子を同じ決済の次の状態変更で使います。不明な識別子は404となり、資産と金額は変更できません。; pattern: `^simulated_[0-9]+$` |
| `event_type` | `string` | いいえ | テストトランザクションの状態変更。同じtransaction_idを確定または取り消してライフサイクルを検証します。; `payment.pending`, `payment.confirmed`, `payment.rolled_back`; 既定値: `payment.confirmed` |
| `amount_raw` | `string` | いいえ | 資産の最小単位で表した正の整数金額。既定値は請求書金額、既存トランザクション金額、または新しいアドレス決済ではカタログ資産の一単位です。別の追加支払いには新規トランザクションを使います。; minLength: `1`; maxLength: `78`; pattern: `^[0-9]+$` |
| `asset` | `string` | いいえ | 請求書の資産は固定です。複数の資産ルールがあるアドレスでは、許可されたカタログ資産を明示的に選択してください。不明なトークンの精度は推測できません。 |
| `decimals` | `integer` | いいえ | 任意の整合性確認値。請求書またはカタログで固定された資産精度と一致する必要があり、精度自体は変更しません。; minimum: `0`; maximum: `255` |
| `occurred_at` | `string` | いいえ | 任意のイベント時刻。現在の30日前から7日と1分後まで指定できます。他のオブジェクトやシステム時刻は変更しません。lateは専用の時刻を設定します。; `date-time` |
| `action` | `string` | いいえ | 請求書専用のシナリオです。expireはイベントやWebhookを作らず、対象請求書を期限切れ処理します。lateは期限切れ処理後、その一秒後の確定決済をシミュレーションします。invoice_statusは通常の受付ルールに従い、lateは特定の状態を保証しません。; `expire`, `late` |

### `Simulation`

| フィールド | 型 | 必須 | 説明 |
| --- | --- | --- | --- |
| `event_id` | `string` | いいえ | 記録されたイベントID。イベントを作らないexpireでは省略されます。 |
| `event_type` | `string` | いいえ | 記録された決済の状態変更。expireでは省略されます。 |
| `watch_id` | `string` | はい | このシナリオで使うSandboxアドレス。 |
| `transaction_id` | `string` | いいえ | 次の状態変更にも使う安定したテスト決済ID。expireでは省略されます。 |
| `invoice_id` | `string` | いいえ | 請求書を対象にしたシナリオで変更されたSandbox請求書。 |
| `invoice_status` | `string` | いいえ | 操作後の実際の請求書状態。期限後や期限切れという結果を決めつけないでください。 |
| `action` | `string` | いいえ | 明示的に指定された請求書シナリオ。; `expire`, `late` |
| `queued` | `boolean` | はい | イベント通知の処理をキューに登録しました。外部送信の受け付け完了を意味しません。 |
| `replayed` | `boolean` | はい | 新たな状態変更やイベントなしに同一の冪等操作の結果を返した場合は真。 |

### `Error`

| フィールド | 型 | 必須 | 説明 |
| --- | --- | --- | --- |
| `error` | `object` | はい |  |
