time2pay Developer Docs

Direct flow

Direct deposit · host-to-host

Your backend drives every step of the payment and your own UI talks to the player's wallet.

How it works

The same payment as the hosted page, with you rendering it. Your backend opens a session and forwards each step the player takes; the response tells your frontend what to show next and, when it is time, what to ask the player's wallet to sign. The API secret stays on your server.

  1. Your backend
    Opens the session with POST /v1/direct/init and passes the first step to your frontend.
  2. Your frontend
    Renders the step: network, wallet, coin, amount. Sends the player's choice to your backend.
  3. Your backend
    Forwards it with POST /v1/direct/step and returns the next step.
  4. Player's wallet
    Signs the approval and the payment your frontend asks for, from the wallet_action in the step.
  5. Chain
    The payment is mined; POST /v1/direct/status shows the progress.
  6. Your backend
    Receives payment.completed or payment.failed and credits the player.
Every call is signed as described in Authentication. Start with the hosted page if you can: the settlement side is identical and you can move here later without changing your webhook handling or ledger.

Methods, in call order

All three are signed and called from your backend.

Direct · host-to-host

Your backend drives every step of the deposit and your frontend renders it and talks to the player's wallet. The API secret never reaches a browser.

POST /v1/direct/init signed

Open a deposit session

Starts a session and returns its first step. Everything in the body is optional, but sending external_order_id is what makes a retry safe.

Prefilled values are validated here, because the steps that would normally check them are the ones being skipped. With no prefill the session starts at network_select; with network at connect_wallet, and the coin picker follows once a wallet is connected; with both at connect_wallet and no picker; add amount and the player's only remaining action is connecting a wallet. See prefilling.

Request body

FieldTypeRequiredDescription
player_id string no Your player reference. Echoed back in the settlement webhook.
external_order_id string no Your order reference, and the idempotency key: repeating a create with the same reference and the same parameters returns the original session instead of opening a second one. Reusing it with different parameters is a conflict.
callback_url string (uri) no Per-session override of the webhook target configured for your merchant. Empty falls back to the merchant default.
amount string no Optional prefill in whole units, e.g. "125.50". Skips the enter_amount step.
network string no Optional prefill of the network, when you already know which one the player is paying on. Skips the network_select step.
token string no Optional prefill of the asset. Requires network; sending both starts the session at connect_wallet.
language string no The language the step views are written in, as an ISO 639-1 code. A region is ignored, so "en-GB" is English. Unsupported or missing falls back to English rather than failing the call. One of: en, ru, es, uk, kk, uz, ky, tg, az, hy, ka, tr, de, fr, it, pt, pl

Request

curl -X POST "$BASE_URL/v1/direct/init" \
  -H "Content-Type: application/json" \
  -H "X-Api-Key: $API_KEY_ID" \
  -H "X-Timestamp: $TS" \
  -H "X-Nonce: $NONCE" \
  -H "X-Signature: $SIG" \
  -d '{"player_id":"player-123","external_order_id":"deposit-1001","amount":"125.50","network":"eth","token":"USDT"}'
res, err := client.Call(ctx, "POST", "/v1/direct/init", `{
	"player_id": "player-123",
	"external_order_id": "deposit-1001",
	"amount": "125.50",
	"network": "eth",
	"token": "USDT"
}`)
$res = $client->call('POST', '/v1/direct/init', [
    'player_id' => 'player-123',
    'external_order_id' => 'deposit-1001',
    'amount' => '125.50',
    'network' => 'eth',
    'token' => 'USDT',
]);
const res = await client.call("POST", "/v1/direct/init", {
    "player_id": "player-123",
    "external_order_id": "deposit-1001",
    "amount": "125.50",
    "network": "eth",
    "token": "USDT"
});
res = client.call("POST", "/v1/direct/init", {
    "player_id": "player-123",
    "external_order_id": "deposit-1001",
    "amount": "125.50",
    "network": "eth",
    "token": "USDT",
})
const res = await client.call("POST", "/v1/direct/init", {
    "player_id": "player-123",
    "external_order_id": "deposit-1001",
    "amount": "125.50",
    "network": "eth",
    "token": "USDT"
});

