# SMS verification in CI without surprises on the bill

> A scheduled pipeline is where SMS tests go wrong quietly: retries buy extra numbers, a crashed job leaves orders open, a price change doubles the cost of the nightly run. Three small pieces prevent all of it: a preflight that checks before buying, maxPrice on every order, and a cleanup step that runs on failure.

Source: https://otpwatch.com/ci-sms-verification
Updated: 2026-11-24
API key: https://otpwatch.com/agent/key

## A key for CI only

Issue a separate named key in the dashboard, call it `ci`, and store it as a repository or environment secret right away: the key string is shown once. A dedicated key gives you three things:

- the 600-requests-per-minute limit is per key, so a busy pipeline cannot slow down a production bot;
- the cleanup step can cancel everything this key left open without touching anyone's manual orders;
- the key's last-used date in the dashboard tells you whether the schedule actually ran.

All keys of an account share one balance and one pool of simultaneous orders, so a separate key is not a separate budget. The preflight below is the budget.

## The workflow

```env title=".env.example"
# handler_api reference: https://otpwatch.com/ci-sms-verification
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
SMS_API_BASE_URL=https://sim-aggregator.org/stubs/handler_api.php
# Key from the SimAggregator dashboard: https://otpwatch.com/agent/key
SMS_API_KEY=
```

```yaml title=".github/workflows/sms-e2e.yml"
# handler_api reference: https://otpwatch.com/ci-sms-verification
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
name: sms-e2e
on:
  workflow_dispatch:
  schedule:
    - cron: "30 3 * * 1-5"   # weekdays 03:30 UTC

concurrency:
  group: sms-e2e             # never two paid runs at once
  cancel-in-progress: false

jobs:
  sms:
    runs-on: ubuntu-latest
    timeout-minutes: 25
    environment: staging      # require approval or branch rules here if you like
    env:
      SMS_API_KEY: ${{ secrets.SMS_API_KEY }}
      SMS_SERVICE: tg
      SMS_COUNTRY: "16"
      SMS_MAX_PRICE: "2.00"
      SMS_TESTS: "4"          # how many tests in the @sms group
      BASE_URL: https://staging.example.com
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - name: Preflight (key, price, balance)
        run: node scripts/sms-preflight.mjs
      - run: npx playwright install --with-deps chromium
      - name: SMS tests
        run: npx playwright test --project=sms --workers=2 --retries=0
      - name: Cancel anything left open
        if: always()
        run: node scripts/sms-release.mjs
      - uses: actions/upload-artifact@v4
        if: failure()
        with:
          name: playwright-report
          path: playwright-report
```

