OpenAPI recipes cookbook
The sample-writing policy guarantees a two-language floor on every sample, and the language-policy page spells out which endpoints carry the full six-language group. Both ship single-call snippets. This cookbook is the next level: each recipe is a complete, runnable sequence — call, keep the id, call again — with the envelope rules written down once instead of discovered one 422 at a time. Every recipe runs in cURL, Node.js, Python, Go, Ruby, and PHP, in that fixed order, per the language-policy page. Use a test key (dv_test_sk_…)
so each chain runs against the sandbox; the only places that use a different
key shape are the public-key endpoints, and the recipe says so inline. Field
and parameter definitions live on the linked API-reference pages — this page
is the sequence, not the schema.
Task index
| # | Recipe | Endpoints used |
|---|---|---|
| 1 | Send an SMS, then poll its status | POST /messages/sms, GET /messages/{id} |
| 2 | Create a contact idempotently, then upsert custom fields | POST /contacts, PUT /custom-fields/values |
| 3 | Build a segment over CDP events | POST /sdk/track (public key), POST /segments/export.csv (secret key) |
| 4 | Upload a file and attach it to a send | POST /files/upload, read the returned URL, POST /messages/sms |
| 5 | Bootstrap a reseller subaccount | POST /subaccounts, PUT /subaccounts/{id}/pricing, PUT /subaccounts/rate-cards, PUT /subaccounts/{id}/assigned-rate-card, PUT /subaccounts/{id}/channel-budgets |
| 6 | Read a subaccount’s live usage counters | GET /subaccounts/{id}/usage/live?channel=sms |
| 7 | Stream the live request log to a terminal | GET /logs/tail (SSE) |
| 8 | The envelope rule every recipe inherits | data + meta.request_id, and the { error, meta } failure shape |
| 9 | Place a voice call, poll to completion, fetch the recording | POST /voice/calls, GET /voice/calls/{id}, GET {recording_url} |
| 10 | Stand up a webhook receiver and verify its signatures | POST /webhooks/, signed delivery, POST /webhooks/{id}/deliveries/{deliveryId}/replay |
| 11 | Send a WhatsApp template with approval-state fallback | GET /templates, POST /messages/whatsapp (template, then free-form) |
| 12 | Preflight a send’s cost before you send | GET /pricing/messaging, GET /pricing/estimate, POST /messages/sms |
X-API-Key. Base URL
https://api.orbit.devotel.io/api/v1 — the sandbox is the same URL with a
dv_test_sk_… key, not a separate host. (Recipe 3 opens with the public-key
endpoint under /sdk, which deliberately sits outside /api/v1 — see the
SDK API page.)
1. Send an SMS, then poll its status
The send returns the message id synchronously and the delivery state asynchronously. A webhook is the durable way to consume the status change (wire one up); until then, pollGET /messages/{id} until data.status leaves queued — the lifecycle
values are on Message status lifecycle.
# 1. Send — keep the id. The SDKs add an Idempotency-Key automatically;
# with raw curl, send one yourself on retries.
SEND=$(curl -s -X POST https://api.orbit.devotel.io/api/v1/messages/sms \
-H "X-API-Key: dv_test_sk_YOUR_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: sms-poll-demo-001" \
-d '{ "to": "+14155552671", "body": "Your order 98421 shipped." }')
ID=$(echo "$SEND" | python3 -c 'import sys, json; print(json.load(sys.stdin)["data"]["id"])')
# 2. Poll until status is delivered / failed.
curl -s https://api.orbit.devotel.io/api/v1/messages/$ID \
-H "X-API-Key: dv_test_sk_YOUR_KEY"
import { Orbit } from "@devotel-orbit/node";
const orbit = new Orbit({ apiKey: process.env.ORBIT_API_KEY! });
const sent = await orbit.messages.sendSms({
to: "+14155552671",
body: "Your order 98421 shipped.",
});
// Poll with generic request() — get-by-id kept out of the typed surface.
for (let attempt = 0; attempt < 10; attempt++) {
const { data } = await orbit.request<unknown>("GET", `/messages/${sent.data.id}`);
const status = (data as { status: string }).status;
if (status !== "queued") {
console.log(status); // delivered | failed | …
break;
}
await new Promise((r) => setTimeout(r, 3000));
}
import requests, os, time
headers = {"X-API-Key": os.environ["ORBIT_API_KEY"]}
sent = requests.post(
"https://api.orbit.devotel.io/api/v1/messages/sms",
headers={**headers, "Idempotency-Key": "sms-poll-demo-001"},
json={"to": "+14155552671", "body": "Your order 98421 shipped."},
).json()["data"]
for _ in range(10):
row = requests.get(
f"https://api.orbit.devotel.io/api/v1/messages/{sent['id']}",
headers=headers,
).json()["data"]
if row["status"] not in ("queued", "sending"):
print(row["status"], row.get("error_code"))
break
time.sleep(3)
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/devotel/orbit-go/orbit"
)
func main() {
client, err := orbit.NewClient(os.Getenv("ORBIT_API_KEY"))
if err != nil {
panic(err)
}
// 1. Send — keep data.id. Request adds an Idempotency-Key itself
// when the last argument is "".
var sent struct {
Data struct {
ID string `json:"id"`
} `json:"data"`
}
body := map[string]any{"to": "+14155552671", "body": "Your order 98421 shipped."}
if err := client.Request(context.Background(), "POST", "/api/v1/messages/sms", nil, body, &sent, "sms-poll-demo-001"); err != nil {
panic(err)
}
// 2. Poll until status leaves queued / sending.
for attempt := 0; attempt < 10; attempt++ {
var row struct {
Data struct {
Status string `json:"status"`
} `json:"data"`
}
if err := client.Request(context.Background(), "GET", "/api/v1/messages/"+sent.Data.ID, nil, nil, &row, ""); err != nil {
panic(err)
}
if row.Data.Status != "queued" && row.Data.Status != "sending" {
fmt.Println(row.Data.Status)
return
}
time.Sleep(3 * time.Second)
}
}
require "orbit_sdk"
client = OrbitSdk::Client.from_env
# 1. Send — keep the id under "data".
sent = client.request(
"POST",
"/api/v1/messages/sms",
json_body: { "to" => "+14155552671", "body" => "Your order 98421 shipped." },
idempotency_key: "sms-poll-demo-001"
)
# 2. Poll until status leaves queued / sending.
10.times do
row = client.request("GET", "/api/v1/messages/#{sent.dig("data", "id")}")
status = row.dig("data", "status")
unless %w[queued sending].include?(status)
puts status
break
end
sleep 3
end
<?php
use Devotel\Orbit\OrbitClient;
$client = OrbitClient::fromEnv();
// 1. Send — keep the id under "data".
$sent = $client->request(
method: "POST",
path: "/api/v1/messages/sms",
jsonBody: ["to" => "+14155552671", "body" => "Your order 98421 shipped."],
idempotencyKey: "sms-poll-demo-001",
);
// 2. Poll until status leaves queued / sending.
for ($attempt = 0; $attempt < 10; $attempt++) {
$row = $client->request(method: "GET", path: "/api/v1/messages/{$sent["data"]["id"]}");
$status = $row["data"]["status"];
if (!in_array($status, ["queued", "sending"], true)) {
echo $status, PHP_EOL;
break;
}
sleep(3);
}
message.delivered and message.failed; the signed-body verification loop
per language is in Verify webhook signatures.
2. Create a contact idempotently, then upsert custom fields
Two discipline points in one recipe:Idempotency-Key on the create so a
safe retry can’t duplicate the row, and custom-field values written through
the values endpoint so the write validates against the field definition.
At least one of phone / email is required on the create; field keys and
types are defined first under /api/v1/custom-fields.
# 1. Create the contact. Replay returns the original response with an
# Idempotency-Replay: true header instead of a second row.
curl -X POST https://api.orbit.devotel.io/api/v1/contacts/ \
-H "X-API-Key: dv_test_sk_YOUR_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: signup-5f2d8a1c" \
-d '{ "email": "jane@example.com", "phone": "+14155550123" }'
# 2. Upsert a custom-field value — update semantics on the same key.
curl -X PUT https://api.orbit.devotel.io/api/v1/custom-fields/values \
-H "X-API-Key: dv_test_sk_YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{ "contact_id": "cnt_9f8a7b6c", "key": "customer_tier", "value": "gold" }'
const contact = await orbit.request("POST", "/contacts/", {
body: { email: "jane@example.com", phone: "+14155550123" },
headers: { "Idempotency-Key": "signup-5f2d8a1c" },
});
// Upsert — re-running with a new value on the same key replaces it.
await orbit.request("PUT", "/custom-fields/values", {
body: {
contact_id: (contact.data as { id: string }).id,
key: "customer_tier",
value: "gold",
},
});
import requests, os
headers = {"X-API-Key": os.environ["ORBIT_API_KEY"]}
base = "https://api.orbit.devotel.io/api/v1"
contact = requests.post(
f"{base}/contacts/",
headers={**headers, "Idempotency-Key": "signup-5f2d8a1c"},
json={"email": "jane@example.com", "phone": "+14155550123"},
).json()["data"]
requests.put(
f"{base}/custom-fields/values",
headers=headers,
json={
"contact_id": contact["id"],
"key": "customer_tier",
"value": "gold",
},
).raise_for_status()
package main
import (
"context"
"os"
"github.com/devotel/orbit-go/orbit"
)
func main() {
client, err := orbit.NewClient(os.Getenv("ORBIT_API_KEY"))
if err != nil {
panic(err)
}
// 1. Create — replay with the same key returns the original row.
var created struct {
Data struct {
ID string `json:"id"`
} `json:"data"`
}
body := map[string]any{"email": "jane@example.com", "phone": "+14155550123"}
if err := client.Request(context.Background(), "POST", "/api/v1/contacts/", nil, body, &created, "signup-5f2d8a1c"); err != nil {
panic(err)
}
// 2. Upsert — re-running with a new value on the same key replaces it.
upsert := map[string]any{"contact_id": created.Data.ID, "key": "customer_tier", "value": "gold"}
if err := client.Request(context.Background(), "PUT", "/api/v1/custom-fields/values", nil, upsert, nil, ""); err != nil {
panic(err)
}
}
require "orbit_sdk"
client = OrbitSdk::Client.from_env
# 1. Create — replay with the same key returns the original row.
contact = client.request(
"POST",
"/api/v1/contacts/",
json_body: { "email" => "jane@example.com", "phone" => "+14155550123" },
idempotency_key: "signup-5f2d8a1c"
)
# 2. Upsert — re-running with a new value on the same key replaces it.
client.request(
"PUT",
"/api/v1/custom-fields/values",
json_body: {
"contact_id" => contact.dig("data", "id"),
"key" => "customer_tier",
"value" => "gold",
}
)
<?php
use Devotel\Orbit\OrbitClient;
$client = OrbitClient::fromEnv();
// 1. Create — replay with the same key returns the original row.
$contact = $client->request(
method: "POST",
path: "/api/v1/contacts/",
jsonBody: ["email" => "jane@example.com", "phone" => "+14155550123"],
idempotencyKey: "signup-5f2d8a1c",
);
// 2. Upsert — re-running with a new value on the same key replaces it.
$client->request(
method: "PUT",
path: "/api/v1/custom-fields/values",
jsonBody: [
"contact_id" => $contact["data"]["id"],
"key" => "customer_tier",
"value" => "gold",
],
);
custom_fields — re-read
GET /contacts/{id} to see the upsert. The full idempotency contract
(replay headers, TTL, 409 on conflicting bodies) is in
Idempotent requests.
3. Build a segment over CDP events
The event-ingest endpoint is public-key — it is safe to call from browser or mobile code. Segment building is secret-key — it is a back-office read over your whole contact base. This split is the entire reason the two calls take different keys:- Ingest with the tenant public key (
dv_test_pk_…in test mode) inX-API-Key, on the/sdk/trackpath outside/api/v1. - Segment with the secret key (
dv_test_sk_…) inX-API-Key, on/api/v1/segments/export.csvwith a filter body referencing the ingested event.
# 1. Ingest events with the PUBLIC key — door opens from the browser.
curl -X POST https://api.orbit.devotel.io/sdk/track \
-H "X-API-Key: dv_test_pk_YOUR_PUBLIC_KEY" \
-H "Content-Type: application/json" \
-d '{
"email": "jane@example.com",
"event": "plan_upgraded",
"properties": { "plan": "gold" }
}'
# 2. Export the cohort with the SECRET key — filter on the event.
curl -X POST https://api.orbit.devotel.io/api/v1/segments/export.csv \
-H "X-API-Key: dv_test_sk_YOUR_KEY" \
-H "Content-Type: application/json" \
-o plan-upgrades.csv \
-d '{
"filters": {
"op": "AND",
"conditions": [
{ "field": "event:plan_upgraded", "op": "occurred", "value": null }
]
},
"filename": "plan-upgrades"
}'
// Server side — both calls run server-to-server; only the key differs.
const PUBLIC = process.env.ORBIT_PUBLIC_KEY!; // dv_test_pk_…
await fetch("https://api.orbit.devotel.io/sdk/track", {
method: "POST",
headers: {
"X-API-Key": PUBLIC,
"Content-Type": "application/json",
},
body: JSON.stringify({
email: "jane@example.com",
event: "plan_upgraded",
properties: { plan: "gold" },
}),
});
const orbit = new Orbit({ apiKey: process.env.ORBIT_API_KEY! });
await orbit.request("POST", "/segments/export.csv", {
body: {
filters: {
op: "AND",
conditions: [{ field: "event:plan_upgraded", op: "occurred", value: null }],
},
filename: "plan-upgrades",
},
});
import requests, os
# 1. Public key — the same call the browser SDK makes.
requests.post(
"https://api.orbit.devotel.io/sdk/track",
headers={"X-API-Key": os.environ["ORBIT_PUBLIC_KEY"]},
json={
"email": "jane@example.com",
"event": "plan_upgraded",
"properties": {"plan": "gold"},
},
).raise_for_status()
# 2. Secret key — the export endpoint returns CSV, not the JSON envelope.
resp = requests.post(
"https://api.orbit.devotel.io/api/v1/segments/export.csv",
headers={"X-API-Key": os.environ["ORBIT_API_KEY"]},
json={
"filters": {
"op": "AND",
"conditions": [
{"field": "event:plan_upgraded", "op": "occurred", "value": None}
],
},
"filename": "plan-upgrades",
},
)
with open("plan-upgrades.csv", "wb") as fh:
fh.write(resp.content)
package main
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"os"
"github.com/devotel/orbit-go/orbit"
)
func main() {
// 1. Public key — Request always sends the secret key, so this
// one call goes out over net/http.
track := []byte(`{"email":"jane@example.com","event":"plan_upgraded","properties":{"plan":"gold"}}`)
req, _ := http.NewRequestWithContext(context.Background(), "POST",
"https://api.orbit.devotel.io/sdk/track", bytes.NewReader(track))
req.Header.Set("X-API-Key", os.Getenv("ORBIT_PUBLIC_KEY")) // dv_test_pk_…
req.Header.Set("Content-Type", "application/json")
if _, err := http.DefaultClient.Do(req); err != nil {
panic(err)
}
// 2. Secret key — the export returns CSV, not the JSON envelope,
// and Request JSON-decodes its output, so this call goes out over
// net/http with the same key header.
filters := []byte(`{"filters":{"op":"AND","conditions":[{"field":"event:plan_upgraded","op":"occurred","value":null}]},"filename":"plan-upgrades"}`)
req2, _ := http.NewRequestWithContext(context.Background(), "POST",
"https://api.orbit.devotel.io/api/v1/segments/export.csv", bytes.NewReader(filters))
req2.Header.Set("X-API-Key", os.Getenv("ORBIT_API_KEY"))
req2.Header.Set("Content-Type", "application/json")
resp2, err := http.DefaultClient.Do(req2)
if err != nil {
panic(err)
}
raw, err := io.ReadAll(resp2.Body)
resp2.Body.Close()
if err != nil {
panic(err)
}
if err := os.WriteFile("plan-upgrades.csv", raw, 0o644); err != nil {
panic(err)
}
fmt.Printf("wrote %d bytes\n", len(raw))
}
require "orbit_sdk"
require "net/http"
require "uri"
# 1. Public key — the same call the browser SDK makes.
uri = URI("https://api.orbit.devotel.io/sdk/track")
req = Net::HTTP::Post.new(uri)
req["X-API-Key"] = ENV.fetch("ORBIT_PUBLIC_KEY") # dv_test_pk_…
req["Content-Type"] = "application/json"
req.body = {
"email" => "jane@example.com",
"event" => "plan_upgraded",
"properties" => { "plan" => "gold" },
}.to_json
Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
# 2. Secret key — the export endpoint returns CSV, not the JSON envelope.
uri = URI("https://api.orbit.devotel.io/api/v1/segments/export.csv")
req = Net::HTTP::Post.new(uri)
req["X-API-Key"] = ENV.fetch("ORBIT_API_KEY")
req["Content-Type"] = "application/json"
req.body = {
"filters" => {
"op" => "AND",
"conditions" => [
{ "field" => "event:plan_upgraded", "op" => "occurred", "value" => nil },
],
},
"filename" => "plan-upgrades",
}.to_json
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
File.write("plan-upgrades.csv", res.body) # CSV body, not the JSON envelope
<?php
use Devotel\Orbit\OrbitClient;
// 1. Public key — the same call the browser SDK makes.
$ch = curl_init("https://api.orbit.devotel.io/sdk/track");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode([
"email" => "jane@example.com",
"event" => "plan_upgraded",
"properties" => ["plan" => "gold"],
]),
CURLOPT_HTTPHEADER => [
"X-API-Key: " . getenv("ORBIT_PUBLIC_KEY"), // dv_test_pk_…
"Content-Type: application/json",
],
]);
curl_exec($ch);
curl_close($ch);
// 2. Secret key — the export endpoint returns CSV, not the JSON
// envelope, so read the raw response with the curl extension.
$ch = curl_init("https://api.orbit.devotel.io/api/v1/segments/export.csv");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode([
"filters" => [
"op" => "AND",
"conditions" => [
["field" => "event:plan_upgraded", "op" => "occurred", "value" => null],
],
],
"filename" => "plan-upgrades",
]),
CURLOPT_HTTPHEADER => [
"X-API-Key: " . getenv("ORBIT_API_KEY"),
"Content-Type: application/json",
],
]);
$csv = curl_exec($ch);
curl_close($ch);
file_put_contents("plan-upgrades.csv", $csv);
{ data, meta } envelope — the body is the
file. Event ingestion is versioned separately from the REST API
(SDK API); the export’s filter grammar is on the
Segments API. In a browser, use the
@devotel-orbit/web SDK rather than hand-rolling the identify
- track calls.
4. Upload a file and attach it to a send
Uploaded files return a file id and a signed URL; channel sends accept the media URL on the payload. This recipe uploads an image and rides the URL into an MMS. The 25 MB upload cap and the signed-URL TTL are on the Files API page.# 1. Upload once → keep data.id and the signed URL.
UPLOAD=$(curl -s -X POST https://api.orbit.devotel.io/api/v1/files/upload \
-H "X-API-Key: dv_test_sk_YOUR_KEY" \
-F "file=@./promo.jpg" \
-F "purpose=mms_attachment")
URL=$(echo "$UPLOAD" | python3 -c 'import sys, json; print(json.load(sys.stdin)["data"]["url"])')
# 2. Send the MMS referencing the uploaded media URL.
curl -s -X POST https://api.orbit.devotel.io/api/v1/messages/sms \
-H "X-API-Key: dv_test_sk_YOUR_KEY" \
-H "Content-Type: application/json" \
-d "{
\"to\": \"+14155552671\",
\"channel\": \"mms\",
\"body\": \"This week's promo\",
\"media_urls\": [\"$URL\"]
}"
import FormData from "form-data";
import fs from "node:fs";
const form = new FormData();
form.append("file", fs.createReadStream("./promo.jpg"));
form.append("purpose", "mms_attachment");
const upload = await orbit.request("POST", "/files/upload", {
body: form.getBuffer(),
headers: form.getHeaders(),
});
const url = (upload.data as { url: string }).url;
await orbit.messages.sendSms({
to: "+14155552671",
channel: "mms",
body: "This week's promo",
media_urls: [url],
});
import requests, os
headers = {"X-API-Key": os.environ["ORBIT_API_KEY"]}
base = "https://api.orbit.devotel.io/api/v1"
with open("./promo.jpg", "rb") as fh:
upload = requests.post(
f"{base}/files/upload",
headers=headers,
files={"file": fh},
data={"purpose": "mms_attachment"},
).json()["data"]
requests.post(
f"{base}/messages/sms",
headers=headers,
json={
"to": "+14155552671",
"channel": "mms",
"body": "This week's promo",
"media_urls": [upload["url"]],
},
).raise_for_status()
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"github.com/devotel/orbit-go/orbit"
)
func main() {
// 1. Multipart upload — Request sends JSON bodies only, so the
// upload itself goes out over net/http with the same key header.
var buf bytes.Buffer
mw := multipart.NewWriter(&buf)
fw, _ := mw.CreateFormFile("file", "promo.jpg")
fh, _ := os.Open("./promo.jpg")
io.Copy(fw, fh)
fh.Close()
mw.WriteField("purpose", "mms_attachment")
mw.Close()
req, _ := http.NewRequestWithContext(context.Background(), "POST",
"https://api.orbit.devotel.io/api/v1/files/upload", &buf)
req.Header.Set("X-API-Key", os.Getenv("ORBIT_API_KEY"))
req.Header.Set("Content-Type", mw.FormDataContentType())
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
var upload struct {
Data struct {
URL string `json:"url"`
} `json:"data"`
}
respRaw, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
panic(err)
}
if err := json.Unmarshal(respRaw, &upload); err != nil {
panic(err)
}
// 2. Send the MMS referencing the uploaded media URL.
client, err := orbit.NewClient(os.Getenv("ORBIT_API_KEY"))
if err != nil {
panic(err)
}
send := map[string]any{
"to": "+14155552671", "channel": "mms",
"body": "This week's promo", "media_urls": []any{upload.Data.URL},
}
if err := client.Request(context.Background(), "POST", "/api/v1/messages/sms", nil, send, nil, ""); err != nil {
panic(err)
}
fmt.Println("mms queued")
}
require "orbit_sdk"
client = OrbitSdk::Client.from_env
# 1. Multipart upload — the SDK client sends JSON bodies only, so the
# upload itself goes out as a raw curl -F with the same key header.
upload = JSON.parse(`curl -s -X POST https://api.orbit.devotel.io/api/v1/files/upload \
-H "X-API-Key: #{ENV.fetch("ORBIT_API_KEY")}" \
-F "file=@./promo.jpg" -F "purpose=mms_attachment"`)
# 2. Send the MMS referencing the uploaded media URL.
client.request(
"POST",
"/api/v1/messages/sms",
json_body: {
"to" => "+14155552671",
"channel" => "mms",
"body" => "This week's promo",
"media_urls" => [upload.dig("data", "url")],
}
)
<?php
use Devotel\Orbit\OrbitClient;
// 1. Multipart upload — CURLFile builds the same -F form the cURL tab sends.
$ch = curl_init("https://api.orbit.devotel.io/api/v1/files/upload");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => [
"file" => new CURLFile("./promo.jpg"),
"purpose" => "mms_attachment",
],
CURLOPT_HTTPHEADER => ["X-API-Key: " . getenv("ORBIT_API_KEY")],
]);
$upload = json_decode((string) curl_exec($ch), true);
curl_close($ch);
// 2. Send the MMS referencing the uploaded media URL.
$client = OrbitClient::fromEnv();
$client->request(
method: "POST",
path: "/api/v1/messages/sms",
jsonBody: [
"to" => "+14155552671",
"channel" => "mms",
"body" => "This week's promo",
"media_urls" => [$upload["data"]["url"]],
],
);
file_id flow drives WhatsApp template sends — pass the URL in the
template’s media component. Oversized or HEIC/TIFF source images need to be
re-encoded first with POST /messages/media/convert; the recipe surfaces
that branch inside the MMS page rather than blocking the upload.
5. Bootstrap a reseller subaccount
The five calls a CSPaaS reseller runs to take a child from row to priced-and-capped. Each is idempotent-safe to rerun with the same body — thePUTs are full-set replaces.
# 1. Create the child organization.
CREATE=$(curl -s -X POST https://api.orbit.devotel.io/api/v1/subaccounts \
-H "X-API-Key: dv_test_sk_YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{ "name": "Rahal Industries", "plan": "growth" }')
ID=$(echo "$CREATE" | python3 -c 'import sys, json; print(json.load(sys.stdin)["data"]["id"])')
# 2. Flat reseller margin + aggregate monthly spend cap.
curl -X PUT "https://api.orbit.devotel.io/api/v1/subaccounts/$ID/pricing" \
-H "X-API-Key: dv_test_sk_YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{ "reseller_margin_pct": 25, "monthly_spend_cap_cents": 5000000 }'
# 3. Draft a named rate card in the parent library (full-set replace).
curl -X PUT https://api.orbit.devotel.io/api/v1/subaccounts/rate-cards \
-H "X-API-Key: dv_test_sk_YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{
"cards": [
{ "id": "rc_us_voice_25", "name": "US voice 20% + SMS US 25%",
"lane_cells": ["voice:US:20"], "deck_cells": ["sms:US:25"] }
]
}'
# 4. Bind the card to this child.
curl -X PUT "https://api.orbit.devotel.io/api/v1/subaccounts/$ID/assigned-rate-card" \
-H "X-API-Key: dv_test_sk_YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{ "assigned_rate_card_id": "rc_us_voice_25" }'
# 5. Per-channel budgets so the child can cap SMS hard while voice alerts.
curl -X PUT "https://api.orbit.devotel.io/api/v1/subaccounts/$ID/channel-budgets" \
-H "X-API-Key: dv_test_sk_YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{
"budgets": [
{ "channel": "sms", "threshold_cents": 100000, "period": "monthly", "action": "block" },
{ "channel": "voice", "threshold_cents": 60000, "period": "monthly", "action": "alert" }
]
}'
const created = await orbit.request("POST", "/subaccounts", {
body: { name: "Rahal Industries", plan: "growth" },
});
const id = (created.data as { id: string }).id;
await orbit.request("PUT", `/subaccounts/${id}/pricing`, {
body: { reseller_margin_pct: 25, monthly_spend_cap_cents: 5000000 },
});
await orbit.request("PUT", "/subaccounts/rate-cards", {
body: {
cards: [
{
id: "rc_us_voice_25",
name: "US voice 20% + SMS US 25%",
lane_cells: ["voice:US:20"],
deck_cells: ["sms:US:25"],
},
],
},
});
await orbit.request("PUT", `/subaccounts/${id}/assigned-rate-card`, {
body: { assigned_rate_card_id: "rc_us_voice_25" },
});
await orbit.request("PUT", `/subaccounts/${id}/channel-budgets`, {
body: {
budgets: [
{ channel: "sms", threshold_cents: 100000, period: "monthly", action: "block" },
{ channel: "voice", threshold_cents: 60000, period: "monthly", action: "alert" },
],
},
});
import requests, os
headers = {"X-API-Key": os.environ["ORBIT_API_KEY"]}
base = "https://api.orbit.devotel.io/api/v1"
child = requests.post(
f"{base}/subaccounts",
headers=headers,
json={"name": "Rahal Industries", "plan": "growth"},
).json()["data"]
sub_id = child["id"]
requests.put(
f"{base}/subaccounts/{sub_id}/pricing",
headers=headers,
json={"reseller_margin_pct": 25, "monthly_spend_cap_cents": 5000000},
)
requests.put(
f"{base}/subaccounts/rate-cards",
headers=headers,
json={
"cards": [
{
"id": "rc_us_voice_25",
"name": "US voice 20% + SMS US 25%",
"lane_cells": ["voice:US:20"],
"deck_cells": ["sms:US:25"],
}
]
},
)
requests.put(
f"{base}/subaccounts/{sub_id}/assigned-rate-card",
headers=headers,
json={"assigned_rate_card_id": "rc_us_voice_25"},
)
requests.put(
f"{base}/subaccounts/{sub_id}/channel-budgets",
headers=headers,
json={
"budgets": [
{"channel": "sms", "threshold_cents": 100000, "period": "monthly", "action": "block"},
{"channel": "voice", "threshold_cents": 60000, "period": "monthly", "action": "alert"},
]
},
).raise_for_status()
package main
import (
"context"
"os"
"github.com/devotel/orbit-go/orbit"
)
func main() {
client, err := orbit.NewClient(os.Getenv("ORBIT_API_KEY"))
if err != nil {
panic(err)
}
ctx := context.Background()
put := func(path string, body any) {
if err := client.Request(ctx, "PUT", path, nil, body, nil, ""); err != nil {
panic(err)
}
}
// 1. Create the child organization.
var created struct {
Data struct {
ID string `json:"id"`
} `json:"data"`
}
if err := client.Request(ctx, "POST", "/api/v1/subaccounts", nil,
map[string]any{"name": "Rahal Industries", "plan": "growth"}, &created, ""); err != nil {
panic(err)
}
id := created.Data.ID
// 2. Flat reseller margin + aggregate monthly spend cap.
put("/api/v1/subaccounts/"+id+"/pricing",
map[string]any{"reseller_margin_pct": 25, "monthly_spend_cap_cents": 5000000})
// 3. Draft a named rate card in the parent library (full-set replace).
put("/api/v1/subaccounts/rate-cards", map[string]any{"cards": []any{map[string]any{
"id": "rc_us_voice_25", "name": "US voice 20% + SMS US 25%",
"lane_cells": []any{"voice:US:20"}, "deck_cells": []any{"sms:US:25"},
}}})
// 4. Bind the card to this child.
put("/api/v1/subaccounts/"+id+"/assigned-rate-card",
map[string]any{"assigned_rate_card_id": "rc_us_voice_25"})
// 5. Per-channel budgets so the child can cap SMS hard while voice alerts.
put("/api/v1/subaccounts/"+id+"/channel-budgets", map[string]any{"budgets": []any{
map[string]any{"channel": "sms", "threshold_cents": 100000, "period": "monthly", "action": "block"},
map[string]any{"channel": "voice", "threshold_cents": 60000, "period": "monthly", "action": "alert"},
}})
}
require "orbit_sdk"
client = OrbitSdk::Client.from_env
# 1. Create the child organization.
created = client.request(
"POST",
"/api/v1/subaccounts",
json_body: { "name" => "Rahal Industries", "plan" => "growth" }
)
id = created.dig("data", "id")
# 2. Flat reseller margin + aggregate monthly spend cap.
client.request(
"PUT",
"/api/v1/subaccounts/#{id}/pricing",
json_body: { "reseller_margin_pct" => 25, "monthly_spend_cap_cents" => 5_000_000 }
)
# 3. Draft a named rate card in the parent library (full-set replace).
client.request(
"PUT",
"/api/v1/subaccounts/rate-cards",
json_body: {
"cards" => [
{
"id" => "rc_us_voice_25",
"name" => "US voice 20% + SMS US 25%",
"lane_cells" => ["voice:US:20"],
"deck_cells" => ["sms:US:25"],
},
],
}
)
# 4. Bind the card to this child.
client.request(
"PUT",
"/api/v1/subaccounts/#{id}/assigned-rate-card",
json_body: { "assigned_rate_card_id" => "rc_us_voice_25" }
)
# 5. Per-channel budgets so the child can cap SMS hard while voice alerts.
client.request(
"PUT",
"/api/v1/subaccounts/#{id}/channel-budgets",
json_body: {
"budgets" => [
{ "channel" => "sms", "threshold_cents" => 100_000, "period" => "monthly", "action" => "block" },
{ "channel" => "voice", "threshold_cents" => 60_000, "period" => "monthly", "action" => "alert" },
],
}
)
<?php
use Devotel\Orbit\OrbitClient;
$client = OrbitClient::fromEnv();
// 1. Create the child organization.
$created = $client->request(
method: "POST",
path: "/api/v1/subaccounts",
jsonBody: ["name" => "Rahal Industries", "plan" => "growth"],
);
$id = $created["data"]["id"];
// 2. Flat reseller margin + aggregate monthly spend cap.
$client->request(
method: "PUT",
path: "/api/v1/subaccounts/{$id}/pricing",
jsonBody: ["reseller_margin_pct" => 25, "monthly_spend_cap_cents" => 5000000],
);
// 3. Draft a named rate card in the parent library (full-set replace).
$client->request(
method: "PUT",
path: "/api/v1/subaccounts/rate-cards",
jsonBody: [
"cards" => [
[
"id" => "rc_us_voice_25",
"name" => "US voice 20% + SMS US 25%",
"lane_cells" => ["voice:US:20"],
"deck_cells" => ["sms:US:25"],
],
],
],
);
// 4. Bind the card to this child.
$client->request(
method: "PUT",
path: "/api/v1/subaccounts/{$id}/assigned-rate-card",
jsonBody: ["assigned_rate_card_id" => "rc_us_voice_25"],
);
// 5. Per-channel budgets so the child can cap SMS hard while voice alerts.
$client->request(
method: "PUT",
path: "/api/v1/subaccounts/{$id}/channel-budgets",
jsonBody: [
"budgets" => [
["channel" => "sms", "threshold_cents" => 100000, "period" => "monthly", "action" => "block"],
["channel" => "voice", "threshold_cents" => 60000, "period" => "monthly", "action" => "alert"],
],
],
);
POST /subaccounts/provision
walks the create + pricing + funding + branding chain atomically, and the
dashboard subaccount wizard drives the same steps. The five discrete calls
stay canonical for resellers scripting the lifecycle from their own tooling.
Every endpoint here requires an owner or admin role on the parent
organization; scope and shape details per endpoint are on the
Subaccounts reference.
6. Read a subaccount’s live usage counters
Budgets are enforced send-side against a near-real-time counter; the statement settles the authoritative spend afterward.GET usage/live
bridges the two — the dashboard’s live-usage widget reads it, and your
tooling can poll it directly for a last-moment pre-warn.
curl "https://api.orbit.devotel.io/api/v1/subaccounts/org_sub_rahal_00x9/usage/live?channel=sms" \
-H "X-API-Key: dv_test_sk_YOUR_KEY"
const res = await orbit.request(
"GET",
"/subaccounts/org_sub_rahal_00x9/usage/live",
{ query: { channel: "sms" } },
);
const sms = (res.data as {
channels: {
channel: string;
spent_cents: number;
live_counter_cents: number;
breached: boolean;
}[];
}).channels.find((c) => c.channel === "sms");
console.log(
`SMS spend so far this period: ${sms!.live_counter_cents / 100} USD — breached: ${sms!.breached}`,
);
import requests, os
res = requests.get(
"https://api.orbit.devotel.io/api/v1/subaccounts/org_sub_rahal_00x9/usage/live",
headers={"X-API-Key": os.environ["ORBIT_API_KEY"]},
params={"channel": "sms"}, # optional; omit for one row per channel
).json()["data"]
(c,) = [c for c in res["channels"] if c["channel"] == "sms"]
print(
f"SMS spend this period: {c['live_counter_cents'] / 100:.2f} {res['currency']} "
f"(statement: {c['spent_cents'] / 100:.2f}) — breached: {c['breached']}"
)
package main
import (
"context"
"fmt"
"net/url"
"os"
"github.com/devotel/orbit-go/orbit"
)
func main() {
client, err := orbit.NewClient(os.Getenv("ORBIT_API_KEY"))
if err != nil {
panic(err)
}
query := url.Values{"channel": {"sms"}} // omit for one row per channel
var res struct {
Data struct {
Currency string `json:"currency"`
Channels []struct {
Channel string `json:"channel"`
SpentCents float64 `json:"spent_cents"`
LiveCounterCents float64 `json:"live_counter_cents"`
Breached bool `json:"breached"`
} `json:"channels"`
} `json:"data"`
}
if err := client.Request(context.Background(), "GET",
"/api/v1/subaccounts/org_sub_rahal_00x9/usage/live", query, nil, &res, ""); err != nil {
panic(err)
}
for _, c := range res.Data.Channels {
if c.Channel == "sms" {
fmt.Printf("SMS spend this period: %.2f %s (statement: %.2f) — breached: %v\n",
c.LiveCounterCents/100, res.Data.Currency, c.SpentCents/100, c.Breached)
}
}
}
require "orbit_sdk"
client = OrbitSdk::Client.from_env
res = client.request(
"GET",
"/api/v1/subaccounts/org_sub_rahal_00x9/usage/live",
query: { "channel" => "sms" } # optional; omit for one row per channel
)
sms = res.dig("data", "channels").find { |c| c["channel"] == "sms" }
puts format("SMS spend this period: %.2f %s (statement: %.2f) — breached: %s",
sms["live_counter_cents"] / 100.0, res.dig("data", "currency"),
sms["spent_cents"] / 100.0, sms["breached"])
<?php
use Devotel\Orbit\OrbitClient;
$client = OrbitClient::fromEnv();
$res = $client->request(
method: "GET",
path: "/api/v1/subaccounts/org_sub_rahal_00x9/usage/live",
query: ["channel" => "sms"], // optional; omit for one row per channel
);
foreach ($res["data"]["channels"] as $c) {
if ($c["channel"] === "sms") {
printf(
"SMS spend this period: %.2f %s (statement: %.2f) — breached: %s\n",
$c["live_counter_cents"] / 100,
$res["data"]["currency"],
$c["spent_cents"] / 100,
$c["breached"] ? "true" : "false"
);
}
}
spent_cents (reconciled statement spend),
live_counter_cents (the send-time gate counter the budget enforces
against, per the response shape the Subaccounts page documents), and
breached (true when the counter passes the channel budget’s
threshold_cents, when a budget is set). The route serves no-cache
responses — poll it; do not memoize.
7. Stream the live request log to a terminal
GET /logs/tail is a SSE stream, not a buffered fetch — the generic
request() helper never returns until the stream closes, so consume it
with raw HTTP and an incremental frame parser. The event catalog is
event: log rows; the API page for the endpoint is
Live request-log tail.
# Server-side you can send the API key as a header; the ?token= form
# exists for EventSource, which can't set headers.
curl -N https://api.orbit.devotel.io/api/v1/logs/tail \
-H "X-API-Key: dv_test_sk_YOUR_KEY"
const resp = await fetch("https://api.orbit.devotel.io/api/v1/logs/tail", {
headers: { "X-API-Key": process.env.ORBIT_API_KEY! },
});
const reader = resp.body!.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
// SSE frames are delimited by a blank line.
let idx;
while ((idx = buffer.indexOf("\n\n")) !== -1) {
const frame = buffer.slice(0, idx);
buffer = buffer.slice(idx + 2);
const dataLine = frame
.split("\n")
.find((l) => l.startsWith("data: "));
if (!dataLine) continue;
const row = JSON.parse(dataLine.slice(6));
console.log(row.method, row.path_pattern, row.status_code, row.duration_ms);
}
}
import requests, os
with requests.get(
"https://api.orbit.devotel.io/api/v1/logs/tail",
headers={"X-API-Key": os.environ["ORBIT_API_KEY"]},
stream=True,
) as resp:
buffer = ""
for chunk in resp.iter_content(chunk_size=None):
buffer += chunk.decode()
while "\n\n" in buffer:
frame, buffer = buffer.split("\n\n", 1)
for line in frame.splitlines():
if line.startswith("data: "):
print(line[6:], flush=True)
package main
import (
"bufio"
"fmt"
"net/http"
"os"
"strings"
)
func main() {
// The SDK Request never returns until the stream closes — same as
// the Node and Python tabs, consume it with raw HTTP.
req, _ := http.NewRequest(http.MethodGet, "https://api.orbit.devotel.io/api/v1/logs/tail", nil)
req.Header.Set("X-API-Key", os.Getenv("ORBIT_API_KEY"))
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "data: ") {
fmt.Println(line[len("data: "):])
}
}
}
require "net/http"
require "openssl"
# The SDK request never returns until the stream closes — same as the
# Node and Python tabs, consume it with a raw socket reader.
uri = URI("https://api.orbit.devotel.io/api/v1/logs/tail")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = uri.scheme == "https"
req = Net::HTTP::Get.new(uri)
req["X-API-Key"] = ENV.fetch("ORBIT_API_KEY")
http.request(req) do |res|
res.read_body do |chunk|
chunk.each_line do |line|
puts line[6..] if line.start_with?("data: ")
end
end
end
<?php
// The SDK request never returns until the stream closes — same as the
// Node and Python tabs, consume it with a streaming fopen read.
$ctx = stream_context_create([
"http" => [
"header" => "X-API-Key: " . getenv("ORBIT_API_KEY"),
],
]);
$fh = fopen("https://api.orbit.devotel.io/api/v1/logs/tail", "r", false, $ctx);
while (($line = fgets($fh)) !== false) {
if (str_starts_with($line, "data: ")) {
echo substr($line, 6), PHP_EOL;
}
}
fclose($fh);
method, path_pattern,
status_code, and duration_ms — plenty to grep against a stuck
integration without shipping the whole request body anywhere.
8. The envelope rule every recipe inherits
Every response — success or failure — is the same shape, so your code can branch once instead of per-endpoint. Success (2xx). The payload is underdata; meta.request_id and
meta.timestamp always accompany it. List endpoints add
meta.pagination. Quote the request_id when you open a support issue —
it is keyed into the request log recipe 7 streams.
200 success
{
"data": { "id": "msg_9x2k" },
"meta": { "request_id": "req_4c9d1e", "timestamp": "2026-10-05T14:03:12Z" }
}
ValidationError; raw clients should read data.errors for the
per-field issues the schema rejected. The envelope still closes in meta.
422 validation failure
{
"data": {
"error": {
"code": "VALIDATION_ERROR",
"message": "The request body failed schema validation."
},
"errors": [
{ "field": "to", "issue": "not a valid E.164 phone number" },
{ "field": "body", "issue": "required" }
]
},
"meta": { "request_id": "req_7bd012", "timestamp": "2026-10-05T14:03:12Z" }
}
UNAUTHORIZED /
INVALID_API_KEY); scope failures 403 (INSUFFICIENT_PERMISSIONS);
throttles return 429 with a Retry-After header and a retry_after field
on the body. The canonical code table is on Error codes;
the error-handling examples walk the
retry decision tree per language. All six languages follow the same
envelope — the per-language unwrap idioms are on
How request samples work.
9. Place a voice call, poll to completion, fetch the recording
POST /voice/calls answers 201 (not 202) with data.call_id and
status: "initiated". The from must be a number your organization owns or
a verified outbound caller-id, or the create 422s before anything dials.
record: true starts capture at answer; the recording URL only appears on
the call row once the call ends and the media is finalized, so the poll loop
below keeps reading until status is terminal and then picks up
recording_url.
BASE=https://api.orbit.devotel.io/api/v1
# 1. Place the call — keep data.call_id.
CREATE=$(curl -s -X POST $BASE/voice/calls \
-H "X-API-Key: dv_test_sk_YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{ "to": "+14155552671", "from": "+18005551234", "record": true }')
CALL_ID=$(echo "$CREATE" | python3 -c 'import sys, json; print(json.load(sys.stdin)["data"]["call_id"])')
# 2. Poll until a terminal status (completed / no-answer / failed).
while true; do
ROW=$(curl -s $BASE/voice/calls/$CALL_ID -H "X-API-Key: dv_test_sk_YOUR_KEY")
STATUS=$(echo "$ROW" | python3 -c 'import sys, json; print(json.load(sys.stdin)["data"]["status"])')
case "$STATUS" in completed|no-answer|failed) break ;; esac
sleep 3
done
# 3. Fetch the recording — same key, media bytes back (not the envelope).
REC_URL=$(echo "$ROW" | python3 -c 'import sys, json; print(json.load(sys.stdin)["data"]["recording_url"])')
curl -s "$BASE$REC_URL" -H "X-API-Key: dv_test_sk_YOUR_KEY" -o call-recording.wav
import fs from "node:fs";
const BASE = "https://api.orbit.devotel.io/api/v1";
const headers = { "X-API-Key": process.env.ORBIT_API_KEY! };
// 1. Place the call.
const created = await fetch(`${BASE}/voice/calls`, {
method: "POST",
headers: { ...headers, "Content-Type": "application/json" },
body: JSON.stringify({ to: "+14155552671", from: "+18005551234", record: true }),
}).then((r) => r.json());
const callId = created.data.call_id as string;
// 2. Poll to a terminal status.
let row = created.data;
while (!["completed", "no-answer", "failed"].includes(row.status)) {
await new Promise((r) => setTimeout(r, 3000));
row = (await fetch(`${BASE}/voice/calls/${callId}`, { headers }).then((r) => r.json())).data;
}
// 3. Download the recording with the same key.
if (row.recording_url) {
const media = await fetch(`${BASE}${row.recording_url}`, { headers });
fs.writeFileSync("call-recording.wav", Buffer.from(await media.arrayBuffer()));
}
import requests, os, time
headers = {"X-API-Key": os.environ["ORBIT_API_KEY"]}
base = "https://api.orbit.devotel.io/api/v1"
# 1. Place the call.
created = requests.post(
f"{base}/voice/calls",
headers=headers,
json={"to": "+14155552671", "from": "+18005551234", "record": True},
).json()["data"]
call_id = created["call_id"]
# 2. Poll to a terminal status.
row = created
while row["status"] not in ("completed", "no-answer", "failed"):
time.sleep(3)
row = requests.get(f"{base}/voice/calls/{call_id}", headers=headers).json()["data"]
# 3. Download the recording — the URL is on the call row once finalized.
if row["recording_url"]:
media = requests.get(f"{base}{row['recording_url']}", headers=headers)
open("call-recording.wav", "wb").write(media.content)
package main
import (
"context"
"fmt"
"io"
"net/http"
"os"
"time"
"github.com/devotel/orbit-go/orbit"
)
func main() {
client, err := orbit.NewClient(os.Getenv("ORBIT_API_KEY"))
if err != nil {
panic(err)
}
ctx := context.Background()
// 1. Place the call — keep data.call_id.
var created struct {
Data struct {
CallID string `json:"call_id"`
Status string `json:"status"`
} `json:"data"`
}
dial := map[string]any{"to": "+14155552671", "from": "+18005551234", "record": true}
if err := client.Request(ctx, "POST", "/api/v1/voice/calls", nil, dial, &created, ""); err != nil {
panic(err)
}
// 2. Poll to a terminal status.
row := created.Data
for row.Status != "completed" && row.Status != "no-answer" && row.Status != "failed" {
time.Sleep(3 * time.Second)
var polled struct {
Data struct {
Status string `json:"status"`
} `json:"data"`
}
if err := client.Request(ctx, "GET", "/api/v1/voice/calls/"+created.Data.CallID, nil, nil, &polled, ""); err != nil {
panic(err)
}
row.Status = polled.Data.Status
}
// 3. Fetch the recording — media bytes, not the envelope; read the
// terminal row once more for recording_url, then download it raw.
var final struct {
Data struct {
RecordingURL string `json:"recording_url"`
} `json:"data"`
}
if err := client.Request(ctx, "GET", "/api/v1/voice/calls/"+created.Data.CallID, nil, nil, &final, ""); err != nil {
panic(err)
}
if final.Data.RecordingURL != "" {
req, _ := http.NewRequest(http.MethodGet, "https://api.orbit.devotel.io"+final.Data.RecordingURL, nil)
req.Header.Set("X-API-Key", os.Getenv("ORBIT_API_KEY"))
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fh, _ := os.Create("call-recording.wav")
io.Copy(fh, resp.Body)
fh.Close()
fmt.Println("recording saved")
}
}
require "orbit_sdk"
client = OrbitSdk::Client.from_env
# 1. Place the call — keep data.call_id.
created = client.request(
"POST",
"/api/v1/voice/calls",
json_body: { "to" => "+14155552671", "from" => "+18005551234", "record" => true }
)
row = created["data"]
# 2. Poll to a terminal status.
until %w[completed no-answer failed].include?(row["status"])
sleep 3
row = client.request("GET", "/api/v1/voice/calls/#{row["call_id"]}")["data"]
end
# 3. Fetch the recording — the URL is on the call row once finalized.
if row["recording_url"]
require "open-uri"
URI.open("https://api.orbit.devotel.io#{row["recording_url"]}",
"X-API-Key" => ENV.fetch("ORBIT_API_KEY")) do |media|
File.write("call-recording.wav", media.read)
end
end
<?php
use Devotel\Orbit\OrbitClient;
$client = OrbitClient::fromEnv();
// 1. Place the call — keep data.call_id.
$created = $client->request(
method: "POST",
path: "/api/v1/voice/calls",
jsonBody: ["to" => "+14155552671", "from" => "+18005551234", "record" => true],
);
$row = $created["data"];
// 2. Poll to a terminal status.
while (!in_array($row["status"], ["completed", "no-answer", "failed"], true)) {
sleep(3);
$row = $client->request(method: "GET", path: "/api/v1/voice/calls/{$row["call_id"]}");
$row = $row["data"];
}
// 3. Fetch the recording — the URL is on the call row once finalized.
if (!empty($row["recording_url"])) {
// Media bytes, not the JSON envelope — download with the curl extension.
$ch = curl_init("https://api.orbit.devotel.io" . $row["recording_url"]);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ["X-API-Key: " . getenv("ORBIT_API_KEY")],
]);
$media = curl_exec($ch);
curl_close($ch);
file_put_contents("call-recording.wav", $media);
}
hangup_reason are listed on
Voice call lifecycle. In production, skip
the poll: subscribe a webhook endpoint (recipe 10) to call.completed and
read recording_url off the event. A 422 on the create names the rejected
field in data.errors per the envelope rule (recipe 8).
10. Stand up a webhook receiver and verify its signatures
The verification loop is the same in every language: read the raw body before any JSON parser touches it, readX-Orbit-Signature (legacy
X-Devotel-Signature on old queued deliveries) carrying
t=<unix_ts>,v1=<hex>, HMAC-SHA256 the signed string <t>.<raw_body> with
your endpoint secret, compare timing-safe, and answer 401 on any mismatch
so forged or stale traffic never gets an ack.
import http from "node:http";
import crypto from "node:crypto";
const secret = process.env.ORBIT_WEBHOOK_SECRET!; // whsec_… , stored at registration
http
.createServer((req, res) => {
const chunks: Buffer[] = [];
req.on("data", (c) => chunks.push(c));
req.on("end", () => {
const raw = Buffer.concat(chunks);
const header =
(req.headers["x-orbit-signature"] as string | undefined) ??
(req.headers["x-devotel-signature"] as string | undefined) ??
"";
const t = /t=(\d+)/.exec(header)?.[1] ?? "";
const v1 = /v1=([0-9a-f]+)/.exec(header)?.[1] ?? "";
const expected = crypto
.createHmac("sha256", secret)
.update(`${t}.${raw.toString("utf8")}`)
.digest("hex");
const ok =
expected.length === v1.length &&
crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(v1));
if (!ok) {
res.writeHead(401).end();
return;
}
const event = JSON.parse(raw.toString("utf8"));
console.log(event.type, event.data?.id ?? "");
res.writeHead(200, { "Content-Type": "application/json" }).end('{"received":true}');
});
})
.listen(8080);
import hashlib, hmac, os, re
from http.server import BaseHTTPRequestHandler, HTTPServer
SECRET = os.environ["ORBIT_WEBHOOK_SECRET"].encode() # whsec_… , stored at registration
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
raw = self.rfile.read(int(self.headers["Content-Length"]))
header = (
self.headers.get("X-Orbit-Signature")
or self.headers.get("X-Devotel-Signature")
or ""
)
t = re.search(r"t=(\d+)", header).group(1) if re.search(r"t=(\d+)", header) else ""
v1 = re.search(r"v1=([0-9a-f]+)", header).group(1) if re.search(r"v1=([0-9a-f]+)", header) else ""
expected = hmac.new(SECRET, f"{t}.".encode() + raw, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, v1):
self.send_response(401); self.end_headers(); return
event = __import__("json").loads(raw)
print(event["type"])
self.send_response(200); self.end_headers()
self.wfile.write(b'{"received":true}')
HTTPServer(("0.0.0.0", 8080), Handler).serve_forever()
package main
import (
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"fmt"
"io"
"net/http"
"os"
"regexp"
)
var (
tRe = regexp.MustCompile(`t=(\d+)`)
v1Re = regexp.MustCompile(`v1=([0-9a-f]+)`)
)
func main() {
secret := os.Getenv("ORBIT_WEBHOOK_SECRET") // whsec_… , stored at registration
http.HandleFunc("/webhooks/orbit", func(w http.ResponseWriter, r *http.Request) {
raw, _ := io.ReadAll(r.Body)
header := r.Header.Get("X-Orbit-Signature")
if header == "" {
header = r.Header.Get("X-Devotel-Signature")
}
t, v1 := "", ""
if m := tRe.FindStringSubmatch(header); m != nil {
t = m[1]
}
if m := v1Re.FindStringSubmatch(header); m != nil {
v1 = m[1]
}
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(t + "."))
mac.Write(raw)
expected := hex.EncodeToString(mac.Sum(nil))
if subtle.ConstantTimeCompare([]byte(expected), []byte(v1)) != 1 {
w.WriteHeader(http.StatusUnauthorized)
return
}
fmt.Println("verified event")
w.Write([]byte(`{"received":true}`))
})
http.ListenAndServe(":8080", nil)
}
require "webrick"
require "openssl"
require "json"
secret = ENV.fetch("ORBIT_WEBHOOK_SECRET") # whsec_… , stored at registration
server = WEBrick::HTTPServer.new(Port: 8080)
server.mount_proc "/webhooks/orbit" do |req, res|
raw = req.body
header = req["X-Orbit-Signature"] || req["X-Devotel-Signature"] || ""
t = header[/t=(\d+)/, 1] || ""
v1 = header[/v1=([0-9a-f]+)/, 1] || ""
expected = OpenSSL::HMAC.hexdigest("sha256", secret, "#{t}.#{raw}")
unless OpenSSL.fixed_length_secure_compare(expected, v1)
res.status = 401
next
end
puts JSON.parse(raw)["type"]
res.body = '{"received":true}'
end
server.start
<?php
$secret = getenv("ORBIT_WEBHOOK_SECRET"); // whsec_… , stored at registration
$raw = file_get_contents("php://input");
$header = $_SERVER["HTTP_X_ORBIT_SIGNATURE"]
?? $_SERVER["HTTP_X_DEVOTEL_SIGNATURE"]
?? "";
preg_match('/t=(\d+)/', $header, $mt);
preg_match('/v1=([0-9a-f]+)/', $header, $mv);
$t = $mt[1] ?? "";
$v1 = $mv[1] ?? "";
$expected = hash_hmac("sha256", $t . "." . $raw, $secret);
if (!hash_equals($expected, $v1)) {
http_response_code(401);
exit;
}
$event = json_decode($raw, true);
echo $event["type"], PHP_EOL;
http_response_code(200);
echo '{"received":true}';
BASE=https://api.orbit.devotel.io/api/v1
# 1. Register — the response carries the signing secret in plaintext
# ONCE; store it now (later reads show a masked prefix only).
REG=$(curl -s -X POST $BASE/webhooks/ \
-H "X-API-Key: dv_test_sk_YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://receiver.example.dev/webhooks/orbit",
"events": ["message.delivered", "message.failed"],
"description": "DLR receiver for order notifications"
}')
WH_ID=$(echo "$REG" | python3 -c 'import sys, json; print(json.load(sys.stdin)["data"]["id"])')
# data.secret here is the whsec_… value your receiver verifies against.
# 2. Generate a DLR — one SMS through recipe 1 fires message.delivered.
curl -s -X POST $BASE/messages/sms \
-H "X-API-Key: dv_test_sk_YOUR_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: webhook-verify-demo-001" \
-d '{ "to": "+14155552671", "body": "Your order 98421 shipped." }' > /dev/null
# 3. Find the delivery, then replay it — the receiver must verify and
# ack 200 a second time.
DELIVERY_ID=$(curl -s "$BASE/webhooks/deliveries?endpoint_id=$WH_ID" \
-H "X-API-Key: dv_test_sk_YOUR_KEY" \
| python3 -c 'import sys, json; print(json.load(sys.stdin)["data"][0]["id"])')
curl -s -X POST "$BASE/webhooks/$WH_ID/deliveries/$DELIVERY_ID/replay" \
-H "X-API-Key: dv_test_sk_YOUR_KEY"
const reg = await orbit.request("POST", "/webhooks/", {
body: {
url: "https://receiver.example.dev/webhooks/orbit",
events: ["message.delivered", "message.failed"],
description: "DLR receiver for order notifications",
},
});
const whId = (reg.data as { id: string }).id; // reg.data.secret: store now, shown once
await orbit.messages.sendSms({ to: "+14155552671", body: "Your order 98421 shipped." });
const deliveries = await orbit.request("GET", "/webhooks/deliveries", {
query: { endpoint_id: whId },
});
const deliveryId = (deliveries.data as { id: string }[])[0].id;
await orbit.request(
"POST",
`/webhooks/${whId}/deliveries/${deliveryId}/replay`,
{},
);
import requests, os
headers = {"X-API-Key": os.environ["ORBIT_API_KEY"]}
base = "https://api.orbit.devotel.io/api/v1"
reg = requests.post(
f"{base}/webhooks/",
headers=headers,
json={
"url": "https://receiver.example.dev/webhooks/orbit",
"events": ["message.delivered", "message.failed"],
"description": "DLR receiver for order notifications",
},
).json()["data"]
# reg["secret"] is the whsec_… value — store it; later reads mask it.
requests.post(
f"{base}/messages/sms",
headers={**headers, "Idempotency-Key": "webhook-verify-demo-001"},
json={"to": "+14155552671", "body": "Your order 98421 shipped."},
)
delivery_id = requests.get(
f"{base}/webhooks/deliveries", headers=headers, params={"endpoint_id": reg["id"]},
).json()["data"][0]["id"]
requests.post(
f"{base}/webhooks/{reg['id']}/deliveries/{delivery_id}/replay", headers=headers,
).raise_for_status()
package main
import (
"context"
"net/url"
"os"
"github.com/devotel/orbit-go/orbit"
)
func main() {
client, err := orbit.NewClient(os.Getenv("ORBIT_API_KEY"))
if err != nil {
panic(err)
}
ctx := context.Background()
// 1. Register — data.secret is shown once; store it now.
var reg struct {
Data struct {
ID string `json:"id"`
} `json:"data"`
}
regBody := map[string]any{
"url": "https://receiver.example.dev/webhooks/orbit",
"events": []any{"message.delivered", "message.failed"},
"description": "DLR receiver for order notifications",
}
if err := client.Request(ctx, "POST", "/api/v1/webhooks/", nil, regBody, ®, ""); err != nil {
panic(err)
}
// 2. Generate a DLR — one SMS through recipe 1 fires message.delivered.
send := map[string]any{"to": "+14155552671", "body": "Your order 98421 shipped."}
if err := client.Request(ctx, "POST", "/api/v1/messages/sms", nil, send, nil, "webhook-verify-demo-001"); err != nil {
panic(err)
}
// 3. Find the delivery, then replay it.
var deliveries struct {
Data []struct {
ID string `json:"id"`
} `json:"data"`
}
q := url.Values{"endpoint_id": {reg.Data.ID}}
if err := client.Request(ctx, "GET", "/api/v1/webhooks/deliveries", q, nil, &deliveries, ""); err != nil {
panic(err)
}
replay := "/api/v1/webhooks/" + reg.Data.ID + "/deliveries/" + deliveries.Data[0].ID + "/replay"
if err := client.Request(ctx, "POST", replay, nil, nil, nil, ""); err != nil {
panic(err)
}
}
require "orbit_sdk"
client = OrbitSdk::Client.from_env
# 1. Register — data.secret is shown once; store it now.
reg = client.request(
"POST",
"/api/v1/webhooks/",
json_body: {
"url" => "https://receiver.example.dev/webhooks/orbit",
"events" => ["message.delivered", "message.failed"],
"description" => "DLR receiver for order notifications",
}
)
# 2. Generate a DLR — one SMS through recipe 1 fires message.delivered.
client.request(
"POST",
"/api/v1/messages/sms",
json_body: { "to" => "+14155552671", "body" => "Your order 98421 shipped." },
idempotency_key: "webhook-verify-demo-001"
)
# 3. Find the delivery, then replay it.
deliveries = client.request(
"GET",
"/api/v1/webhooks/deliveries",
query: { "endpoint_id" => reg.dig("data", "id") }
)
delivery_id = deliveries.dig("data", 0, "id")
client.request(
"POST",
"/api/v1/webhooks/#{reg.dig("data", "id")}/deliveries/#{delivery_id}/replay"
)
<?php
use Devotel\Orbit\OrbitClient;
$client = OrbitClient::fromEnv();
// 1. Register — data.secret is shown once; store it now.
$reg = $client->request(
method: "POST",
path: "/api/v1/webhooks/",
jsonBody: [
"url" => "https://receiver.example.dev/webhooks/orbit",
"events" => ["message.delivered", "message.failed"],
"description" => "DLR receiver for order notifications",
],
);
// 2. Generate a DLR — one SMS through recipe 1 fires message.delivered.
$client->request(
method: "POST",
path: "/api/v1/messages/sms",
jsonBody: ["to" => "+14155552671", "body" => "Your order 98421 shipped."],
idempotencyKey: "webhook-verify-demo-001",
);
// 3. Find the delivery, then replay it.
$deliveries = $client->request(
method: "GET",
path: "/api/v1/webhooks/deliveries",
query: ["endpoint_id" => $reg["data"]["id"]],
);
$deliveryId = $deliveries["data"][0]["id"];
$client->request(
method: "POST",
path: "/api/v1/webhooks/{$reg["data"]["id"]}/deliveries/{$deliveryId}/replay",
);
Orbit.webhooks.constructEvent and friends) wrap this same check in
Verify webhook signatures; rotation and
the legacy header fallback are specified on
Webhook security.
11. Send a WhatsApp template with approval-state fallback
Outside the recipient’s 24-hour customer-service window, WhatsApp sends must ride a Meta-approved template; inside it, free-form text is accepted. The chain below reads the template’s approval state first and falls back to free-form when the template is notAPPROVED:
BASE=https://api.orbit.devotel.io/api/v1
# 1. Read the approval state — never send a name that hasn't cleared review.
STATUS=$(curl -s $BASE/templates -H "X-API-Key: dv_test_sk_YOUR_KEY" \
| python3 -c 'import sys, json
rows = [t for t in json.load(sys.stdin)["data"] if t["name"] == "order_shipped"]
print(rows[0]["status"] if rows else "MISSING")')
if [ "$STATUS" = "APPROVED" ]; then
# 2a. Template send — positional {{1}} filled from template_params.
curl -s -X POST $BASE/messages/whatsapp \
-H "X-API-Key: dv_test_sk_YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{
"to": "+14155552671",
"type": "template",
"template": { "name": "order_shipped", "language": { "code": "en_US" } },
"template_params": { "1": "order 98421" }
}'
else
# 2b. Fallback — free-form text, accepted only inside the 24h window.
curl -s -X POST $BASE/messages/whatsapp \
-H "X-API-Key: dv_test_sk_YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{
"to": "+14155552671",
"type": "text",
"text": { "body": "Your order 98421 shipped." }
}'
fi
const templates = await orbit.request("GET", "/templates");
const tpl = (templates.data as { name: string; status: string }[])
.find((t) => t.name === "order_shipped");
if (tpl?.status === "APPROVED") {
await orbit.request("POST", "/messages/whatsapp", {
body: {
to: "+14155552671",
type: "template",
template: { name: "order_shipped", language: { code: "en_US" } },
template_params: { "1": "order 98421" },
},
});
} else {
// PENDING / REJECTED / missing → free-form, inside the 24h window only.
await orbit.request("POST", "/messages/whatsapp", {
body: {
to: "+14155552671",
type: "text",
text: { body: "Your order 98421 shipped." },
},
});
}
import requests, os
headers = {"X-API-Key": os.environ["ORBIT_API_KEY"]}
base = "https://api.orbit.devotel.io/api/v1"
rows = requests.get(f"{base}/templates", headers=headers).json()["data"]
tpl = next((t for t in rows if t["name"] == "order_shipped"), None)
if tpl and tpl["status"] == "APPROVED":
body = {
"to": "+14155552671",
"type": "template",
"template": {"name": "order_shipped", "language": {"code": "en_US"}},
"template_params": {"1": "order 98421"},
}
else:
# Free-form fallback — only accepted inside the 24h service window.
body = {
"to": "+14155552671",
"type": "text",
"text": {"body": "Your order 98421 shipped."},
}
requests.post(f"{base}/messages/whatsapp", headers=headers, json=body).raise_for_status()
package main
import (
"context"
"os"
"github.com/devotel/orbit-go/orbit"
)
func main() {
client, err := orbit.NewClient(os.Getenv("ORBIT_API_KEY"))
if err != nil {
panic(err)
}
ctx := context.Background()
// 1. Read the approval state.
var templates struct {
Data []struct {
Name string `json:"name"`
Status string `json:"status"`
} `json:"data"`
}
if err := client.Request(ctx, "GET", "/api/v1/templates", nil, nil, &templates, ""); err != nil {
panic(err)
}
status := "MISSING"
for _, t := range templates.Data {
if t.Name == "order_shipped" {
status = t.Status
}
}
// 2. Template send when approved — free-form inside the 24h window otherwise.
var body map[string]any
if status == "APPROVED" {
body = map[string]any{
"to": "+14155552671", "type": "template",
"template": map[string]any{"name": "order_shipped", "language": map[string]any{"code": "en_US"}},
"template_params": map[string]any{"1": "order 98421"},
}
} else {
body = map[string]any{
"to": "+14155552671", "type": "text",
"text": map[string]any{"body": "Your order 98421 shipped."},
}
}
if err := client.Request(ctx, "POST", "/api/v1/messages/whatsapp", nil, body, nil, ""); err != nil {
panic(err)
}
}
require "orbit_sdk"
client = OrbitSdk::Client.from_env
# 1. Read the approval state — never send a name that hasn't cleared review.
rows = client.request("GET", "/api/v1/templates").dig("data")
tpl = rows.find { |t| t["name"] == "order_shipped" }
# 2. Template send when approved — free-form inside the 24h window otherwise.
body =
if tpl && tpl["status"] == "APPROVED"
{
"to" => "+14155552671",
"type" => "template",
"template" => { "name" => "order_shipped", "language" => { "code" => "en_US" } },
"template_params" => { "1" => "order 98421" },
}
else
{
"to" => "+14155552671",
"type" => "text",
"text" => { "body" => "Your order 98421 shipped." },
}
end
client.request("POST", "/api/v1/messages/whatsapp", json_body: body)
<?php
use Devotel\Orbit\OrbitClient;
$client = OrbitClient::fromEnv();
// 1. Read the approval state — never send a name that hasn't cleared review.
$rows = $client->request(method: "GET", path: "/api/v1/templates");
$tpl = null;
foreach ($rows["data"] as $t) {
if ($t["name"] === "order_shipped") {
$tpl = $t;
}
}
// 2. Template send when approved — free-form inside the 24h window otherwise.
$body = ($tpl !== null && $tpl["status"] === "APPROVED")
? [
"to" => "+14155552671",
"type" => "template",
"template" => ["name" => "order_shipped", "language" => ["code" => "en_US"]],
"template_params" => ["1" => "order 98421"],
]
: [
"to" => "+14155552671",
"type" => "text",
"text" => ["body" => "Your order 98421 shipped."],
];
$client->request(method: "POST", path: "/api/v1/messages/whatsapp", jsonBody: $body);
data.errors. Template authoring and submission live on the
WhatsApp channel page; status flips arrive on your
webhooks as template status updates.
12. Preflight a send’s cost before you send
Two reads before the write:GET /pricing/messaging lists your lanes for a
country, and GET /pricing/estimate resolves the exact rate for one
destination. Gate the send on the estimate so an unpublished lane or a
budget breach surfaces before money moves:
BASE=https://api.orbit.devotel.io/api/v1
# 1. Lane table for the destination country.
curl -s "$BASE/pricing/messaging?country=US" -H "X-API-Key: dv_test_sk_YOUR_KEY"
# 2. Exact per-unit rate for this recipient. rate is null when no rate
# is published for the lane — treat that as "do not send".
EST=$(curl -s "$BASE/pricing/estimate?channel=sms&to=%2B1415552671" \
-H "X-API-Key: dv_test_sk_YOUR_KEY")
RATE=$(echo "$EST" | python3 -c 'import sys, json; print((json.load(sys.stdin)["data"]["rate"] or {}).get("ratePerUnit", "UNPUBLISHED"))')
# 3. Send only when the lane priced — same chain as recipe 1.
if [ "$RATE" != "UNPUBLISHED" ]; then
curl -s -X POST $BASE/messages/sms \
-H "X-API-Key: dv_test_sk_YOUR_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: preflight-demo-001" \
-d '{ "to": "+14155552671", "body": "Your order 98421 shipped." }'
fi
const lanes = await orbit.request("GET", "/pricing/messaging", {
query: { country: "US" },
});
const estimate = await orbit.request("GET", "/pricing/estimate", {
query: { channel: "sms", to: "+14155552671" },
});
const rate = (estimate.data as {
rate: { ratePerUnit: number; currency: string } | null;
}).rate;
if (rate && rate.ratePerUnit <= 0.02) {
await orbit.messages.sendSms({ to: "+14155552671", body: "Your order 98421 shipped." });
} else {
console.warn("lane unpublished or over budget — send skipped");
}
import requests, os
headers = {"X-API-Key": os.environ["ORBIT_API_KEY"]}
base = "https://api.orbit.devotel.io/api/v1"
lanes = requests.get(f"{base}/pricing/messaging", headers=headers, params={"country": "US"}).json()["data"]
estimate = requests.get(
f"{base}/pricing/estimate", headers=headers, params={"channel": "sms", "to": "+14155552671"},
).json()["data"]
rate = estimate["rate"]
if rate and rate["ratePerUnit"] <= 0.02:
requests.post(
f"{base}/messages/sms",
headers={**headers, "Idempotency-Key": "preflight-demo-001"},
json={"to": "+14155552671", "body": "Your order 98421 shipped."},
).raise_for_status()
else:
print("lane unpublished or over budget — send skipped")
package main
import (
"context"
"fmt"
"net/url"
"os"
"github.com/devotel/orbit-go/orbit"
)
func main() {
client, err := orbit.NewClient(os.Getenv("ORBIT_API_KEY"))
if err != nil {
panic(err)
}
ctx := context.Background()
// 1. Lane table for the destination country.
if err := client.Request(ctx, "GET", "/api/v1/pricing/messaging",
url.Values{"country": {"US"}}, nil, nil, ""); err != nil {
panic(err)
}
// 2. Exact per-unit rate for this recipient.
var estimate struct {
Data struct {
Rate *struct {
RatePerUnit float64 `json:"ratePerUnit"`
} `json:"rate"`
} `json:"data"`
}
q := url.Values{"channel": {"sms"}, "to": {"+14155552671"}}
if err := client.Request(ctx, "GET", "/api/v1/pricing/estimate", q, nil, &estimate, ""); err != nil {
panic(err)
}
// 3. Send only when the lane priced.
if estimate.Data.Rate != nil && estimate.Data.Rate.RatePerUnit <= 0.02 {
send := map[string]any{"to": "+14155552671", "body": "Your order 98421 shipped."}
if err := client.Request(ctx, "POST", "/api/v1/messages/sms", nil, send, nil, "preflight-demo-001"); err != nil {
panic(err)
}
} else {
fmt.Println("lane unpublished or over budget — send skipped")
}
}
require "orbit_sdk"
client = OrbitSdk::Client.from_env
# 1. Lane table for the destination country.
client.request("GET", "/api/v1/pricing/messaging", query: { "country" => "US" })
# 2. Exact per-unit rate for this recipient.
estimate = client.request(
"GET",
"/api/v1/pricing/estimate",
query: { "channel" => "sms", "to" => "+14155552671" }
)
rate = estimate.dig("data", "rate")
# 3. Send only when the lane priced.
if rate && rate["ratePerUnit"] <= 0.02
client.request(
"POST",
"/api/v1/messages/sms",
json_body: { "to" => "+14155552671", "body" => "Your order 98421 shipped." },
idempotency_key: "preflight-demo-001"
)
else
puts "lane unpublished or over budget — send skipped"
end
<?php
use Devotel\Orbit\OrbitClient;
$client = OrbitClient::fromEnv();
// 1. Lane table for the destination country.
$client->request(method: "GET", path: "/api/v1/pricing/messaging", query: ["country" => "US"]);
// 2. Exact per-unit rate for this recipient.
$estimate = $client->request(
method: "GET",
path: "/api/v1/pricing/estimate",
query: ["channel" => "sms", "to" => "+14155552671"],
);
$rate = $estimate["data"]["rate"];
// 3. Send only when the lane priced.
if ($rate !== null && $rate["ratePerUnit"] <= 0.02) {
$client->request(
method: "POST",
path: "/api/v1/messages/sms",
jsonBody: ["to" => "+14155552671", "body" => "Your order 98421 shipped."],
idempotencyKey: "preflight-demo-001",
);
} else {
echo "lane unpublished or over budget — send skipped", PHP_EOL;
}
/pricing/messaging returns baseRatePerUnit and effectiveRatePerUnit
per lane (the effective figure includes your org overrides); /pricing/estimate
resolves the destination country from the E.164 number itself and adds
allIn=true for the itemized surcharge view. Both are reads — they never
reserve budget or touch the rate card. Longer bodies split into segments the
same way the send path splits them, so cost a campaign as
segments × ratePerUnit before committing.
See also
- API Overview — base URL, auth, pagination, and the envelope this cookbook builds on
- REST API recipes — the task-by-task cookbook with all six languages on every flow
- Per-language recipes — the same four-way loop in Python / Go / Ruby / PHP / Java / C#
- Idempotent requests — the full Idempotency-Key contract recipe 2 leans on
- Error handling examples — typed error handling per language