The client is the one on Signing requests: it signs, sends, and turns an error into an exception carrying its code.

Response 200

The session's first step.

{
  "step": "connect_wallet",
  "session": "sess_9f2c1e",
  "components": [
    {
      "type": "heading",
      "text": "Connect a wallet"
    },
    {
      "type": "wallet_connect",
      "action": "wallet_connected"
    }
  ]
}

Errors

400 unsupported Malformed JSON, an unknown network or token, a token sent without a network, or an amount that is not a positive number. Codes: validation, unsupported.
{
  "error": {
    "code": "unsupported",
    "message": "unsupported token \"DAI\" on \"eth\""
  }
}
401 unauthorized The signature, key, timestamp or nonce did not check out: a missing header, an unknown key id, a timestamp more than 5 minutes from ours, a signature that does not match, or a nonce already used inside the window. Do not retry without rebuilding the request — a retry needs a new timestamp, a new nonce and a new signature.
{
  "error": {
    "code": "unauthorized",
    "message": "invalid signature"
  }
}
403 forbidden The credential is valid but the caller's IP is not in the allowlist configured for your merchant. Not retryable.
{
  "error": {
    "code": "forbidden",
    "message": "client IP not allowed for this merchant"
  }
}
409 conflict This external_order_id already belongs to a session created with different parameters. Repeating a create with identical parameters is safe and returns the original session; changing the amount, player or token under a reference you already used is not, and is refused rather than silently resolved.
{
  "error": {
    "code": "conflict",
    "message": "external_order_id \"deposit-1001\" already belongs to session sess_9f2c1e with different parameters"
  }
}
503 unavailable A dependency we need to answer safely is degraded, so the request was refused rather than served wrongly. Transient: retry with backoff, using a fresh timestamp, nonce and signature.
{
  "error": {
    "code": "unavailable",
    "message": "cannot verify request nonce"
  }
}
POST /v1/direct/step signed

Advance a deposit session

Submits the action the current step asked for and returns the next step. The action name and the shape of its value come from the step you are on — see the step machine.

Request body

FieldTypeRequiredDescription
session string yes Session id returned by init.
action string yes The action the current step expects, e.g. select_network.
value string no The action's value. Empty for actions that carry none, such as poll.

Request

curl -X POST "$BASE_URL/v1/direct/step" \
  -H "Content-Type: application/json" \
  -H "X-Api-Key: $API_KEY_ID" \
  -H "X-Timestamp: $TS" \
  -H "X-Nonce: $NONCE" \
  -H "X-Signature: $SIG" \
  -d '{"session":"sess_9f2c1e","action":"select_network","value":"eth"}'
res, err := client.Call(ctx, "POST", "/v1/direct/step", `{
	"session": "sess_9f2c1e",
	"action": "select_network",
	"value": "eth"
}`)
$res = $client->call('POST', '/v1/direct/step', [
    'session' => 'sess_9f2c1e',
    'action' => 'select_network',
    'value' => 'eth',
]);
const res = await client.call("POST", "/v1/direct/step", {
    "session": "sess_9f2c1e",
    "action": "select_network",
    "value": "eth"
});
res = client.call("POST", "/v1/direct/step", {
    "session": "sess_9f2c1e",
    "action": "select_network",
    "value": "eth",
})
const res = await client.call("POST", "/v1/direct/step", {
    "session": "sess_9f2c1e",
    "action": "select_network",
    "value": "eth"
});

The client is the one on Signing requests: it signs, sends, and turns an error into an exception carrying its code.

Response 200

The step the session moved to.

