Accept Card Payments over the Phone with Twilio
When a caller reads a card number over the phone and Twilio collects it with <Pay>, Twilio sends the card to the payment connector URL you configured. If that URL points at your own servers, the card number, expiration date and security code reach your systems, and your servers, logs and databases are in PCI DSS scope.
This guide points the connector at a Basis Theory Pre-Configured Proxy instead. A code request transform verifies Twilio's credentials, tokenizes the card, and either answers Twilio directly or forwards only the token to your API. The card never reaches your systems.
You can finish the payment in two places. In the transform, you call your payment processor yourself and answer Twilio from the Proxy. In your backend, the Proxy forwards the token to your API and your API completes the payment, for example by invoking a Reactor with a token expression. Both start with the setup in this guide.
In the first pattern, the transform answers Twilio:
In the second pattern, your backend completes the payment:
Getting Started
To get started, you will need to create a Basis Theory Account and a TEST Tenant.
Provisioning Resources
You need one Management Application and one Pre-Configured Proxy. The Proxy runs your transform, so it needs no other Basis Theory resources.
Management Application
You will need a Management Application to provision resources. Click here to create one using the Basis Theory Customer Portal.
This will create an application with the following Access Controls:
- Permissions:
proxy:create,proxy:read,proxy:update
key from the created Management Application as it will be used later in this guide.Pre-Configured Proxy
The Proxy receives every request the Twilio connector sends. Its transform does three things:
- Compares the
Authorizationheader with the connector's username and password. Twilio sends them as HTTP Basic authentication. - Tokenizes the card from the JSON body. The
methodfield tells you the transaction type:tokenizeorcharge. - Answers Twilio directly for
tokenizerequests, and forwards the token (never the card) to your API forchargerequests. Any othermethodgets anunsupported_methoderror and is never forwarded.
Twilio expects a JSON response with token_id for tokenize requests, charge_id for charge requests, and error_code and error_message set to null on success. Your API returns the charge_id response, so the Proxy forwards it back to Twilio unchanged.
Save the transform as transform.js. It uses a Node.js runtime image and reads the connector credentials from the Proxy configuration:
const { timingSafeEqual } = require("node:crypto");
const { BasisTheoryClient } = require("@basis-theory/node-sdk");
const reply = (statusCode, body) => ({
res: {
statusCode,
headers: { "Content-Type": "application/json" },
body,
},
});
const matches = (received, expected) => {
const a = Buffer.from(received ?? "");
const b = Buffer.from(expected);
return a.length === b.length && timingSafeEqual(a, b);
};
module.exports = async function (event) {
const { req, configuration, applicationOptions } = event;
const credentials = Buffer.from(
`${configuration.TWILIO_USERNAME}:${configuration.TWILIO_PASSWORD}`
).toString("base64");
if (!matches(req.headers.authorization, `Basic ${credentials}`)) {
return reply(401, { error: "unauthorized" });
}
const body = typeof req.body === "string" ? JSON.parse(req.body) : req.body;
if (!["tokenize", "charge"].includes(body.method)) {
return reply(200, {
charge_id: null,
error_code: "unsupported_method",
error_message: "Only tokenize and charge are supported",
});
}
const client = new BasisTheoryClient({
apiKey: applicationOptions.apiKey,
baseUrl: applicationOptions.baseUrl,
});
const year = Number(body.expiry_year);
const token = await client.tokens.create({
type: "card",
data: {
number: body.cardnumber,
cvc: body.cvv,
expiration_month: Number(body.expiry_month),
expiration_year: year < 100 ? 2000 + year : year,
},
});
if (body.method === "tokenize") {
return reply(200, {
token_id: token.id,
error_code: null,
error_message: null,
});
}
// charge: forward the token to your API, never the card
const { cardnumber, cvv, expiry_month, expiry_year, ...rest } = body;
return {
req: {
headers: {
...req.headers,
// only when you configure BACKEND_SHARED_SECRET (Pattern B)
...(configuration.BACKEND_SHARED_SECRET && {
"x-backend-secret": configuration.BACKEND_SHARED_SECRET,
}),
},
body: { ...rest, token_id: token.id },
},
};
};
The transform parses the body defensively because the Proxy only parses it into an object when the request's Content-Type is application/json. The runtime.permissions below give the transform a scoped API key that can create tokens and nothing else.
Create the Proxy with the Create Proxy API, or in the Customer Portal. This example uses jq to embed transform.js in the request:
curl 'https://api.basistheory.com/proxies' \
-X 'POST' \
-H 'BT-API-KEY: <MANAGEMENT_API_KEY>' \
-H 'Content-Type: application/json' \
--data "$(jq -n \
--rawfile code transform.js \
'{
name: "Twilio Pay",
destination_url: "<YOUR_API_URL>",
require_auth: false,
configuration: {
TWILIO_USERNAME: "<CONNECTOR_USERNAME>",
TWILIO_PASSWORD: "<CONNECTOR_PASSWORD>"
},
request_transforms: [{
type: "code",
code: $code,
options: {
runtime: {
image: "node24",
dependencies: { "@basis-theory/node-sdk": "6.3.0" },
permissions: ["token:create"]
}
}
}]
}')"
{
"id": "47afce63-6a16-43c6-aae4-dfa8bce40069",
"key": "e29a50980ca5",
"name": "Twilio Pay",
"destination_url": "<YOUR_API_URL>",
"require_auth": false,
"state": "creating"
}
Save the Proxy id and key. A few settings in this request matter:
require_auth: falselets Twilio call the Proxy without a Basis Theory API key. The transform authenticates Twilio with the connector credentials instead.destination_urlis required even when the transform answers Twilio itself. Point it at your API, which receiveschargerequests with the token in place of the card. If you only answer from the transform, any placeholder URL works, for examplehttps://echo.basistheory.com/anything.configurationkeeps the connector credentials out of the transform code.
Basis Theory installs the transform's dependencies before the Proxy can be invoked. Poll the Get a Proxy API until state is active. Until then, requests to the Proxy return 409.
Why the Transform Doesn't Invoke a Reactor
Code running in a Proxy transform can't call the Reactor invoke endpoints, so a transform can tokenize a card but can't hand the token to a Reactor. Basis Theory rejects those calls before authentication. See the Invoke Reactors limitations. To finish the payment, call your payment processor from the transform, or forward the token to your backend and invoke the Reactor from there.
Connect Twilio
In Twilio, create a Generic Pay Connector and set its username and password to the values you stored in the Proxy configuration. For the endpoint URL, use the Proxy URL:
https://api.basistheory.com/proxy?bt-proxy-key=<PROXY_KEY>
The Proxy accepts its key in the bt-proxy-key query parameter as well as in the BT-PROXY-KEY header. If you prefer a URL on your own domain, put a custom hostname in front of the Proxy.
Two Twilio requirements affect this setup:
- Pay Connectors require PCI Mode. It applies to your whole Twilio account and can't be turned off once enabled.
- Twilio locks the connector URL when the connector goes live, so settle on the Proxy URL or custom hostname before you request go-live.
Pattern A: Charge in the Transform
In this pattern the transform calls your payment processor with the card and answers Twilio itself. Your servers aren't part of the flow.
Native Proxy forwarding doesn't fit here: a code request transform can't change the destination path, so the Proxy can't turn the connector request into a call to your processor's charge endpoint. See what a code request transform can and cannot change. The transform makes the HTTPS call itself instead, and returns the result through Skip Proxy Request.
Replace transform.js with the version below. It branches on method:
tokenizecreates a card token and returns itstoken_id.chargecalls the processor and returns itscharge_id.- Any other
method, or a missing one, returns anunsupported_methoderror without calling the processor.
Both answer with the Generic Pay Connector shape: token_id or charge_id, plus error_code and error_message, which are null on success.
const { timingSafeEqual } = require("node:crypto");
const { BasisTheoryClient } = require("@basis-theory/node-sdk");
const reply = (body) => ({
res: {
statusCode: 200,
headers: { "Content-Type": "application/json" },
body,
},
});
const matches = (received, expected) => {
const a = Buffer.from(received ?? "");
const b = Buffer.from(expected);
return a.length === b.length && timingSafeEqual(a, b);
};
module.exports = async function (event) {
const { req, configuration, applicationOptions, logger } = event;
const credentials = Buffer.from(
`${configuration.TWILIO_USERNAME}:${configuration.TWILIO_PASSWORD}`
).toString("base64");
if (!matches(req.headers.authorization, `Basic ${credentials}`)) {
return {
res: {
statusCode: 401,
headers: { "Content-Type": "application/json" },
body: { error: "unauthorized" },
},
};
}
const body = typeof req.body === "string" ? JSON.parse(req.body) : req.body;
const year = Number(body.expiry_year);
const card = {
number: body.cardnumber,
cvc: body.cvv,
expiration_month: Number(body.expiry_month),
expiration_year: year < 100 ? 2000 + year : year,
};
if (body.method === "tokenize") {
const client = new BasisTheoryClient({
apiKey: applicationOptions.apiKey,
baseUrl: applicationOptions.baseUrl,
});
const token = await client.tokens.create({ type: "card", data: card });
return reply({
token_id: token.id,
error_code: null,
error_message: null,
});
}
if (body.method !== "charge") {
return reply({
charge_id: null,
error_code: "unsupported_method",
error_message: "Only tokenize and charge are supported",
});
}
try {
const response = await fetch("<PROCESSOR_URL>", {
method: "POST",
headers: {
Authorization: `Bearer ${configuration.PROCESSOR_API_KEY}`,
"Content-Type": "application/json",
// Twilio retries with the same transaction_id, so the processor can
// recognize a repeated charge
"Idempotency-Key": body.transaction_id,
},
body: JSON.stringify({
amount: body.amount,
currency: body.currency_code,
card,
}),
// answer before Twilio's 10 second timeout
signal: AbortSignal.timeout(8000),
});
const result = await response.json();
if (!response.ok) {
logger.warn("processor declined the charge", { status: response.status });
return reply({
charge_id: null,
error_code: String(result.code ?? response.status),
error_message: result.message ?? "The processor could not complete the charge",
});
}
return reply({
charge_id: result.id,
error_code: null,
error_message: null,
});
} catch (error) {
logger.error("processor call failed", { name: error.name });
return reply({
charge_id: null,
error_code: "processor_unavailable",
error_message: "The processor did not respond",
});
}
};
Replace <PROCESSOR_URL> and the request body with what your processor's charge API expects. The transform only needs a processor that accepts a card in a request body and, ideally, an idempotency key.
Update the Proxy with the new transform and the processor credentials, using the Patch Proxy API or the Customer Portal. Add the processor credentials next to the connector ones in configuration:
{
"configuration": {
"TWILIO_USERNAME": "<CONNECTOR_USERNAME>",
"TWILIO_PASSWORD": "<CONNECTOR_PASSWORD>",
"PROCESSOR_API_KEY": "<PROCESSOR_API_KEY>"
}
}
A few details matter for this pattern:
destination_urlis still required, even though nochargerequest ever reaches it. Use a placeholder such ashttps://echo.basistheory.com/anything. Nothing is sent to it, because the transform answers every request.- The transform shares the runtime timeout with every synchronous transform: 10 to 30 seconds, 10 by default. Twilio is stricter. It waits 10 seconds for the connector to answer, then retries with the same
transaction_id. Keep the whole transform, the processor call or the token creation included, well inside 10 seconds. - Send
transaction_idto the processor as its idempotency key, as the example does. The transform keeps no state, so it can't recognize a repeated request on its own. The processor has to. If your processor has no idempotency keys, use Pattern B, where your backend finishes the payment, and record eachtransaction_idin your backend. - Proxy requests don't support the
BT-IDEMPOTENCY-KEYheader, so the key goes on the processor call, not on the request to the Proxy. - In Pattern A, a
chargecreates no token, so a retriedchargecreates none either. A retriedtokenizecan create another card token, because the transform keeps no state. Only the charge is protected by the idempotency key.
Pattern B: Process in Your Backend
In this pattern the Proxy tokenizes the card and forwards the token to your API. Your backend completes the payment by invoking a Reactor with a token expression, then returns the result to Twilio through the Proxy response.
The transform.js from Pre-Configured Proxy already does the Proxy's part. For tokenize requests it answers Twilio directly. For charge requests it removes the card fields and sends the rest of the connector request, with a token_id added, to the Proxy destination_url. Set destination_url to your API endpoint.
Your backend invokes the Reactor, because a Reactor can't be invoked from the transform. Invoking one needs a Basis Theory API key, and a transform can't call the invoke endpoints. See the Invoke Reactors limitations. Twilio and IVRs can't call a Reactor directly either, because invoking one needs a BT-API-KEY. They call a Pre-Configured Proxy instead.
The handler below receives the forwarded charge request, invokes the Reactor with the token expression, and answers in the Generic Pay Connector shape. It records each transaction_id first, so a retry gets the stored result instead of a second charge:
const { timingSafeEqual } = require("node:crypto");
const { BasisTheoryClient } = require("@basis-theory/node-sdk");
const client = new BasisTheoryClient({ apiKey: process.env.BT_API_KEY });
// payments is your own store, keyed by transaction_id
app.post("/twilio/charge", async (req, res) => {
const received = Buffer.from(req.get("x-backend-secret") ?? "");
const expected = Buffer.from(process.env.BACKEND_SHARED_SECRET);
if (received.length !== expected.length || !timingSafeEqual(received, expected)) {
return res.status(401).json({ error: "unauthorized" });
}
const { transaction_id, token_id, amount, currency_code } = req.body;
const existing = await payments.find(transaction_id);
if (existing) {
return res.status(200).json(existing.response);
}
const created = await payments.create(transaction_id);
if (!created) {
// another attempt with this transaction_id is still running
return res.status(409).json({ error: "in progress" });
}
try {
const result = await client.reactors.react(process.env.CHARGE_REACTOR_ID, {
args: {
card: `{{${token_id}}}`,
amount,
currency: currency_code,
idempotency_key: transaction_id,
},
});
// a success, or a decline the Reactor returns, is final: save it
const response = result.raw.charge_id
? { charge_id: result.raw.charge_id, error_code: null, error_message: null }
: {
charge_id: null,
error_code: result.raw.error_code,
error_message: result.raw.error_message,
};
await payments.save(transaction_id, response);
return res.status(200).json(response);
} catch (error) {
// an error or timeout leaves the outcome unknown: don't save an answer
await payments.release(transaction_id);
return res.status(200).json({
charge_id: null,
error_code: "processor_unavailable",
error_message: "The payment could not be completed",
});
}
});
The Reactor code receives card with the real card values and calls your payment processor, passing idempotency_key along. It returns the processor's charge_id in raw, which is what the handler reads from result.raw. For a clear decline, have it return error_code and error_message in raw instead. See Invoke Reactors for the request and response format, and replace the processor-specific values with what your processor expects. The 409 for an attempt that is still running is a placeholder: how Twilio treats a non-200 answer isn't something this guide covers, so return whatever your integration needs for that case, and make sure a later attempt gets the stored result.
The handler saves only a final outcome. If the Reactor call throws or times out, you can't tell whether the processor charged the card. The handler calls payments.release (a method on your own store that clears the in-progress record) and answers without saving, so Twilio's retry calls the Reactor again with the same idempotency_key and the processor returns the original result. Saving processor_unavailable would replay that failure on every retry.
The handler checks the X-Backend-Secret header before it touches any payment state. The transform adds the header from BACKEND_SHARED_SECRET in the Proxy configuration, so set the same value in your API's environment and add it next to the connector credentials:
{
"configuration": {
"TWILIO_USERNAME": "<CONNECTOR_USERNAME>",
"TWILIO_PASSWORD": "<CONNECTOR_PASSWORD>",
"BACKEND_SHARED_SECRET": "<RANDOM_SECRET>"
}
}
The Proxy returns your backend's response to Twilio unchanged, so it must be a JSON body with charge_id, error_code and error_message, as described in Pre-Configured Proxy.
Key Considerations
Timeout Budget
Twilio waits 10 seconds for the connector to answer. If it doesn't, Twilio retries up to 5 times with the same transaction_id. Plan for 10 seconds per attempt, not for the Proxy's own limits:
- The Proxy destination timeout is 25 seconds by default and 55 seconds at most. It is longer than Twilio's wait, so a slow destination doesn't stop Twilio from retrying while the first attempt is still running.
- Code that runs in a Basis Theory runtime, a Reactor or a transform, has a runtime timeout of 10 to 30 seconds, 10 by default.
- In Pattern B, tokenization, your backend, the Reactor and the processor all fit inside the same 10 seconds. In Pattern A, the transform has the whole budget to itself.
Treat every attempt as if it could overlap with the previous one.
Idempotency
Twilio sends the same transaction_id on every retry of a request, and describes it as an idempotency token. Use it as the key for the payment:
- Pass
transaction_idto your payment processor as its idempotency key. In Pattern A that is the only protection, because the transform keeps no state. - In Pattern B, record each
transaction_idin your backend, as the handler above does. Return the storedcharge_idortoken_idfor a repeated one. - Proxy requests don't support the
BT-IDEMPOTENCY-KEYheader (see Idempotency), so the Proxy can't dedupe Twilio's retries. The Reactor invoke is aPOSTand accepts the header, but the key that protects the payment belongs on the processor call. - A retry can create another card token. In Pattern A only
tokenizerequests create a token, so a retriedtokenizecan create another one. In Pattern B the transform tokenizes the card on every request, so a retriedchargecan too. Thetransaction_idprotects the payment, not the token count.
Using <Gather>
<Pay> is the main path for card payments, but you can also collect digits with <Gather>. The Proxy URL goes in the verb's action attribute. Twilio sends the collected Digits to it as a form-encoded request, and each <Gather> submits its own request. Tokenize the digits in the transform and keep only the token in your call state.
<Gather> differs from <Pay> in two ways:
- The
actionendpoint returns TwiML, so there is no Generic Pay Connector response shape. Return a response with a TwiML body and aContent-Typeoftext/xml. - Twilio doesn't use Basic authentication here. It signs the request in the
X-Twilio-Signatureheader, so the transform validates that instead of theAuthorizationheader.
To validate the signature, take the full URL Twilio called, query string included, so the bt-proxy-key parameter is part of it. Sort the POST parameters by name, append each name and value to the URL with no delimiters, compute an HMAC-SHA1 with your Twilio Auth Token as the key, and compare the base64 result with the header:
const { createHmac, timingSafeEqual } = require("node:crypto");
const isFromTwilio = (req, configuration) => {
const params =
typeof req.body === "string"
? Object.fromEntries(new URLSearchParams(req.body))
: req.body;
// the exact URL Twilio called, for example the Proxy URL with ?bt-proxy-key=...
const signed = Object.keys(params)
.sort()
.reduce((url, name) => url + name + params[name], configuration.TWILIO_WEBHOOK_URL);
const expected = createHmac("sha1", configuration.TWILIO_AUTH_TOKEN)
.update(signed)
.digest("base64");
const received = req.headers["x-twilio-signature"] ?? "";
return (
received.length === expected.length &&
timingSafeEqual(Buffer.from(received), Buffer.from(expected))
);
};
Store the URL and the Auth Token in the Proxy configuration, as TWILIO_WEBHOOK_URL and TWILIO_AUTH_TOKEN. The URL must match what Twilio called character for character, including the query string and any trailing slash. Include every parameter Twilio sends, not a fixed list. For production, Twilio recommends its SDK's request validator.