API reference

Simulate a Sandbox payment

POST/v1/simulate

Contract v1 / 1.1.3 5 / 2026-11-17

On this page

Run a payment scenario with a test write key and simulation scope. Requires Idempotency-Key; an identical retry returns the stored result without another payment transition or delivery. Reusing the key with different parameters returns 409. Data, recipients, quotas and balances remain separate from Live. No blockchain transaction is created. Supported invoice actions are expire and late; Pay checkout and subscriptions are excluded.

Key permissions: simulation / write.

Parameters

ParameterInRequiredDescription
Idempotency-KeyheaderYes16–80 ASCII letters, digits, dashes or underscores. Keep the same key and exact request when retrying this scenario. Use a new key for each distinct transaction transition.
string minLength: 16; maxLength: 80; pattern: ^[A-Za-z0-9_-]+$

Request body

FieldTypeRequiredDescription
operation_idstringNoOptional body copy of Idempotency-Key; when present it must exactly match the header. Prefer the header alone.
minLength: 16; maxLength: 80; pattern: ^[A-Za-z0-9_-]+$
invoice_idstringNoA Sandbox invoice owned by the key account and allowed project. Supply exactly one of invoice_id or watch_id.
minLength: 1
watch_idstringNoAn active Sandbox address owned by the key account and allowed project/service. Supply exactly one target.
minLength: 1
transaction_idstringNoOmit for a new test payment. Reuse the returned simulated_ identifier for later transitions of that payment. Unknown identifiers return 404; asset and amount cannot change.
pattern: ^simulated_[0-9]+$
event_typestringNoTransition of the test transaction. Confirm and roll back the same transaction_id to exercise its lifecycle.
payment.pending, payment.confirmed, payment.rolled_back; Default: payment.confirmed
amount_rawstringNoPositive integer amount in the asset smallest units. Defaults to the invoice amount, the existing transaction amount, or one whole catalogue asset for a new watch payment. Use a new transaction for a separate partial payment.
minLength: 1; maxLength: 78; pattern: ^[0-9]+$
assetstringNoInvoice asset is frozen. For a watch with multiple asset rules, select an allowed catalogue asset explicitly. Unknown token precision cannot be inferred.
decimalsintegerNoOptional consistency assertion; must equal the frozen invoice or catalogue asset precision. It does not override precision.
minimum: 0; maximum: 255
occurred_atstringNoOptional event time, from 30 days before now through 7 days and 1 minute after now. Does not change other objects or system time. The late action sets its own time.
date-time
actionstringNoInvoice-only scenario. expire advances this invoice through its expiry logic without an event or webhook. late expires this invoice and simulates a confirmed payment one second after its expiry. The returned invoice_status follows normal payment and acceptance rules; late does not promise a particular status.
expire, late
application/json
{
  "invoice_id": "2001",
  "event_type": "payment.pending",
  "amount_raw": "1000000"
}

Request examples

Examples perform a real operation in your account. Set the environment variables named in the code. Keep your key private; write requests are not retried automatically.

Shell / cURL
#!/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
Download example
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) }
}
Download example
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); }
}
Download example
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);
}
Download example
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)
Download example
Node.js
// 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;
}
Download example

Responses and errors