{
  "step": "awaiting_payment",
  "session": "sess_9f2c1e",
  "components": [
    {
      "type": "status",
      "status": "info",
      "text": "Sign the payment in your wallet."
    }
  ],
  "wallet_action": {
    "method": "eth_sendTransaction",
    "chain_id": "0xaa36a7",
    "params": [
      {
        "from": "0x…",
        "to": "0x…",
        "data": "0x…",
        "value": "0x0"
      }
    ]
  },
  "submit_action": "signature_submitted"
}

Errors

400 invalid_action An action that does not belong to the current step, a terminal session being advanced, a malformed value such as an address or transaction hash of the wrong shape, or a payer wallet that does not hold enough of the token to cover the deposit. Codes: validation, invalid_action, insufficient_funds, insufficient_allowance, tx_reverted.
{
  "error": {
    "code": "invalid_action",
    "message": "action \"submit_amount\" is not valid at step \"connect_wallet\""
  }
}
401 unauthorized The signature, key, timestamp or nonce did not check out: a missing header, an unknown key id, a timestamp more than 5 minutes from ours, a signature that does not match, or a nonce already used inside the window. Do not retry without rebuilding the request — a retry needs a new timestamp, a new nonce and a new signature.
{
  "error": {
    "code": "unauthorized",
    "message": "invalid signature"
  }
}
403 forbidden The credential is valid but the caller's IP is not in the allowlist configured for your merchant. Not retryable.
{
  "error": {
    "code": "forbidden",
    "message": "client IP not allowed for this merchant"
  }
}
404 not_found No such session for your merchant. Another merchant's session id is indistinguishable from one that does not exist.
{
  "error": {
    "code": "not_found",
    "message": "session not found"
  }
}
503 unavailable A dependency we need to answer safely is degraded, so the request was refused rather than served wrongly. Transient: retry with backoff, using a fresh timestamp, nonce and signature.
{
  "error": {
    "code": "unavailable",
    "message": "cannot verify request nonce"
  }
}
POST /v1/direct/status signed

Read the current step

Read-only and safe to poll while the chain listener settles in the background. Each poll is a separate signed request and therefore needs its own nonce.

Request body

FieldTypeRequiredDescription
session string yes

Request

curl -X POST "$BASE_URL/v1/direct/status" \
  -H "Content-Type: application/json" \
  -H "X-Api-Key: $API_KEY_ID" \
  -H "X-Timestamp: $TS" \
  -H "X-Nonce: $NONCE" \
  -H "X-Signature: $SIG" \
  -d '{"session":"sess_9f2c1e"}'
res, err := client.Call(ctx, "POST", "/v1/direct/status", `{
	"session": "sess_9f2c1e"
}`)
$res = $client->call('POST', '/v1/direct/status', [
    'session' => 'sess_9f2c1e',
]);
const res = await client.call("POST", "/v1/direct/status", {
    "session": "sess_9f2c1e"
});
res = client.call("POST", "/v1/direct/status", {
    "session": "sess_9f2c1e",
})
const res = await client.call("POST", "/v1/direct/status", {
    "session": "sess_9f2c1e"
});

The client is the one on Signing requests: it signs, sends, and turns an error into an exception carrying its code.

Response 200

Where the session stands now.

{
  "step": "processing",
  "session": "sess_9f2c1e",
  "components": [
    {
      "type": "status",
      "status": "info",
      "text": "Confirmations: 5 of 12"
    }
  ]
}

Errors

401 unauthorized The signature, key, timestamp or nonce did not check out: a missing header, an unknown key id, a timestamp more than 5 minutes from ours, a signature that does not match, or a nonce already used inside the window. Do not retry without rebuilding the request — a retry needs a new timestamp, a new nonce and a new signature.
{
  "error": {
    "code": "unauthorized",
    "message": "invalid signature"
  }
}
403 forbidden The credential is valid but the caller's IP is not in the allowlist configured for your merchant. Not retryable.
{
  "error": {
    "code": "forbidden",
    "message": "client IP not allowed for this merchant"
  }
}
404 not_found No such session for your merchant.
{
  "error": {
    "code": "not_found",
    "message": "session not found"
  }
}
503 unavailable A dependency we need to answer safely is degraded, so the request was refused rather than served wrongly. Transient: retry with backoff, using a fresh timestamp, nonce and signature.
{
  "error": {
    "code": "unavailable",
    "message": "cannot verify request nonce"
  }
}