The tests themselves are the ones from the [Playwright page](https://otpwatch.com/playwright-otp-testing.md); the same steps work for Cypress or pytest with a different test command.

## Preflight: refuse to start a run you cannot afford

```js title="scripts/sms-preflight.mjs"
// handler_api reference: https://otpwatch.com/ci-sms-verification
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
// Exits non-zero before any purchase if the key, the price or the balance is off.
const API = process.env.SMS_API_BASE_URL ?? "https://sim-aggregator.org/stubs/handler_api.php";
const { SMS_API_KEY: key, SMS_SERVICE = "tg", SMS_COUNTRY = "16", SMS_MAX_PRICE = "2", SMS_TESTS = "1" } = process.env;
const get = async (q) => (await (await fetch(`${API}?api_key=${encodeURIComponent(key ?? "")}&${q}`)).text()).trim();
const die = (msg) => { console.error(`preflight: ${msg}`); process.exit(1); };

const bal = await get("action=getBalance");
if (!bal.startsWith("ACCESS_BALANCE:")) die(`key rejected or API error: ${bal}`);
const balance = Number(bal.slice("ACCESS_BALANCE:".length));

const raw = await get(`action=getPrices&country=${SMS_COUNTRY}&service=${SMS_SERVICE}`);
if (!raw.startsWith("{")) die(`getPrices refused: ${raw}`);
const p = JSON.parse(raw)[SMS_COUNTRY]?.[SMS_SERVICE];
if (!p || p.count < Number(SMS_TESTS)) die(`not enough free numbers for ${SMS_SERVICE}/${SMS_COUNTRY} right now`);
if (p.cost > Number(SMS_MAX_PRICE)) die(`price ${p.cost} is above SMS_MAX_PRICE ${SMS_MAX_PRICE}`);

const budget = Number(SMS_MAX_PRICE) * Number(SMS_TESTS);
if (balance < budget) die(`balance ${balance} is below the run budget ${budget.toFixed(2)}`);
console.log(`preflight ok: balance ${balance}, ${SMS_SERVICE}/${SMS_COUNTRY} at ${p.cost}, budget ${budget.toFixed(2)}`);
```

`getPrices` and `getBalance` order nothing and hold nothing, so the preflight is free apart from two requests. It budgets at `SMS_MAX_PRICE` rather than the current price, because every test sends that cap with its order and the cap is the most a test can cost.

## Cleanup: cancel what the key left open

```js title="scripts/sms-release.mjs"
// handler_api reference: https://otpwatch.com/ci-sms-verification
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
// Cancels every activation of this key that is still waiting for a code.
const API = process.env.SMS_API_BASE_URL ?? "https://sim-aggregator.org/stubs/handler_api.php";
const key = encodeURIComponent(process.env.SMS_API_KEY ?? "");
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const get = async (q) => (await (await fetch(`${API}?api_key=${key}&${q}`)).text()).trim();
// Our choice, not an API rule: the docs only say "too early to cancel, repeat the request later".
const CANCEL_TRIES = 9;
const CANCEL_PAUSE_MS = 10_000;

const list = await get("action=getCurrentActivationsList");
const open = list.startsWith("[") ? JSON.parse(list).filter((a) => a.status === 0) : [];
for (const a of open) {
  let r = "";
  for (let i = 0; i < CANCEL_TRIES; i++) {
    r = await get(`action=setStatus&id=${a.numberid}&status=8`);
    if (r !== "EARLY_CANCEL_DENIED") break;
    if (i < CANCEL_TRIES - 1) await sleep(CANCEL_PAUSE_MS); // too early to cancel: repeat later
  }
  if (r === "EARLY_CANCEL_DENIED") {
    console.error(`${a.numberid}: still EARLY_CANCEL_DENIED after ${CANCEL_TRIES} tries; cancel it later`);
    process.exitCode = 1;
  } else console.log(`${a.numberid}: ${r}`);
}
console.log(`released ${open.length} open activation(s)`);
```

With `if: always()` it runs after failures and after a cancelled workflow run. The per-test teardown in the fixtures already closes orders; this step catches the cases where the runner died before teardown.

## Where the cost cap really lives

Three layers, each cheap:

1. **maxPrice on every order.** The order is refused with `WRONG_MAX_PRICE:<lowest price>` instead of being bought at a higher price. Nothing is charged.
2. **The preflight** refuses to start if `SMS_MAX_PRICE × SMS_TESTS` exceeds the balance.
3. **`retries=0` and `concurrency`** stop the two classic multipliers: a retry buys a second number, and an overlapping scheduled run buys a second set.

For the default pair in this workflow, Telegram in the United Kingdom, the "from" price was $1.3798 on 24 Nov 2026. [Price control](https://otpwatch.com/price-control.md) has starting caps for other pairs.

## GitLab CI

```yaml title=".gitlab-ci.yml"
# handler_api reference: https://otpwatch.com/ci-sms-verification
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
sms-e2e:
  image: mcr.microsoft.com/playwright:v1.49.0-noble
  rules:
    - if: $CI_PIPELINE_SOURCE == "schedule"
  resource_group: sms-e2e        # one paid run at a time
  timeout: 25m
  variables:
    SMS_SERVICE: tg
    SMS_COUNTRY: "16"
    SMS_MAX_PRICE: "2.00"
    SMS_TESTS: "4"
  script:
    - npm ci
    - node scripts/sms-preflight.mjs
    - npx playwright test --project=sms --workers=2 --retries=0
  after_script:
    - node scripts/sms-release.mjs
```

Add `SMS_API_KEY` under Settings → CI/CD → Variables as masked and protected. `after_script` runs even when `script` fails. Match the image tag to the Playwright version in your package.json.

## Polling budget for parallel jobs

Every worker polling `getStatus` every 3 seconds spends 20 requests a minute. Two workers on a matrix of three jobs is 120 a minute, comfortable. Twenty workers each holding a number is 400 a minute before orders and cancels, close to the 600 limit. The fix is fewer workers for the paid group, not a faster poll; [migrate by base URL](https://otpwatch.com/migrate-base-url.md#4-request-budget) has the formula.
