otpwatch handler_api.php recipes
Get API key

Cancel and refund: where the money goes at each step

An order holds its price on your balance; it does not spend it. What happens next depends on one thing: whether an SMS reached the number. No SMS means the money comes back, either when you cancel or when the window runs out on its own. An SMS means the order is paid.

Get an API key Opens sign-up on SimAggregator, the marketplace this API belongs to. Key in the dashboard, balance in USD.

The life of an order

MomentYour callReplyMoney
order placedgetNumberACCESS_NUMBER:<id>:<number>price held on the balance
waitinggetStatusSTATUS_WAIT_CODEstill held
too early (the docs give no time)setStatus 8EARLY_CANCEL_DENIEDstill held; repeat the cancel later
no SMS, you cancelsetStatus 8ACCESS_CANCELhold released, back on the balance
no SMS, window endsnothingthe order is closed (STATUS_CANCEL or NO_ACTIVATION)released automatically
SMS arrivedgetStatusSTATUS_OK:<code>the hold becomes a payment
code workedsetStatus 6ACCESS_ACTIVATIONpaid, slot freed
need another codesetStatus 3ACCESS_RETRY_GETsame order, keep polling
cancel after the SMSsetStatus 8BAD_STATUScannot be cancelled

The activation window is set per service in the catalog and is currently one hour for every service.

Rules worth memorising

  • Refund means "no SMS". If a message reached the number, the order counts as delivered, even if the service then rejects the sign-up or your test fails. Check the number and the country before you trigger the SMS, not after.
  • A cancel can be refused as too early. The answer is EARLY_CANCEL_DENIED, which the API documentation describes as "too early to cancel, repeat the request later". It does not say how long, so repeat the cancel with a pause and stop after a fixed number of attempts.
  • Refunds land on the internal balance and can be spent on the next order right away. They are not sent back to a wallet.
  • Rentals have a tighter rule. A rental (duration d1, d3 or d7) can be cancelled with a refund only within the first hour after purchase and only before any SMS or call. After that it is paid in full. See renting a number.
  • A price refusal costs nothing. WRONG_MAX_PRICE or NO_NUMBERS means no order was placed and nothing was held.

Why cancel at all if refunds are automatic

Because an open order holds two things until it closes: its price on your balance and a slot in the account's limit of simultaneous orders. A test that gave up after two minutes but leaves the order open keeps both for the rest of the window. On a big parallel run that is how you hit NO_BALANCE or CHANNEL_LIMIT with money on the account.

There is also a quieter effect. The account's limit of simultaneous orders depends on its history, and the dashboard shows the share of orders that ended with a code over the last 7 days. Orders grabbed "just in case" and dropped push that share down. Order when the app is ready to send, and close what you open.

A cancel helper that handles EARLY_CANCEL_DENIED

cancel.mjs
// handler_api reference: https://otpwatch.com/cancel-and-refund
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/partner
const API = process.env.SMS_API_BASE_URL ?? "https://sim-aggregator.org/stubs/handler_api.php";
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

// Our choice, not an API rule: the docs only say "too early to cancel, repeat the request later".
const RETRY_EVERY_MS = 10_000;
const GIVE_UP_AFTER_MS = 120_000;

// Resolves with the final reply: ACCESS_CANCEL, BAD_STATUS (code already delivered), NO_ACTIVATION...
// Throws if the cancel is still EARLY_CANCEL_DENIED after giveUpAfterMs.
export async function cancel(apiKey, id, { giveUpAfterMs = GIVE_UP_AFTER_MS } = {}) {
  const deadline = Date.now() + giveUpAfterMs;
  for (;;) {
    const r = (await (await fetch(`${API}?action=setStatus&api_key=${apiKey}&id=${id}&status=8`)).text()).trim();
    if (r !== "EARLY_CANCEL_DENIED") return r;
    if (Date.now() + RETRY_EVERY_MS > deadline) {
      throw new Error(`cancel ${id}: still EARLY_CANCEL_DENIED after ${giveUpAfterMs / 1000} s; repeat it later`);
    }
    await sleep(RETRY_EVERY_MS);                           // too early to cancel: repeat later
  }
}
cancel.py
# handler_api reference: https://otpwatch.com/cancel-and-refund
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/partner
import os
import time

import requests

API = os.getenv("SMS_API_BASE_URL", "https://sim-aggregator.org/stubs/handler_api.php")

# Our choice, not an API rule: the docs only say "too early to cancel, repeat the request later".
RETRY_EVERY_S = 10
GIVE_UP_AFTER_S = 120


def cancel(api_key: str, activation_id: str, give_up_after_s: float = GIVE_UP_AFTER_S) -> str:
    """Final reply: ACCESS_CANCEL, BAD_STATUS, NO_ACTIVATION... Raises if still too early."""
    deadline = time.monotonic() + give_up_after_s
    while True:
        reply = requests.get(API, params={"action": "setStatus", "api_key": api_key,
                                          "id": activation_id, "status": 8}, timeout=30).text.strip()
        if reply != "EARLY_CANCEL_DENIED":
            return reply
        if time.monotonic() + RETRY_EVERY_S > deadline:
            raise RuntimeError(f"cancel {activation_id}: still EARLY_CANCEL_DENIED "
                               f"after {give_up_after_s:g} s; repeat it later")
        time.sleep(RETRY_EVERY_S)  # too early to cancel: repeat later

The first cancel goes out at once. The API documentation names no wait for EARLY_CANCEL_DENIED, so the 10-second pause and the two-minute cap are this helper's settings, not limits of the platform: change them to fit your teardown budget. When the helper gives up, log the id and cancel it later, for example from the cleanup job on the CI page.

Reconciling money per order

If you keep your own ledger, one row per activation with these columns matches the platform's rules:

ledger
# handler_api reference: https://otpwatch.com/cancel-and-refund
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/partner
activation_id | ordered_at | price_held | outcome   | charged
12345         | 10:02:11   | 1.38       | code      | 1.38
12346         | 10:04:40   | 1.38       | cancelled | 0.00
12347         | 10:05:02   | 1.38       | expired   | 0.00

outcome comes from the last reply you saw: STATUS_OK means code, ACCESS_CANCEL means cancelled, STATUS_CANCEL without a code means expired. Every balance movement (top-up, payment, refund) also appears as a separate line in the dashboard's transaction history, filterable by direction and date.

Checklist for test suites

  • Order at the step right before the app sends the SMS, not in setup.
  • Close every order in teardown: 6 if the code was read, 8 otherwise.
  • Teardown must handle EARLY_CANCEL_DENIED (retry with a pause, then give up loudly); give it its own timeout.
  • No whole-test retries for tests that order numbers.
  • A cleanup job after the run cancels anything the key still has open; the CI page has one.

ready to run it?

Cancel what you do not need, finish what you used, and the balance stays honest.

Get an API key

Install for your coding agent

terminal
# Agent skills index: https://otpwatch.com/.well-known/agent-skills/index.json
npx skills add https://otpwatch.com

Two skills: receiving an SMS code in your own app or test, and building a bot that sells numbers. Index: /.well-known/agent-skills/index.json

Updated