Self-hosted

Your backend drives the session and your frontend renders it. Each step comes back as a small UI schema — headings, buttons, inputs — plus, when the player has to sign something, an opaque wallet_action you forward to their wallet untouched. The API secret never reaches a browser because every call goes through your own backend.

  1. Open a session with POST /v1/direct/init and remember its session against the player. Prefill what you already know and the matching steps are skipped.
  2. Render the step from components, and send the action it asks for to POST /v1/direct/step — through your backend, which adds the session id and the signature.
  3. Forward wallet actions to window.ethereum.request exactly as given, then submit the resulting transaction hash with the submit_action the step named.
  4. Poll with the poll action while the step is processing, and credit from the webhook.

Backend: open the session

body, _ := json.Marshal(map[string]string{
	"player_id":         player.ID,
	"external_order_id": order.ID,
	"network":           "eth",
})
step, err := client.Call(ctx, "POST", "/v1/direct/init", string(body))
if err != nil {
	return err
}
if err := saveCashierSession(ctx, player.ID, step["session"].(string)); err != nil {
	return err
}
return json.NewEncoder(w).Encode(step)
$step = $client->call('POST', '/v1/direct/init', [
    'player_id' => $playerId,
    'external_order_id' => $orderId,
    'network' => 'eth',
]);
$_SESSION['payment_session'] = $step['session'];
header('Content-Type: application/json');
echo json_encode($step);
const step = await client.call("POST", "/v1/direct/init", {
  player_id: playerId,
  external_order_id: orderId,
  network: "eth",
});
await saveCashierSession(playerId, step.session);
return Response.json(step);
step = client.call("POST", "/v1/direct/init", {
    "player_id": current_player_id(),
    "external_order_id": order_id,
    "network": "eth",
})
session["payment_session"] = step["session"]
return step
const step = await client.call("POST", "/v1/direct/init", {
  player_id: req.user.id,
  external_order_id: orderId,
  network: "eth",
});
req.session.paymentSession = step.session;
res.json(step);

Backend: proxy the steps

The browser never talks to us. It posts {action, value} to your backend, which looks up the player's session, signs the call and passes the step back. Pass our error code through so the page can word it.

func paymentStep(client *time2pay.Client, sessionOf func(r *http.Request) (string, error)) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		session, err := sessionOf(r)
		if err != nil {
			http.Error(w, "no open deposit", http.StatusNotFound)
			return
		}
		var in struct {
			Action string `json:"action"`
			Value  string `json:"value"`
		}
		if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
			http.Error(w, "bad request", http.StatusBadRequest)
			return
		}
		body, _ := json.Marshal(map[string]string{"session": session, "action": in.Action, "value": in.Value})
		step, err := client.Call(r.Context(), "POST", "/v1/direct/step", string(body))
		var apiErr *time2pay.Error
		if errors.As(err, &apiErr) {
			w.WriteHeader(apiErr.Status)
			_ = json.NewEncoder(w).Encode(map[string]any{"error": map[string]string{"code": apiErr.Code}})
			return
		}
		if err != nil {
			http.Error(w, "try again", http.StatusBadGateway)
			return
		}
		_ = json.NewEncoder(w).Encode(step)
	}
}
<?php

require __DIR__ . '/Time2payClient.php';

session_start();
$client = new Time2payClient(getenv('BASE_URL'), getenv('API_KEY_ID'), getenv('API_KEY_SECRET'));
$in = json_decode(file_get_contents('php://input'), true) ?? [];

