Skip to content

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
Keep your code

Or keep your Twilio code as it is

Your Twilio SDK can talk to PacketExchange directly. Change the credentials and add one small HTTP client, and messages.create, fetch, list and status callbacks keep working. The rest of this guide is for moving to the native API.
  1. 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.
  2. 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.
  3. 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

twilio: send a message
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

the same code, 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.
Fields

What maps one to one

The request fields first, then the status values your code switches on.
Message request fields
On TwilioToOn PacketExchangetoSameE.164, with or without the plus.
On TwilioFromOn PacketExchangefromSameA number, or up to 30 letters, digits and spaces as an alphanumeric sender.
On TwilioBodyOn PacketExchangemessageSameUp to 1,600 characters.
On TwilioMessagingServiceSidOn PacketExchangeroute, strategy or routeIdOur wayChoose how the message is routed instead of which pool sends it, with cheapest, best_quality, balanced, or a route you bought.
On TwilioStatusCallbackOn PacketExchangeAccount webhook (sms.sent, sms.delivered, sms.failed)Our waySet once on the account, so every message reports without passing a URL each time.
On TwilioNo idempotency key on sendsOn PacketExchangeX-Idempotency-Key headerGoes furtherThe same key replays the original reply for 24 hours instead of sending, and billing, twice.

Status values

Message status values
On Twilioqueued, acceptedOn PacketExchangeacceptedSameTaken and being handed to the route.
On Twiliosending, sentOn PacketExchangesentSameThe route took it.
On TwiliodeliveredOn PacketExchangedeliveredSameOnly from a carrier receipt that says delivered, never inferred.
On Twilioundelivered, failedOn PacketExchangefailedSameRefused by the route or reported undelivered. Refunded either way.

Endpoints

Messaging endpoints
On TwilioPOST /2010-04-01/Accounts/{AccountSid}/Messages.jsonOn PacketExchangePOST /comms/smsSameJSON body with to, from and message. The reply carries the segments billed and the exact cost.
On TwilioGET .../Messages/{MessageSid}.jsonOn PacketExchangeGET /comms/sms/{messageId}SameReturns the status timeline, delivered or failed once a carrier receipt arrives.
On TwilioGET .../Messages.jsonOn PacketExchangeGET /comms/smsSamePaged by date.
On TwilioOne request per messageOn PacketExchangePOST /comms/sms/bulkGoes furtherUp 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 numberOn PacketExchangePOST /dids/{id}/messagesOur wayTwo-way SMS lives on the number itself, with its own inbox and threads.
What changes

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.

Steps

Moving it over

  1. 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.
  2. 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.
  3. Step 3

    Store our message id

    Save messageId where you saved the MessageSid, and cost where you used to fetch the price later.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
Code

The send, before and after

Before, on Twilio

twilio: send a message
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

packetexchange: send a message
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.

Webhooks

Status callbacks become events

One endpoint receives every event you subscribed to, as JSON, signed over the timestamp and body.
Message webhook fields
On TwilioForm-encoded POSTOn PacketExchangeJSON POST { event, data, timestamp }Our wayParse 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 furtherCheck it over the raw bytes and refuse anything older than five minutes.
On TwilioMessageSidOn PacketExchangedata.messageIdSameThe id the send returned.
On TwilioMessageStatusOn PacketExchangeevent (sms.sent, sms.delivered, sms.failed) and data.statusOur wayOne event per state instead of one field.
On TwilioErrorCodeOn PacketExchangedata.errorCodeOur wayOur own codes, plus the carrier receipt values in carrierStatus and carrierError, so support can see what the network said.
On TwilioTo, FromOn PacketExchangedata.to, data.fromSameAs sent.

The handler, before and after

Before, on Twilio

twilio: status callback handler
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

packetexchange: webhook handler
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.

Inbound

Replies on your own numbers

Inbound messages are reported, not answered with TwiML. Your app replies with a normal request.
Inbound message handling
On TwilioSmsUrl webhook replying with TwiMLOn PacketExchangenumber.sms.received event or the number’s forward URLOur wayA notification, not a reply instruction. Send a reply with POST /dids/{id}/messages.
On TwilioBody, From, ToOn PacketExchangedata.body, data.from, data.toSamePlus data.segments and data.receivedAt.
POST /dids/{id}/messages
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.

Testing

Prove it before live traffic

  1. 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.
  2. 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.
  3. 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.
Gotchas

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.
Questions

Messaging, answered

Do I need to buy a route before sending?
No. Leave the route out and Smart Routing picks one for the destination by the strategy you pass. Buying an SMS route on the marketplace is for when you want a specific route, and bulk sends need one.
Can I send from an alphanumeric sender like on Twilio?
Yes, where the route carries alphanumeric senders. Each SMS route says which sender types it carries before you buy or send.
How do I handle replies?
Replies arrive on your own numbers. Switch SMS on for the number, then either set its forward URL or subscribe to number.sms.received. Each number also has an inbox and threads in the dashboard.
What happens when a message fails?
If the route refuses the hand-off, the charge is reversed at once and the reply says failed with a cost of zero. If a carrier receipt later reports it undelivered, sms.failed fires and the message is refunded.

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.