202 Scenario accepted, or the stored result of an identical retry.
FieldTypeRequiredDescription
event_idstringNoRecorded event ID. Omitted for expire, which does not create an event.
event_typestringNoRecorded payment transition; omitted for expire.
watch_idstringYesSandbox address used by this scenario.
transaction_idstringNoStable test payment identifier for later transitions; omitted for expire.
invoice_idstringNoAffected Sandbox invoice, when the scenario targets an invoice.
invoice_statusstringNoActual invoice status after the operation; never infer a fixed late or expired outcome.
actionstringNoExplicit invoice scenario, when requested.
expire, late
queuedbooleanYesEvent notification processing was queued. It does not prove an external delivery was accepted.
replayedbooleanYesTrue when the same idempotent operation was returned without another transition or event.
202 application/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 Invalid request (bad_request, unsupported_asset).
FieldTypeRequiredDescription
errorobjectYes
400 application/json
{
  "error": {
    "code": "forbidden",
    "message": "this API key is read-only"
  }
}
401 No valid active API key (unauthorized).
FieldTypeRequiredDescription
errorobjectYes
401 application/json
{
  "error": {
    "code": "forbidden",
    "message": "this API key is read-only"
  }
}
403 Key disallows the operation, project, service or IP; email unconfirmed.
FieldTypeRequiredDescription
errorobjectYes
403 application/json
{
  "error": {
    "code": "forbidden",
    "message": "this API key is read-only"
  }
}
404 Object not found within the key's scope (not_found).
FieldTypeRequiredDescription
errorobjectYes
404 application/json
{
  "error": {
    "code": "forbidden",
    "message": "this API key is read-only"
  }
}
409 State conflict, conflicting retry parameters, or payment resource limit (conflict, limit_reached, service_inactive).
FieldTypeRequiredDescription
errorobjectYes
409 application/json
{
  "error": {
    "code": "forbidden",
    "message": "this API key is read-only"
  }
}
429 Too many requests (rate_limited); retry after Retry-After.
FieldTypeRequiredDescription
errorobjectYes
429 application/json
{
  "error": {
    "code": "forbidden",
    "message": "this API key is read-only"
  }
}
500 Internal error (internal).
FieldTypeRequiredDescription
errorobjectYes
500 application/json
{
  "error": {
    "code": "forbidden",
    "message": "this API key is read-only"
  }
}
503 Temporary unavailability (unavailable); retry with backoff.
FieldTypeRequiredDescription
errorobjectYes
503 application/json
{
  "error": {
    "code": "forbidden",
    "message": "this API key is read-only"
  }
}

Handling errors and retrying safely

Nested objects

SimulateRequest

FieldTypeRequiredDescription
operation_idstringNoOptional body copy of Idempotency-Key; when present it must exactly match the header. Prefer the header alone.
minLength: 16; maxLength: 80; pattern: ^[A-Za-z0-9_-]+$
invoice_idstringNoA Sandbox invoice owned by the key account and allowed project. Supply exactly one of invoice_id or watch_id.
minLength: 1
watch_idstringNoAn active Sandbox address owned by the key account and allowed project/service. Supply exactly one target.
minLength: 1
transaction_idstringNoOmit for a new test payment. Reuse the returned simulated_ identifier for later transitions of that payment. Unknown identifiers return 404; asset and amount cannot change.
pattern: ^simulated_[0-9]+$
event_typestringNoTransition of the test transaction. Confirm and roll back the same transaction_id to exercise its lifecycle.
payment.pending, payment.confirmed, payment.rolled_back; Default: payment.confirmed
amount_rawstringNoPositive integer amount in the asset smallest units. Defaults to the invoice amount, the existing transaction amount, or one whole catalogue asset for a new watch payment. Use a new transaction for a separate partial payment.
minLength: 1; maxLength: 78; pattern: ^[0-9]+$
assetstringNoInvoice asset is frozen. For a watch with multiple asset rules, select an allowed catalogue asset explicitly. Unknown token precision cannot be inferred.
decimalsintegerNoOptional consistency assertion; must equal the frozen invoice or catalogue asset precision. It does not override precision.
minimum: 0; maximum: 255
occurred_atstringNoOptional event time, from 30 days before now through 7 days and 1 minute after now. Does not change other objects or system time. The late action sets its own time.
date-time
actionstringNoInvoice-only scenario. expire advances this invoice through its expiry logic without an event or webhook. late expires this invoice and simulates a confirmed payment one second after its expiry. The returned invoice_status follows normal payment and acceptance rules; late does not promise a particular status.
expire, late
Simulation

FieldTypeRequiredDescription
event_idstringNoRecorded event ID. Omitted for expire, which does not create an event.
event_typestringNoRecorded payment transition; omitted for expire.
watch_idstringYesSandbox address used by this scenario.
transaction_idstringNoStable test payment identifier for later transitions; omitted for expire.
invoice_idstringNoAffected Sandbox invoice, when the scenario targets an invoice.
invoice_statusstringNoActual invoice status after the operation; never infer a fixed late or expired outcome.
actionstringNoExplicit invoice scenario, when requested.
expire, late
queuedbooleanYesEvent notification processing was queued. It does not prove an external delivery was accepted.
replayedbooleanYesTrue when the same idempotent operation was returned without another transition or event.
Error

FieldTypeRequiredDescription
errorobjectYes