header('Content-Type: application/json');
try {
    echo json_encode($client->call('POST', '/v1/direct/step', [
        'session' => $_SESSION['payment_session'],
        'action' => (string) ($in['action'] ?? ''),
        'value' => (string) ($in['value'] ?? ''),
    ]));
} catch (Time2payError $e) {
    http_response_code($e->status);
    echo json_encode(['error' => ['code' => $e->errorCode()]]);
}
export async function paymentStep(request, env, sessionOf) {
  const client = createClient({ baseUrl: env.BASE_URL, keyId: env.API_KEY_ID, secret: env.API_KEY_SECRET });
  const session = await sessionOf(request);
  const { action, value = "" } = await request.json();
  try {
    return Response.json(await client.call("POST", "/v1/direct/step", { session, action, value }));
  } catch (e) {
    if (!(e instanceof Time2payError)) return new Response("try again", { status: 502 });
    return Response.json({ error: { code: e.code } }, { status: e.status });
  }
}
@app.post("/payments/step")
def payment_step():
    body = request.get_json(force=True)
    try:
        return client.call("POST", "/v1/direct/step", {
            "session": session["payment_session"],
            "action": str(body.get("action", "")),
            "value": str(body.get("value", "")),
        })
    except Time2payError as e:
        return {"error": {"code": e.code}}, e.status
app.post("/payments/step", express.json(), async (req, res) => {
  try {
    res.json(await client.call("POST", "/v1/direct/step", {
      session: req.session.paymentSession,
      action: String(req.body.action ?? ""),
      value: String(req.body.value ?? ""),
    }));
  } catch (e) {
    if (!(e instanceof Time2payError)) return res.status(502).end();
    res.status(e.status).json({ error: { code: e.code } });
  }
});

Frontend: render and talk to the wallet

Plain browser JavaScript; render is yours — it draws components. The wallet request is forwarded exactly as the step gave it, including the chain switch when chain_id is set.

async function send(action, value = "") {
  const res = await fetch("/payments/step", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ action, value }),
  });
  return render(await res.json());
}

async function connectWallet() {
  const [address] = await window.ethereum.request({ method: "eth_requestAccounts" });
  return send("wallet_connected", address);
}

async function runWalletAction(step) {
  const { method, params, chain_id: chainId } = step.wallet_action;
  if (chainId) {
    await window.ethereum.request({ method: "wallet_switchEthereumChain", params: [{ chainId }] });
  }
  const txHash = await window.ethereum.request({ method, params });
  return send(step.submit_action, txHash);
}

The step machine

The wallet is asked for before the coin. Which coins are worth offering is a question about the player's wallet: token_select carries the balance the connected wallet holds in each one, and greys out the coins it cannot open a deposit with. Options on that step may therefore arrive with note, disabled and reason set — render a disabled option, do not drop it, or the player is told a coin you accept is unsupported.

A player may also send change_wallet (no value) from token_select, enter_amount or awaiting_approval to return to connect_wallet and pay from a different address. It is refused from awaiting_payment onwards, where the order is already bound to the wallet that approved it. A coin the player chose is re-chosen with the new wallet; a coin you prefilled is kept.

StepAction to sendValueMoves to
network_selectselect_networkthe value of the option the player pickedconnect_wallet
connect_walletwallet_connected0x + 40 hex charstoken_select, or straight past it when you prefilled token
token_selectselect_tokenthe value of the option the player pickedenter_amount, or awaiting_approval / awaiting_payment when the amount was prefilled
enter_amountsubmit_amountpositive decimalawaiting_approval, or awaiting_payment
awaiting_approvalapproval_submitted0x + 64 hex charsawaiting_payment
awaiting_paymentsignature_submitted0x + 64 hex charsprocessing
processingpollemptyprocessing, completed, failed, reverted
The approval step is skipped when it is not needed. Before asking for one we read the allowance the wallet has already granted the router; a player who approved enough in an earlier deposit goes straight to awaiting_payment. Never assume the step order — render whatever step the response names.
Wait for the approval transaction to be mined before sending the payment transaction. Otherwise transferFrom reverts, because the allowance is not visible on-chain yet — and approval_submitted is refused with tx_reverted or unavailable until the allowance is readable.

