Authentication
Send Authorization: Bearer KEY from your server. Create keys in your signed-in Website and API page. Secrets are shown once.


Base path /api/v1. Bearer key, scoped, never in a browser.
Send Authorization: Bearer KEY from your server. Create keys in your signed-in Website and API page. Secrets are shown once.
Each key lists explicit scopes. The version is v1; new capabilities never authorize existing keys.
60 requests per minute per key and 300 per minute aggregate per owner.
Inbox, wallet and media are private. Do not render them on public pages or hand them to browsers.
A paid request is accepted only when all of this holds:
Paid work may return an operation id. Poll GET /api/v1/operations/{id} with operations:read. Pending or uncertain results need reconciliation, never resubmission.
Failures return { "error": { "code", "message" } }. Branch on code.
| Status | Meaning |
|---|---|
400 | Invalid or unbounded input. |
401 | Missing, invalid, expired or revoked key. |
402 | Insufficient prepaid balance or frozen wallet. |
403 | Key lacks the scope, or browser use is denied. |
404 | Resource not found for your account or unsupported route. |
409 | Blocked prerequisite, price-version mismatch, maximum-charge conflict or idempotency conflict. |
429 | Per-key 60/min or owner 300/min limit reached. Retry-After is returned. |
503 | Service temporarily unavailable. Do not assume a paid operation failed. |
Run only on your backend. Store BIZGO_API_BASE_URL and BIZGO_API_KEY in server-side environment variables. Do not expose the key or private inbox/wallet data in a website response. Authenticate and rate-limit your own website endpoint; BizGo keys do not authenticate your visitors.
Opt-in resumable imports: importPrivateCollection is inactive until explicitly called on a customer backend for numbers, communications, media or usage with the existing read scope. Pass a private checkpoint { cursor: null, complete: false } for a new import, a durable processPage callback, and optionally saveCheckpoint. Persist the whole checkpoint by owner and endpoint only after every record in the page is safely stored; upsert by record ID because interruptions or checkpoint-write failures can replay a page. The returned cursor is the continuation after the last fully processed and checkpointed page, not a per-record cursor. Never expose keys, checkpoints or imported records in browser storage, logs, public pages or analytics. Only complete: true means the import reached the end; save that flag too so a completed import does not start again. page_budget means resume from the returned checkpoint in another explicit invocation. rate_limited preserves the cursor and returns retryAfterSeconds (Retry-After seconds or HTTP date; fallback 60 seconds): wait at least that long before explicitly resuming, never reset the cursor or busy-loop. restart_required means 400 INVALID_CURSOR: do not wait or retry the same token; explicitly start a new checkpoint after reviewing owner/endpoint identity or secret rotation, retaining duplicate-safe imports. Other request, processing or malformed-page failures stop with complete: false and the prior checkpoint; inspect and fix the cause before resuming. The helper never automatically retries or restarts, changes permissions, invokes providers or submits paid operations. Collections are not snapshots; a completed pass does not include newer inserts, and records removed or expired during interruption may no longer be available.
// Node.js backend or serverless runtime. Never browser JavaScript.
// Concurrent imports: use the private fenced compareAndSwapCheckpoint adapter,
// not an unconditional saveCheckpoint. checkpoint_conflict requires explicit
// reload of the current owner's endpoint checkpoint, not automatic retry.
// stopped means cancellation retained the last completely committed page.
const base = process.env.BIZGO_API_BASE_URL; // approved https://<host>/api/v1
const key = process.env.BIZGO_API_KEY; // <YOUR_BIZGO_CUSTOMER_KEY>
if (!base || !key) throw new Error("Missing server configuration");
async function request(path, method = "GET", body, idempotencyKey, withHeaders = false, signal) {
const response = await fetch(base + path, {
method,
headers: {
Authorization: "Bearer " + key,
...(body ? { "Content-Type": "application/json" } : {}),
...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
},
...(body ? { body: JSON.stringify(body) } : {}),
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(20000)]) : AbortSignal.timeout(20000),
});
const data = await response.json().catch(error => {
if (response.ok) throw error;
return {};
});
if (!response.ok) {
// CAPABILITY_BLOCKED means prerequisites remain incomplete. Never bypass them.
throw Object.assign(new Error(data.error?.message || "Request failed"), {
code: data.error?.code, status: response.status,
retryAfter: response.headers.get("Retry-After"),
});
}
return withHeaders ? { data, headers: response.headers } : data;
}
// No charge, no provider requests, no private content.
const checkConnection = () => request("/connection");
const capabilities = () => request("/capabilities");
const prices = () => request("/prices"); // prices:read, no spending authorization
// Opt-in private page iterator: defining/importing it makes no requests.
// processPage must durably upsert by record ID; a failed page can be replayed.
// saveCheckpoint is optional, private server storage scoped to owner + endpoint.
// Save the WHOLE checkpoint, including complete, not just the cursor.
// Concurrent workers must use compareAndSwapCheckpoint(expected, updated).
// The private adapter must atomically compare BOTH fields, scoped to the same
// authenticated owner + endpoint, and return false on conflict. Never implement
// it as a read followed by an unconditional write, or retry a conflict blindly.
// Prefer a revision/fencing token in the backing store to prevent ABA updates.
// For example, bind owner/path/revision in a server-side closure around a single
// transactional UPDATE ... WHERE owner=? AND endpoint=? AND revision=?.
// A lease adapter must reject stale fencing tokens even after its lease expires.
// signal cancels reads but never interrupts processPage/checkpoint commit midway.
async function importPrivateCollection(path, processPage, {
checkpoint = { cursor: null, complete: false }, saveCheckpoint,
compareAndSwapCheckpoint, signal, limit = 50, maxPages = 100,
} = {}) {
if (!["/numbers", "/communications", "/media", "/usage"].includes(path) ||
!Number.isInteger(limit) || limit < 1 || limit > 50 ||
!Number.isInteger(maxPages) || maxPages < 1 ||
typeof processPage !== "function" ||
(saveCheckpoint !== undefined && typeof saveCheckpoint !== "function") ||
(compareAndSwapCheckpoint !== undefined && typeof compareAndSwapCheckpoint !== "function") ||
(saveCheckpoint && compareAndSwapCheckpoint) ||
typeof checkpoint.complete !== "boolean" ||
!(checkpoint.cursor === null || (typeof checkpoint.cursor === "string" &&
checkpoint.cursor.length > 0 && checkpoint.cursor.length <= 1024))) {
throw new Error("Invalid private import configuration");
}
let cursor = checkpoint.cursor;
if (checkpoint.complete) return { cursor, complete: true, reason: "complete" };
const seen = new Set(cursor ? [cursor] : []);
for (let page = 0; page < maxPages; page++) {
if (signal?.aborted) return { cursor, complete: false, reason: "stopped" };
let response;
try {
const query = new URLSearchParams({ limit: String(limit) });
if (cursor) query.set("cursor", cursor);
response = await request(path + "?" + query, "GET", undefined, undefined, true, signal);
} catch (error) {
if (signal?.aborted) return { cursor, complete: false, reason: "stopped" };
if (error.status === 429) {
const raw = error.retryAfter;
const seconds = raw && /^\d+$/.test(raw) ? Number(raw) :
(raw ? Math.ceil((Date.parse(raw) - Date.now()) / 1000) : NaN);
return { cursor, complete: false, reason: "rate_limited",
retryAfterSeconds: Number.isFinite(seconds) ? Math.max(0, seconds) : 60 };
}
return { cursor, complete: false,
reason: error.status === 400 && error.code === "INVALID_CURSOR" ?
"restart_required" : "request_failed" };
}
if (signal?.aborted) return { cursor, complete: false, reason: "stopped" };
const next = response.headers.get("X-Next-Cursor");
if (!Array.isArray(response.data) || response.data.length > limit ||
(next !== null && (!next || next.length > 1024 || seen.has(next)))) {
return { cursor, complete: false, reason: "invalid_page" };
}
const updated = { cursor: next ?? cursor, complete: next === null };
try {
await processPage(response.data);
if (compareAndSwapCheckpoint &&
await compareAndSwapCheckpoint({ cursor, complete: false }, updated) !== true) {
return { cursor, complete: false, reason: "checkpoint_conflict" };
}
if (saveCheckpoint) await saveCheckpoint(updated);
} catch {
// Do not advance: processing or persistence failed; replay idempotently.
return { cursor, complete: false, reason: "processing_failed" };
}
cursor = updated.cursor;
if (updated.complete) return { ...updated, reason: "complete" };
seen.add(next);
}
return { cursor, complete: false, reason: "page_budget" };
}
// Call these only after explicit price/charge/consent approval, never as a demo.
const askWebsite = (question, approved, stableKey) =>
request("/ai/answers", "POST", {
question, confirmed: true, disclosureAccepted: true,
maximumChargeNano: approved.maximumChargeNano, // decimal string, USD nanos
inputPrice: { rateId: approved.inputRateId, maximumUnits: 40000 },
outputPrice: { rateId: approved.outputRateId, maximumUnits: 500 },
}, stableKey);
const sendSms = (numberId, destination, text, approved, stableKey) =>
request("/communications/sms", "POST", {
numberId, destination, text, confirmed: true, consent: true,
maximumChargeNano: approved.maximumChargeNano,
price: { rateId: approved.smsRateId, maximumUnits: 1 },
}, stableKey);
const pollOperation = (id) => request("/operations/" + encodeURIComponent(id));
// pending/uncertain: keep the same identity; poll, then request reconciliation.
// Never generate a new stableKey merely because a network response was lost.
// Example blocked response (409):
// { "error": { "code": "CAPABILITY_BLOCKED", "message": "Retail activation is not approved." } }
export { checkConnection, capabilities, prices, importPrivateCollection, askWebsite, sendSms, pollOperation };<?php
// Concurrent imports require a private fenced compareAndSwapCheckpoint adapter.
// checkpoint_conflict: explicitly reload owner/endpoint progress, never retry.
// stopped: isCancelled stopped at a page boundary, preserving committed progress.
// PHP website backend only. Never echo the secret or private responses.
function bizgo($path, $method = 'GET', $body = null, $stableKey = null, $withHeaders = false) {
$base = getenv('BIZGO_API_BASE_URL'); // https://<approved-host>/api/v1
$key = getenv('BIZGO_API_KEY'); // <YOUR_BIZGO_CUSTOMER_KEY>
if (!$base || !$key) throw new RuntimeException('Missing server configuration');
$headers = ['Authorization: Bearer ' . $key, 'Accept: application/json'];
if ($body !== null) $headers[] = 'Content-Type: application/json';
if ($stableKey !== null) $headers[] = 'Idempotency-Key: ' . $stableKey;
$ch = curl_init($base . $path);
$responseHeaders = [];
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers, CURLOPT_TIMEOUT => 20,
CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$responseHeaders) {
if (str_starts_with($line, 'HTTP/')) $responseHeaders = [];
$parts = explode(':', $line, 2);
if (count($parts) === 2) $responseHeaders[strtolower(trim($parts[0]))] = trim($parts[1]);
return strlen($line);
},
]);
if ($body !== null) curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body, JSON_THROW_ON_ERROR));
$raw = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($raw === false) throw new RuntimeException('Network outcome unknown: poll, never repeat paid use');
if ($status >= 400) {
$errorData = json_decode($raw, true);
throw new BizgoHttpError($errorData['error']['code'] ?? 'HTTP_ERROR', $status, $responseHeaders['retry-after'] ?? null);
}
$data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
return $withHeaders ? ['data' => $data, 'isList' => is_array(json_decode($raw)), 'headers' => $responseHeaders] : $data;
}
class BizgoHttpError extends RuntimeException {
public function __construct($code, public int $status, public ?string $retryAfter) {
parent::__construct($code);
}
}
function checkConnection() { return bizgo('/connection'); } // no charge
function capabilities() { return bizgo('/capabilities'); }
function prices() { return bizgo('/prices'); } // no spending authorization
// Opt-in only. Callbacks durably upsert private records and save the WHOLE
// checkpoint in private server storage scoped to owner + endpoint.
// For multiple workers, compareAndSwapCheckpoint(expected, updated) must use a
// transactional owner/endpoint/revision comparison with a stale-writer fence.
// Return false on conflict, never overwrite/retry automatically. saveCheckpoint
// is the single-worker alternative; do not combine the two adapters.
// isCancelled is checked between bounded reads; it cannot interrupt PHP cURL.
function importPrivateCollection($path, $processPage, $options = []) {
$checkpoint = $options['checkpoint'] ?? ['cursor' => null, 'complete' => false];
$limit = $options['limit'] ?? 50; $maxPages = $options['maxPages'] ?? 100;
if (!in_array($path, ['/numbers', '/communications', '/media', '/usage'], true) ||
!is_int($limit) || $limit < 1 || $limit > 50 ||
!is_int($maxPages) || $maxPages < 1 || !is_callable($processPage) ||
(isset($options['saveCheckpoint']) && !is_callable($options['saveCheckpoint'])) ||
(isset($options['compareAndSwapCheckpoint']) && !is_callable($options['compareAndSwapCheckpoint'])) ||
(isset($options['isCancelled']) && !is_callable($options['isCancelled'])) ||
(isset($options['saveCheckpoint']) && isset($options['compareAndSwapCheckpoint'])) ||
!is_bool($checkpoint['complete'] ?? null) ||
!array_key_exists('cursor', $checkpoint) ||
!($checkpoint['cursor'] === null || (is_string($checkpoint['cursor']) &&
strlen($checkpoint['cursor']) > 0 && strlen($checkpoint['cursor']) <= 1024))) {
throw new RuntimeException('Invalid private import configuration');
}
$cursor = $checkpoint['cursor'];
$result = ['cursor' => $cursor, 'complete' => false];
if ($checkpoint['complete']) return array_merge($result, ['complete' => true, 'reason' => 'complete']);
$seen = $cursor === null ? [] : [$cursor];
for ($page = 0; $page < $maxPages; $page++) {
if (isset($options['isCancelled']) && ($options['isCancelled'])())
return array_merge($result, ['reason' => 'stopped']);
$query = ['limit' => $limit];
if ($cursor !== null) $query['cursor'] = $cursor;
try {
$response = bizgo($path . '?' . http_build_query($query, '', '&', PHP_QUERY_RFC3986), 'GET', null, null, true);
} catch (\Throwable $error) {
if ($error instanceof BizgoHttpError && $error->status === 429) {
$raw = $error->retryAfter;
$date = $raw === null ? false : strtotime($raw);
$seconds = $raw !== null && ctype_digit($raw) ? (float)$raw : ($date === false ? 60 : $date - time());
return array_merge($result, ['reason' => 'rate_limited', 'retryAfterSeconds' => max(0, $seconds)]);
}
return array_merge($result, ['reason' => $error instanceof BizgoHttpError &&
$error->status === 400 && $error->getMessage() === 'INVALID_CURSOR' ? 'restart_required' : 'request_failed']);
}
if (isset($options['isCancelled']) && ($options['isCancelled'])())
return array_merge($result, ['reason' => 'stopped']);
$next = $response['headers']['x-next-cursor'] ?? null;
if (!$response['isList'] || !is_array($response['data']) || !array_is_list($response['data']) ||
count($response['data']) > $limit ||
($next !== null && ($next === '' || strlen($next) > 1024 || in_array($next, $seen, true)))) {
return array_merge($result, ['reason' => 'invalid_page']);
}
$updated = ['cursor' => $next ?? $cursor, 'complete' => $next === null];
try {
$processPage($response['data']);
if (isset($options['compareAndSwapCheckpoint']) &&
($options['compareAndSwapCheckpoint'])(['cursor' => $cursor, 'complete' => false], $updated) !== true)
return array_merge($result, ['reason' => 'checkpoint_conflict']);
if (isset($options['saveCheckpoint'])) ($options['saveCheckpoint'])($updated);
} catch (\Throwable $error) {
return array_merge($result, ['reason' => 'processing_failed']);
}
$cursor = $updated['cursor']; $result = $updated;
if ($updated['complete']) return array_merge($updated, ['reason' => 'complete']);
$seen[] = $next;
}
return array_merge($result, ['reason' => 'page_budget']);
}
// Functions below are NOT called automatically.
function askWebsite($question, $approved, $stableKey) {
return bizgo('/ai/answers', 'POST', [
'question' => $question, 'confirmed' => true, 'disclosureAccepted' => true,
'maximumChargeNano' => $approved['maximumChargeNano'],
'inputPrice' => ['rateId' => $approved['inputRateId'], 'maximumUnits' => 40000],
'outputPrice' => ['rateId' => $approved['outputRateId'], 'maximumUnits' => 500],
], $stableKey);
}
function sendSms($numberId, $destination, $text, $approved, $stableKey) {
return bizgo('/communications/sms', 'POST', [
'numberId' => $numberId, 'destination' => $destination, 'text' => $text,
'confirmed' => true, 'consent' => true,
'maximumChargeNano' => $approved['maximumChargeNano'],
'price' => ['rateId' => $approved['smsRateId'], 'maximumUnits' => 1],
], $stableKey);
}
function pollOperation($id) { return bizgo('/operations/' . rawurlencode($id)); }
// 409 CAPABILITY_BLOCKED: inspect prerequisites, do not substitute an internal route.
// Keep the same stableKey after disconnects; never repeat pending/uncertain work.
Start with the no-charge connection check. AI/SMS functions are examples only and are never invoked automatically. Read and review current price versions using GET /api/v1/prices with prices:read. The returned unit cap is a bound, not consent; approve both rate IDs and your maximum before a paid request. Prices do not activate services. Choose a stable idempotency key per full business request, keep it across network disconnects, and poll the returned operation ID. Calls, MMS, fax and purchases have no execution routes: inspect capabilities instead.
Additive v1 capabilities never widen a key. Breaking field or behavior changes require a new major API version. Read collections are bounded to 50 records, except up to 100 stock voices. Bodies are limited to 32 KB; questions to 2,000 characters. SMS must fit one GSM/UCS-2 part. AI output approval is exactly 500 tokens; the input cap must cover bounded business context. Paid response details are sanitized and never include provider credentials, raw references, recordings or source snapshots.
Numbers, communications, media and usage return arrays with limit 1–50 (default 50). When X-Next-Cursor is present, URL-encode it as cursor on the same endpoint using an authorized key for the same owner; absence means the end. Cursors never grant scopes. Ordering is descending timestamp then ID: creation for numbers/usage, start for communications, expiry for media. Newer inserts require restarting; this is not a snapshot, and deleted or expired media stays excluded on every page. Invalid tokens return 400 INVALID_CURSOR; malformed query parameters return 400 INVALID_INPUT. Session-secret rotation invalidates cursors. Inbox retains limit and nextBefore pagination.
const url = new URL("/api/v1/usage", apiOrigin);
url.searchParams.set("limit", "50");
let cursor;
do {
if (cursor) url.searchParams.set("cursor", cursor);
const response = await fetch(url, {
headers: { Authorization: "Bearer " + process.env.BIZGO_API_KEY }
});
if (!response.ok) throw new Error("Pagination stopped: " + response.status);
const records = await response.json(); // Still an array; keep private.
await processPrivateRecords(records);
cursor = response.headers.get("X-Next-Cursor");
} while (cursor);