Moving from Twilio
Messaging, step by step
Messages.json becomes POST /comms/sms, status callbacks become signed events, and replies land on your own numbers. Most of the change is renaming.
- Body becomes message
- Cost and segments in every reply
- Delivered only on a carrier receipt
Or keep your Twilio code as it is
- Step 1
Copy your Account SID
Find it on the API keys page in the dashboard. It starts with AC, like a Twilio one, and replaces your Twilio Account SID. - Step 2
Use an API key as the auth token
Any of your keys with the sms:send permission. A test key (px_test_sk_) simulates every send, so start there. - Step 3
Point the SDK at PacketExchange
Add the small HTTP client below, which sends every request for api.twilio.com to packetexchange.io/api/v1/compat. Paths, fields, responses and paging stay the same.
The same call, before and after
Before, on Twilio
import twilio from 'twilio';
const client = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
const message = await client.messages.create({
to: '+447700900123',
from: 'Acme',
body: 'Your order 1042 has shipped.',
statusCallback: 'https://example.com/sms-status',
});
console.log(message.sid, message.status);After, on PacketExchange
import twilio from 'twilio';
// The one addition: send every Twilio API request to PacketExchange.
class PacketExchangeClient extends twilio.RequestClient {
request(opts) {
opts.uri = opts.uri.replace('https://api.twilio.com', 'https://packetexchange.io/api/v1/compat');
return super.request(opts);
}
}
// Your AccountSid from the API keys page, and an API key as the auth token.
const client = twilio(process.env.PX_ACCOUNT_SID, process.env.PX_API_KEY, {
httpClient: new PacketExchangeClient(),
});
const message = await client.messages.create({
to: '+447700900123',
from: 'Acme',
body: 'Your order 1042 has shipped.',
statusCallback: 'https://example.com/sms-status',
});
console.log(message.sid, message.status);Node and Python use the custom HTTP client each Twilio SDK documents. For any other language, send the same requests to the base URL shown in the cURL tab.
Good to know
Message text stays with you
We do not store message content. The send reply includes body; a later read-back returns the record without it, so keep the text on your side if you need it.Callbacks carry our signature
Status callbacks are signed with our own signature header, because we only ever hold a hash of your key. Verify that header, or rely on the https URL being yours.Callbacks use https
A StatusCallback on plain http is refused when you send, so a callback can never be silently dropped.Clear errors for other options
Options outside SMS, such as media or content templates, answer with error 20001, and nothing is sent or charged.Use a main account key
The compatible route takes keys of the account itself. Sub-account keys keep working on the native API.
What maps one to one
| On Twilio | On PacketExchange | How close | What to know |
|---|---|---|---|
| On TwilioTo | On PacketExchangeto | Same | E.164, with or without the plus. |
| On TwilioFrom | On PacketExchangefrom | Same | A number, or up to 30 letters, digits and spaces as an alphanumeric sender. |
| On TwilioBody | On PacketExchangemessage | Same | Up to 1,600 characters. |
| On TwilioMessagingServiceSid | On PacketExchangeroute, strategy or routeId | Our way | Choose how the message is routed instead of which pool sends it, with cheapest, best_quality, balanced, or a route you bought. |
| On TwilioStatusCallback | On PacketExchangeAccount webhook (sms.sent, sms.delivered, sms.failed) | Our way | Set once on the account, so every message reports without passing a URL each time. |
| On TwilioNo idempotency key on sends | On PacketExchangeX-Idempotency-Key header | Goes further | The same key replays the original reply for 24 hours instead of sending, and billing, twice. |
Status values
| On Twilio | On PacketExchange | How close | What to know |
|---|---|---|---|
| On Twilioqueued, accepted | On PacketExchangeaccepted | Same | Taken and being handed to the route. |
| On Twiliosending, sent | On PacketExchangesent | Same | The route took it. |
| On Twiliodelivered | On PacketExchangedelivered | Same | Only from a carrier receipt that says delivered, never inferred. |
| On Twilioundelivered, failed | On PacketExchangefailed | Same | Refused by the route or reported undelivered. Refunded either way. |
Endpoints
| On Twilio | On PacketExchange | How close | What to know |
|---|---|---|---|
| On TwilioPOST /2010-04-01/Accounts/{AccountSid}/Messages.json | On PacketExchangePOST /comms/sms | Same | JSON body with to, from and message. The reply carries the segments billed and the exact cost. |
| On TwilioGET .../Messages/{MessageSid}.json | On PacketExchangeGET /comms/sms/{messageId} | Same | Returns the status timeline, delivered or failed once a carrier receipt arrives. |
| On TwilioGET .../Messages.json | On PacketExchangeGET /comms/sms | Same | Paged by date. |
| On TwilioOne request per message | On PacketExchangePOST /comms/sms/bulk | Goes further | Up to 1,000 messages in one request on an SMS route you bought, with a status for each. |
| On TwilioPOST .../Messages.json with From set to your number | On PacketExchangePOST /dids/{id}/messages | Our way | Two-way SMS lives on the number itself, with its own inbox and threads. |
Six things that work better here
You choose the route
Each message names its sender, and you choose how it is routed: leave the route out and Smart Routing picks one by strategy (cheapest, best_quality or balanced), or pass routeId for an SMS route you bought on the marketplace.The cost is in the reply
Rate, segments and fee are booked together before the message leaves, and the reply carries segments and cost. If the route refuses the hand-off, the charge is reversed and the reply shows a cost of zero.Delivery is never guessed
A message moves to delivered only on a carrier receipt that says delivered. Routes that return no receipts leave their messages at sent, and the message record says whether the route has returned any receipts recently.Bulk is one request
POST /comms/sms/bulk takes up to 1,000 messages on an SMS route you bought, sends them in order and returns a status for each.Retries are safe by header
Send an X-Idempotency-Key on each message. A retry with the same key replays the original reply for 24 hours instead of sending, and billing, a second time.Segments counted before sending
Messages are up to 1,600 characters and are split the way networks count them, at 160 GSM-7 characters (153 a part once split) or 70 Unicode (67 a part), so the cost is known before the message leaves.
Messaging
One request, and the reply states exactly what it cost.
Moving it over
- Step 1
Create a key for sending
In the dashboard, create a live key limited to sms:send, and a test key. Put the live key where your Twilio Auth Token was. - Step 2
Swap the send call
Replace messages.create with POST /comms/sms. Rename Body to message, keep to and from, drop statusCallback, and add an idempotency key. - Step 3
Store our message id
Save messageId where you saved the MessageSid, and cost where you used to fetch the price later. - Step 4
Register the webhook endpoint
Subscribe one HTTPS endpoint to sms.sent, sms.delivered and sms.failed, and check X-PX-Signature on each delivery. - Step 5
Map the statuses
queued and accepted become accepted; sending and sent become sent; undelivered and failed both become failed, and a failed message is refunded. - Step 6
Move inbound and replies
For two-way conversations, request a number, switch SMS on for it and set its forward URL or subscribe to number.sms.received. Reply with POST /dids/{id}/messages. - Step 7
Test, then share live traffic
Run your flows on the test key, then send a share of live traffic per destination and compare delivery and cost before moving the rest.
The send, before and after
Before, on Twilio
import twilio from 'twilio';
const client = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
const message = await client.messages.create({
to: '+447700900123',
from: 'Acme',
body: 'Your order 1042 has shipped.',
statusCallback: 'https://example.com/sms-status',
});
console.log(message.sid, message.status);After, on PacketExchange
import { randomUUID } from 'node:crypto';
const API = 'https://packetexchange.io/api/v1';
// One JSON request with your API key as a Bearer token.
async function px(method, path, body, headers = {}) {
const res = await fetch(API + path, {
method,
headers: {
Authorization: `Bearer ${process.env.PACKETEXCHANGE_API_KEY}`,
'Content-Type': 'application/json',
...headers,
},
body: body === undefined ? undefined : JSON.stringify(body),
});
const json = await res.json();
if (!res.ok) throw new Error(`${res.status} ${json.error?.code}: ${json.error?.message}`);
return json.data;
}
// Delivery updates go to the webhook you registered once, not a per-request URL.
// The idempotency key makes a retry replay the reply instead of sending twice.
const sms = await px('POST', '/comms/sms',
{ to: '+447700900123', from: 'Acme', message: 'Your order 1042 has shipped.' },
{ 'X-Idempotency-Key': randomUUID() },
);
console.log(sms.messageId, sms.status, sms.segments, sms.cost);Leave out routeId and Smart Routing picks the route; add strategy to say how.
Status callbacks become events
| On Twilio | On PacketExchange | How close | What to know |
|---|---|---|---|
| On TwilioForm-encoded POST | On PacketExchangeJSON POST { event, data, timestamp } | Our way | Parse JSON, then switch on event. |
| On TwilioX-Twilio-Signature (HMAC-SHA1 of URL and params) | On PacketExchangeX-PX-Signature v1 (HMAC-SHA256 of timestamp and body) | Goes further | Check it over the raw bytes and refuse anything older than five minutes. |
| On TwilioMessageSid | On PacketExchangedata.messageId | Same | The id the send returned. |
| On TwilioMessageStatus | On PacketExchangeevent (sms.sent, sms.delivered, sms.failed) and data.status | Our way | One event per state instead of one field. |
| On TwilioErrorCode | On PacketExchangedata.errorCode | Our way | Our own codes, plus the carrier receipt values in carrierStatus and carrierError, so support can see what the network said. |
| On TwilioTo, From | On PacketExchangedata.to, data.from | Same | As sent. |
The handler, before and after
Before, on Twilio
import express from 'express';
import twilio from 'twilio';
const app = express();
// Form-encoded body, signed with X-Twilio-Signature over the URL and params.
app.post('/sms-status',
express.urlencoded({ extended: false }),
twilio.webhook(process.env.TWILIO_AUTH_TOKEN),
(req, res) => {
const { MessageSid, MessageStatus, ErrorCode } = req.body;
if (MessageStatus === 'delivered') markDelivered(MessageSid);
if (MessageStatus === 'failed' || MessageStatus === 'undelivered') markFailed(MessageSid, ErrorCode);
res.sendStatus(204);
});After, on PacketExchange
import express from 'express';
import { createHmac, timingSafeEqual } from 'node:crypto';
const app = express();
// Raw bytes in, so the signature is checked over exactly what was sent.
app.post('/px-events', express.raw({ type: 'application/json' }), (req, res) => {
const ts = req.get('X-PX-Timestamp') ?? '';
const mac = createHmac('sha256', process.env.PACKETEXCHANGE_WEBHOOK_SECRET)
.update(`${ts}.`).update(req.body).digest('hex');
const expected = Buffer.from(`v1=${mac}`);
const given = Buffer.from(req.get('X-PX-Signature') ?? '');
const fresh = /^\d+$/.test(ts) && Math.abs(Date.now() / 1000 - Number(ts)) < 300;
// Refuse stale or unsigned deliveries; compare in constant time.
if (!fresh || given.length !== expected.length || !timingSafeEqual(given, expected)) {
return res.sendStatus(401);
}
// One event per state, instead of one MessageStatus field.
const { event, data } = JSON.parse(req.body);
if (event === 'sms.delivered') markDelivered(data.messageId);
if (event === 'sms.failed') markFailed(data.messageId, data.errorCode);
res.sendStatus(204);
});Two-way
Replies to your own numbers arrive as signed events.
Replies on your own numbers
| On Twilio | On PacketExchange | How close | What to know |
|---|---|---|---|
| On TwilioSmsUrl webhook replying with TwiML | On PacketExchangenumber.sms.received event or the number’s forward URL | Our way | A notification, not a reply instruction. Send a reply with POST /dids/{id}/messages. |
| On TwilioBody, From, To | On PacketExchangedata.body, data.from, data.to | Same | Plus data.segments and data.receivedAt. |
curl https://packetexchange.io/api/v1/dids/$DID_ID/messages \
-H "Authorization: Bearer $PACKETEXCHANGE_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "to": "+447700900123", "body": "Thanks, we will call you at 3pm." }'Need a number first? The numbers guide covers requesting one and running it beside your current numbers.
Prove it before live traffic
- Step 1
Use a test key
A test key validates, routes, counts segments and prices the message on a real route, then simulates the send and returns simulated: true. Nothing is delivered and your balance is untouched. - Step 2
Add sandbox credit
Test sends draw on sandbox credit, which is added with an invite code, so your live balance is never touched. - Step 3
Check the webhook path
Send a test event to your endpoint from the dashboard and confirm your handler accepts the signature and rejects a body you altered.
Things that catch people out
Ten send requests a second per key
Each key is held to 10 send requests a second. For volume, use bulk sends or spread traffic over more than one key.Sender IDs are checked
Up to 30 characters from letters, digits, spaces and . + _ -. Each SMS route states whether it carries alphanumeric, numeric or pre-registered senders, so check the route for your destination.Embargoed destinations are refused
Countries the platform does not carry are refused before routing or billing, with a clear error.Four status words, lower case
accepted, sent, delivered and failed. queued and sending map to accepted and sent, and undelivered maps to failed, which is refunded.One webhook shape
Every event arrives as JSON with event, data and timestamp; parse once, then switch on event.
Messaging, answered
Do I need to buy a route before sending?
Can I send from an alphanumeric sender like on Twilio?
How do I handle replies?
What happens when a message fails?
Moving the rest
- Overview and cutover planThe concept map, the plan and the checklist for the whole move.
- VoiceCalls.json and TwiML to POST /comms/calls with call actions, and what to do about mid-call logic.
- VerifyServices, Verifications and VerificationCheck to /verify/start and /verify/check.
- Phone numbersSearching, requesting and pointing numbers, and running old and new numbers side by side.
- Feature comparisonEvery product side by side, and where PacketExchange goes further.
Start with a test key
Open a free account, create a test key and run your existing flows against the real path without sending anything. Move live traffic when it matches.
Twilio is a trademark of Twilio Inc. PacketExchange is not affiliated with or endorsed by Twilio.