Terminal steps

completed, failed and reverted all end the session, and all three carry an order status of completed or failed — branch on the status, and use the step only to word the screen. reverted is a payment that was mined and rejected by the chain: the player's tokens never moved and only their gas was spent, which is the opposite of what a generic failure message implies.

Prefilling

network, token and amount are optional on both create calls and mean the same thing in each: when you already know what the player is depositing, the matching step is skipped and the session starts further along.

Prefilling token does more than skip a screen. The coin picker runs after the wallet connects and lists what that wallet holds, so a session without a prefilled token gives the player the coins they can actually pay with — and lets them pick a different one if they change wallets. Prefill the token only when the order really is denominated in it.

You sendSession starts at
nothingnetwork_select
networkconnect_wallet, then token_select
network + tokenconnect_wallet, and the coin picker is skipped
network + token + amountconnect_wallet, and the player is never asked for a coin or an amount

Prefilled values are validated when the session is created, because the steps that would normally check them are exactly the ones being skipped. An unknown network, a token that does not exist on that network, a token without a network, or an amount that is not a positive number are all rejected at create time rather than surfacing at settlement.

Deposit statuses

StatusSet byMeaning
pendingthe sessionCreated; no payment transaction submitted yet.
processingthe sessionPayment transaction submitted; waiting for confirmations.
completedthe chain listenerReached the required confirmation depth. This is when you credit.
failedthe chain listenerSettlement was unsuccessful.

Confirmation depth is amount-based: larger deposits wait for more blocks. The listener matches a payment by orderRef (which is keccak256(session_id)) and falls back to the transaction hash, so a deposit reconciles even if the browser never reported the hash.

Webhooks are the way to learn the outcome. If one never arrives — your endpoint was down through every retry — read the session with /v1/direct/status and credit from its status, deduplicating on external_order_id exactly as the webhook handler does.

Webhooks in this flow

Each is a POST to your callback URL, signed with your API key secret. Verify it as described in Verifying the signature, deduplicate on X-Idempotency-Key and answer any 2xx.

POST payment.completed no signature

A deposit settled

Sent to your callback URL when a deposit session reaches the required confirmation depth. Signed with your API key secret. Deduplicate on X-Idempotency-Key.

Body

{
  "event": "payment.completed",
  "session_id": "01J8ZQ7K4M2X9F3B6D0T5R8W1C",
  "merchant_id": "acme-shop",
  "player_id": "player-77421",
  "external_order_id": "ORD-2026-000188",
  "network": "eth",
  "token": "USDT",
  "amount": "250.000000",
  "status": "completed",
  "tx_hash": "0x9f2c4e1a7b3d5f8e0c6a2b4d7e9f1c3a5b7d9e1f2c4a6b8d0e2f4a6c8b0d2e4f",
  "order_ref": "a7f3c9d1",
  "occurred_at": "2026-08-05T12:41:07Z"
}

Response 200

Any 2xx marks the delivery successful. Anything else is retried with backoff: 30s, 1m, 2m … 1h, up to 8 attempts.

POST payment.failed no signature

A deposit failed

Sent to your callback URL when a deposit session ends without a valid payment. failure_code is one of abandoned, not_found, stuck, reverted or rejected; failure_reason is human-readable and may change. Do not credit the player. Signed with your API key secret. Deduplicate on X-Idempotency-Key.

Body

{
  "event": "payment.failed",
  "session_id": "01J8ZQ9D2F6H0K3M7P1S4V8Y5B",
  "merchant_id": "acme-shop",
  "player_id": "player-77421",
  "amount": "250.000000",
  "status": "failed",
  "failure_code": "abandoned",
  "failure_reason": "session expired before a payment was seen",
  "occurred_at": "2026-08-05T13:12:07Z"
}

Response 200

Any 2xx marks the delivery successful. Anything else is retried with backoff: 30s, 1m, 2m … 1h, up to 8 attempts.