Skip to navigation

Take payments on a call

Collect a card on the keypad and charge it through your own processor
View as MarkdownOpen in Claude

Your app can take a card payment in the middle of a call. The caller types the card details on the keypad, and SignalWire hands them to a payment connector you host, which charges the card through your payment processor. Start by charging a test card on a call to your own phone, then charge a card from SWML or Relay, save a card for later payments, customize the prompts, handle the result, stop collection from your code, and take a payment from an AI agent.

Pick the right product for taking payments

Payments run inside a live call, from the code that controls that call.

FunctionSWMLWebSocket (Relay)RESTBrowser SDKCall Flow Builder
Charge a card during a call
Save a card as a token for later payments
Customize the prompts the caller hears
Stop collecting card details from your code
Get the payment result in your own code, without a webhook
Send payment progress to a status webhook
  • SWML is the document that describes how the call should flow. Its pay method collects the card and sets variables the rest of the document can branch on. Write it with the SWML builders in the Server SDKs, or by hand.
  • WebSocket (Relay) is a Relay client in the Server SDKs. It holds a WebSocket connection to a call in progress, starts payment collection with call.pay, and receives the result as an event in your code.
  • The REST Calling API places calls and delivers SWML to them. A dial request that carries a SWML document with pay takes a payment, as the first run on this page shows; the payment itself runs in SWML.
  • The Browser SDK puts a person on a call from a web page. Payment collection runs in the SWML or Relay code that handles the call.
  • Call Flow Builder draws call flows on a canvas without code. Payment flows are built in SWML or Relay.

An AI agent built with the Server SDKs generates SWML, so it takes payments the same way; Take a payment from an AI agent shows how.

Prepare for taking payments

Have these values ready:

  • Your Space URL, such as <YOUR_SPACE>.signalwire.com.
  • Your Project ID and API token from the Dashboard’s API credentials page. Enable the token’s Voice permission for the Calling API.
  • A voice-capable phone number purchased in your Space or a verified caller ID.
  • A phone you can answer, with a keypad.
  • Your project’s Signing Key. In the Dashboard, open API Credentials, find Signing Key, and select Show. Verify webhook signature covers how SignalWire uses it.
  • A machine that can run a small server, and a tunnel such as ngrok that gives it a public https:// URL.

Your payment connector is an HTTPS endpoint you host. It receives the card details SignalWire collects, charges the card through your payment processor, and replies with the outcome. You build one in Build a payment connector.

Payment connector URLs must use https://

SignalWire sends card details to your payment connector over HTTPS only, and rejects a payment_connector_url that doesn’t start with https:// before it collects anything. During development, put a TLS tunnel in front of your local server, as Give the connector a public URL shows.

Your payment connector receives full card data

SignalWire sends the full card number and security code to your connector, because your processor needs them to charge the card. That puts the connector in scope for the Payment Card Industry Data Security Standard (PCI DSS). Never log or store full card data, and read Payments and PCI compliance before you take a real payment.

Trial projects only call and receive calls from verified numbers

A trial project only places calls to and receives calls from numbers you’ve purchased or verified, and can’t call internationally. Verify the phone you’ll test with before the first run.

Replace these values in the samples you run:

ValueReplace with
<YOUR_SPACE>Your Space’s subdomain in <YOUR_SPACE>.signalwire.com
<YOUR_PROJECT_ID>Your Project ID
<YOUR_API_TOKEN>Your API token with the Voice permission, used only in server code
<YOUR_CALLER_ID>Your SignalWire phone number, or a verified caller ID, in E.164 format
<YOUR_DESTINATION>The phone you’ll answer, in E.164 format
<YOUR_PAYMENT_CONNECTOR_URL>The public https:// URL of your payment connector, ending in / if it has no path. Use the same URL in payment_connector_url and in your connector, because SignalWire signs requests against it, minus any user:password@ credentials.
<YOUR_SIGNING_KEY>Your project’s Signing Key, used only in your payment connector
<YOUR_STATUS_WEBHOOK_URL>An HTTPS endpoint you control that receives payment progress

How taking a payment works

A payment starts when your SWML document or Relay code runs pay on a live call, and runs in four parts:

  1. SignalWire prompts the caller for each card detail in turn: the card number, the expiration date, the security code, and the postal code. The caller types each one on the keypad and presses # to finish an entry, or * to cancel the payment.
  2. SignalWire checks each entry as it arrives, such as whether the card number is valid and its type is one you accept. When an entry fails the check or the caller enters nothing, SignalWire asks again, giving the caller max_attempts tries in all.
  3. SignalWire sends the card details in a signed HTTPS request to your payment connector. Your connector charges the card, or saves it, through your payment processor and replies with the outcome.
  4. SignalWire plays a closing prompt to the caller and hands the result to your code: as the pay_result variable in SWML, or as the final calling.call.pay event in Relay.

The diagram follows one payment from the first prompt to the result.

Your SWML or Relay code starts pay. SignalWire prompts the caller for each card detail, and the caller enters the digits on the keypad, pressing pound to finish an entry or star to cancel. SignalWire checks each entry, then sends the card data and amount in a signed HTTPS POST to your payment connector. Your connector charges or saves the card through your payment processor, which returns a charge, a token, or a decline. Your connector replies to SignalWire with charge_id or token_id, or an error. SignalWire plays a closing prompt to the caller and hands the result to your code.

Build a payment connector

SignalWire sends your connector one HTTPS POST per payment, with a JSON body. Your connector checks the signature, charges the card or saves it through your payment processor, and replies.

This is the body for the Bayview Taxi fare when pay also passes a ride ID in parameters, as in Payment options. A test card’s details arrive in full:

JSON
{
"transaction_id": "b6a2c3e1-4f0d-4c8e-9a51-2d7f3e8c1a90",
"method": "credit-card",
"cardnumber": "4111111111111111",
"cvv": "123",
"description": "Bayview Taxi fare",
"chargeAmount": "24.50",
"token_type": "reusable",
"expiry_month": "12",
"expiry_year": "30",
"currency_code": "usd",
"parameters": [
{ "ride_id": "R-1042" }
]
}
FieldWhat it holds
transaction_idA unique ID for this payment
methodThe payment method, credit-card
cardnumberThe full card number
cvvThe security code
postal_codeThe postal code, left out when postal_code on pay is "false"
expiry_month, expiry_yearThe expiration date, two digits each
descriptionThe description you set on pay, left out when you set none
chargeAmountThe amount to charge. A zero amount means save the card instead of charging it.
token_typeThe token_type you set on pay, reusable by default
currency_codeThe currency, usd by default
parametersThe custom parameters you set on pay, each as a one-key object, left out when you set none

Reply with HTTP 200 and a JSON body. For a charge, return the processor’s charge ID in charge_id. For a zero amount, return the saved card’s token in token_id. To decline, return error_code and error_message with no ID. The caller still hears SignalWire’s payment-completed prompt for any 200 reply, so override the payment-completed prompt or follow it with your own message when the result isn’t success.

{
"charge_id": "ch_3f9a1c2b7d4e8f60",
"error_code": null,
"error_message": null
}

SignalWire counts the payment as a success only when the reply is HTTP 200 with a charge_id for a charge, or a token_id for a zero amount, and no error. Any other reply is a decline, including a non-200 status and a token_id for a nonzero amount.

SignalWire signs each request with your project’s Signing Key. The X-SignalWire-Signature header holds the lowercase hex HMAC-SHA1 of the connector URL you passed in payment_connector_url, followed by the raw request body. If that URL carries credentials, as https://user:password@pay.example.com/ does, SignalWire removes them before signing and sends them as HTTP Basic authentication instead, so the signed URL is https://pay.example.com/. SignalWire also normalizes the URL before signing: a URL without a path gets a trailing /, the scheme is lowercased, and . and .. path segments are resolved. An X-SignalWire-SHA256-Signature header carries the same value computed with HMAC-SHA256. Compute the signature yourself and reject any request whose header doesn’t match. The samples check it with the Server SDKs’ webhook signature helper. Both compare against the URL you passed, because a tunnel or proxy can change the URL your server sees.

These connectors check the signature, log the last four digits, and reply with a new ID in place of a real processor call. Replace the ID with your processor’s call where the comment says so.

# Install: python -m pip install signalwire-sdk flask
# Save as payment_connector.py and run: python payment_connector.py
import json
import uuid
from flask import Flask, jsonify, request
from signalwire.core.security import validate_webhook_signature
SIGNING_KEY = "<YOUR_SIGNING_KEY>"
# The URL you pass as payment_connector_url, without any user:password@ part.
# SignalWire signs that URL, not the one a tunnel or proxy hands your server.
CONNECTOR_URL = "<YOUR_PAYMENT_CONNECTOR_URL>"
app = Flask(__name__)
@app.post("/")
def charge():
raw_body = request.get_data(as_text=True)
signature = request.headers.get("X-SignalWire-Signature", "")
if not validate_webhook_signature(SIGNING_KEY, signature, CONNECTOR_URL, raw_body):
return jsonify(error="invalid signature"), 403
payment = json.loads(raw_body)
amount = payment["chargeAmount"]
# parameters arrives as a list of one-key objects: [{"ride_id": "R-1042"}]
extra = {k: v for item in payment.get("parameters", []) for k, v in item.items()}
# Log the last four digits only. Never log or store the full card number or the security code.
print(
f"{payment['transaction_id']}: card ending {payment['cardnumber'][-4:]}, "
f"{amount} {payment['currency_code']}, {payment.get('description', '')} {extra}"
)
# Call your payment processor here with cardnumber, cvv, expiry_month,
# expiry_year, and postal_code. If it declines, reply with its code and
# message instead of an ID:
# {"charge_id": None, "error_code": "card_declined", "error_message": "Card declined"}
if float(amount) == 0:
# A zero amount saves the card: reply with a token instead of a charge.
return jsonify(token_id=f"tok_{uuid.uuid4().hex[:16]}", error_code=None, error_message=None)
return jsonify(charge_id=f"ch_{uuid.uuid4().hex[:16]}", error_code=None, error_message=None)
if __name__ == "__main__":
app.run(port=8080)

Take your first payment

Charge the Bayview Taxi fare to a test card on a call to your own phone. The connector from Build a payment connector stands in for your processor, so no real card is charged.

1

Give the connector a public URL

In a terminal, put a tunnel in front of port 8080:

ngrok http 8080

ngrok prints an https:// Forwarding URL. Add a trailing / to it, as in https://<id>.ngrok-free.app/, and use that as your <YOUR_PAYMENT_CONNECTOR_URL> in the connector and in the call. The signature covers the URL, and SignalWire signs a URL with no path as if it ended in /. Keep the tunnel running while you test; a new tunnel usually means a new hostname.

2

Run the payment connector

Fill in <YOUR_SIGNING_KEY> and <YOUR_PAYMENT_CONNECTOR_URL> in the connector you saved from Build a payment connector, and start it in a second terminal with the run command in its header comment. It listens on port 8080 and prints a line for each payment.

3

Place the call

Send a REST dial request with a SWML document in swml. When you answer, the document reads the fare, runs pay, and then reads the result back to you from the pay_result variable.

# Install: python -m pip install signalwire-sdk
# Save as first_payment.py and run: python first_payment.py
from signalwire import SWMLBuilder, SWMLService
from signalwire.rest import RestClient
client = RestClient(
project="<YOUR_PROJECT_ID>",
token="<YOUR_API_TOKEN>",
host="<YOUR_SPACE>.signalwire.com",
)
swml = (
SWMLBuilder(SWMLService(name="first-payment"))
.say("Thanks for riding with Bayview Taxi. Your fare is 24 dollars and 50 cents.")
.pay(
payment_connector_url="<YOUR_PAYMENT_CONNECTOR_URL>",
charge_amount="24.50",
description="Bayview Taxi fare",
)
.say("The payment result is ${pay_result}.")
.build()
)
call = client.calling.dial(
from_="<YOUR_CALLER_ID>",
to="<YOUR_DESTINATION>",
swml=swml,
)
print(call["id"])

The cURL example sends the dial command to Call commands.

The REST API returns a call id and status queued. This confirms that SignalWire accepted the request; the call hasn’t necessarily rung or been answered yet. Save the id to identify this call.

Response
{
"billing_ms": null,
"charge": 0,
"charge_details": [
{
"charge": 0.004,
"description": "Outbound Voice"
}
],
"created_at": "2024-05-06T12:20:00Z",
"direction": "outbound-api",
"duration": null,
"duration_ms": null,
"from": "+12069708643",
"id": "0e9c80d7-a149-4917-892d-420043709f45",
"parent_id": null,
"qos_metrics": null,
"source": "realtime_api",
"status": "queued",
"to": "+15550198765",
"type": "relay_pstn_call",
"url": null
}
4

Answer and pay on the keypad

Answer your phone. After the fare, SignalWire asks for each card detail in turn. Enter these on the keypad, pressing # after each one:

  • Card number 4111111111111111, a test number that passes SignalWire’s card number check.
  • An expiration date in the future, as four digits, month then year, such as 1230.
  • Any three-digit security code.
  • Any postal code.

You hear “The payment result is success.” The connector prints a line such as ...: card ending 1111, 24.50 usd, Bayview Taxi fare {}, and the Relay program also prints Payment result: success.

If you hear a different result, find it here:

  • internal-error: your connector, or the tunnel in front of it, didn’t reply with a valid ID. If the connector printed nothing, check that the tunnel and the connector are both running and that <YOUR_PAYMENT_CONNECTOR_URL> is the tunnel’s current https:// URL. If they are, the connector rejected the signature: check <YOUR_SIGNING_KEY>, and that the connector’s <YOUR_PAYMENT_CONNECTOR_URL> ends in / and matches the URL in the call exactly.
  • payment-connector-error: SignalWire got no response from that URL, because the host couldn’t be reached or your connector took too long to reply.
  • too-many-failed-attempts: an entry failed SignalWire’s check. Re-enter the test card number and a future expiration date.

If the call ends before anything plays, or the Relay program stops at call.pay with an error instead of printing a result, check that <YOUR_PAYMENT_CONNECTOR_URL> starts with https://. SignalWire runs a SWML document or a call.pay request only when its connector URL does. The Relay program stops without hanging up when call.pay fails, so end the call on your phone if it’s still connected.

Charge a card during a call

To charge a card, run pay with your connector’s URL and the amount. charge_amount is a string with the decimal amount, such as "24.50", in the currency set by currency (usd unless you set another). description reaches your connector unchanged, for your own records.

Charge a card via SWML

This document reads the fare, charges it, and branches on pay_result with switch to thank the rider or promise a callback. Deliver it the same way as in the first run, or any other way your app serves SWML.

# Install: python -m pip install signalwire-sdk
# Save as charge_fare_swml.py and run: python charge_fare_swml.py
import json
from signalwire import SWMLBuilder, SWMLService
swml = (
SWMLBuilder(SWMLService(name="charge-fare"))
.answer()
.say("Thanks for riding with Bayview Taxi. Your fare is 24 dollars and 50 cents.")
.pay(
payment_connector_url="<YOUR_PAYMENT_CONNECTOR_URL>",
charge_amount="24.50",
description="Bayview Taxi fare",
)
.switch(
variable="pay_result",
case={
"success": [{"play": {"url": "say:Your payment went through. Thanks for riding with Bayview Taxi."}}],
},
default=[{"play": {"url": "say:We couldn't take your payment. A dispatcher will call you back."}}],
)
.hangup()
.build()
)
print(json.dumps(swml, indent=2))

Charge a card via WebSocket (Relay)

This call handler answers calls on the default context, charges the fare, and reads the final calling.call.pay event. That event carries result, plus the masked card number and the connector’s charge_id as payment_confirmation_code, so the handler waits for it rather than for call.pay to return.

# Install: python -m pip install signalwire-sdk
# Save as charge_fare_relay.py and run: python charge_fare_relay.py
import asyncio
from signalwire.relay import RelayClient
client = RelayClient(
project="<YOUR_PROJECT_ID>",
token="<YOUR_API_TOKEN>",
contexts=["default"],
)
def is_pay_result(event):
# Progress events name the step in "for"; the last event carries "result".
return "result" in event.params
@client.on_call
async def handle_call(call):
await call.answer()
intro = await call.play([{
"type": "tts",
"params": {"text": "Thanks for riding with Bayview Taxi. Your fare is 24 dollars and 50 cents."},
}])
await intro.wait()
finished = asyncio.create_task(call.wait_for("calling.call.pay", predicate=is_pay_result))
await call.pay(
payment_connector_url="<YOUR_PAYMENT_CONNECTOR_URL>",
charge_amount="24.50",
description="Bayview Taxi fare",
)
p = (await finished).params
if p["result"] == "success":
print(f"Charged {p['payment_card_type']} {p['payment_card_number']}: {p['payment_confirmation_code']}")
text = "Your payment went through. Thanks for riding with Bayview Taxi."
else:
print(f"Payment failed: {p['result']} {p.get('payment_error', '')}")
text = "We couldn't take your payment. A dispatcher will call you back."
async def hang_up_after_playback(_event):
if call.state != "ended":
await call.hangup()
await call.play([{"type": "tts", "params": {"text": text}}], on_completed=hang_up_after_playback)
await call.wait_for_ended()
client.run()

On a successful charge, the handler prints a line such as Charged visa ************1111: ch_3f9a1c2b7d4e8f60. When your connector declines the card, it prints Payment failed: internal-error card-declined.

Save a card for later payments

To save a card without charging it, set charge_amount to "0". SignalWire collects the card the same way and sends your connector a zero chargeAmount. Your connector saves the card with your processor and replies with token_id, and SignalWire returns that token as payment_token. Store it with the customer’s account to charge the card later through your processor.

charge_amount defaults to "0.00", so a pay with no amount also saves the card. token_type tells your connector how the token will be used: reusable (the default) for a card on file, or one-time.

Save a card via SWML

# Install: python -m pip install signalwire-sdk
# Save as save_card_swml.py and run: python save_card_swml.py
import json
from signalwire import SWMLBuilder, SWMLService
swml = (
SWMLBuilder(SWMLService(name="save-card"))
.answer()
.say("Bayview Taxi can keep a card on file for your rides.")
.pay(
payment_connector_url="<YOUR_PAYMENT_CONNECTOR_URL>",
charge_amount="0",
token_type="reusable",
description="Bayview Taxi card on file",
)
.switch(
variable="pay_result",
case={"success": [{"play": {"url": "say:Your card is saved for future rides."}}]},
default=[{"play": {"url": "say:We couldn't save your card. A dispatcher will call you back."}}],
)
.hangup()
.build()
)
print(json.dumps(swml, indent=2))

Save a card via WebSocket (Relay)

This handler extends Charge a card via WebSocket (Relay) with a zero amount, and prints the token from payment_token.

# Install: python -m pip install signalwire-sdk
# Save as save_card_relay.py and run: python save_card_relay.py
import asyncio
from signalwire.relay import RelayClient
client = RelayClient(
project="<YOUR_PROJECT_ID>",
token="<YOUR_API_TOKEN>",
contexts=["default"],
)
def is_pay_result(event):
# Progress events name the step in "for"; the last event carries "result".
return "result" in event.params
@client.on_call
async def handle_call(call):
await call.answer()
intro = await call.play([{
"type": "tts",
"params": {"text": "Bayview Taxi can keep a card on file for your rides."},
}])
await intro.wait()
finished = asyncio.create_task(call.wait_for("calling.call.pay", predicate=is_pay_result))
await call.pay(
payment_connector_url="<YOUR_PAYMENT_CONNECTOR_URL>",
charge_amount="0",
token_type="reusable",
description="Bayview Taxi card on file",
)
p = (await finished).params
if p["result"] == "success":
# Store payment_token with the rider's account to charge the card later.
print(f"Saved {p['payment_card_type']} {p['payment_card_number']} as {p['payment_token']}")
text = "Your card is saved for future rides."
else:
print(f"Card not saved: {p['result']} {p.get('payment_error', '')}")
text = "We couldn't save your card. A dispatcher will call you back."
async def hang_up_after_playback(_event):
if call.state != "ended":
await call.hangup()
await call.play([{"type": "tts", "params": {"text": text}}], on_completed=hang_up_after_playback)
await call.wait_for_ended()
client.run()

Payment options: prompts, card types, security code, and postal code

Every option has a default, so pay needs only payment_connector_url. Set these to change what SignalWire collects and how it asks:

OptionDefaultWhat it does
valid_card_types"visa mastercard amex"The card types you accept, space-separated. Also accepts maestro, discover, jcb, and diners-club.
security_code"true"Whether to ask for the security code. Takes the string "true" or "false".
postal_code"true"Whether to ask for the postal code. Takes "true" or "false", or a postal code you already have, which SignalWire sends to your connector without asking the caller.
max_attempts1How many tries the caller gets at each entry, from 1 to 3. An entry that fails the check or times out uses a try. Values outside that range fall back to 1.
timeout5How many seconds SignalWire waits for the caller’s next key press before it checks the entry. The minimum is 3. Lower values fall back to 5.
charge_amount"0.00"The amount to charge. Zero saves the card.
currencyusdThe currency of charge_amount.
token_typereusablereusable or one-time, passed to your connector.
descriptionnoneA description passed to your connector.
parametersnoneCustom name and value pairs passed to your connector, which receives each as a one-key object such as {"ride_id": "R-1042"}.
promptsSignalWire’s promptsYour own prompts for any step of the payment.

Each entry in prompts replaces SignalWire’s prompt for one step, named in for: payment-card-number, expiration-date, security-code, postal-code, payment-processing, payment-completed, payment-failed, or payment-canceled. Its actions list what to play: a Say action speaks its phrase as text-to-speech, and a Play action plays the audio file at the URL in its phrase. Narrow a prompt to one situation with error_type, a space-separated list of errors such as invalid-card-number invalid-card-type or timeout; with card_type; or with attempt, a space-separated list of attempt numbers such as "2 3". Steps you don’t give a prompt keep SignalWire’s.

When several prompts match, SignalWire plays the most specific one, counting its own prompts too. A prompt whose error_type matches the current error outranks one whose card_type matches the card, which outranks a prompt with neither, and your prompt wins a tie with SignalWire’s. SignalWire has its own prompt for every retry after a timeout or an invalid entry, so a prompt without error_type replaces SignalWire’s only on the first try. To replace a retry prompt too, give your prompt the matching error_type. The security code of an American Express card has its own prompts as well, so a security code prompt replaces them only when its card_type includes amex.

The Bayview Taxi fare below accepts Visa and Mastercard only, skips the postal code, gives the caller three tries and ten seconds per entry, and has three custom prompts. The second card number prompt names timeout and both invalid-entry errors, so the caller hears it on every retry of the card number. The fare passes the ride’s ID to the connector in parameters.

Set payment options via SWML

# Install: python -m pip install signalwire-sdk
# Save as fare_options_swml.py and run: python fare_options_swml.py
import json
from signalwire import SWMLBuilder, SWMLService
swml = (
SWMLBuilder(SWMLService(name="fare-options"))
.answer()
.pay(
payment_connector_url="<YOUR_PAYMENT_CONNECTOR_URL>",
charge_amount="24.50",
description="Bayview Taxi fare",
valid_card_types="visa mastercard",
postal_code="false",
max_attempts=3,
timeout=10,
prompts=[
{
"for": "payment-card-number",
"actions": [{"type": "Say", "phrase": "Enter your card number, then press pound."}],
},
{
"for": "payment-card-number",
"error_type": "timeout invalid-card-number invalid-card-type",
"actions": [{
"type": "Say",
"phrase": "Bayview Taxi takes Visa and Mastercard. Enter the card number again, then press pound.",
}],
},
{
"for": "payment-processing",
"actions": [{"type": "Say", "phrase": "One moment while we charge your fare."}],
},
],
parameters=[{"name": "ride_id", "value": "R-1042"}],
)
.say("The payment result is ${pay_result}.")
.hangup()
.build()
)
print(json.dumps(swml, indent=2))

Set payment options via WebSocket (Relay)

The Relay client takes every option as a string, including max_attempts and timeout. This handler extends Charge a card via WebSocket (Relay) with the same options.

# Install: python -m pip install signalwire-sdk
# Save as fare_options_relay.py and run: python fare_options_relay.py
import asyncio
from signalwire.relay import RelayClient
client = RelayClient(
project="<YOUR_PROJECT_ID>",
token="<YOUR_API_TOKEN>",
contexts=["default"],
)
def is_pay_result(event):
# Progress events name the step in "for"; the last event carries "result".
return "result" in event.params
@client.on_call
async def handle_call(call):
await call.answer()
intro = await call.play([{
"type": "tts",
"params": {"text": "Thanks for riding with Bayview Taxi. Your fare is 24 dollars and 50 cents."},
}])
await intro.wait()
finished = asyncio.create_task(call.wait_for("calling.call.pay", predicate=is_pay_result))
await call.pay(
payment_connector_url="<YOUR_PAYMENT_CONNECTOR_URL>",
charge_amount="24.50",
description="Bayview Taxi fare",
valid_card_types="visa mastercard",
postal_code="false",
max_attempts="3",
timeout="10",
prompts=[
{
"for": "payment-card-number",
"actions": [{"type": "Say", "phrase": "Enter your card number, then press pound."}],
},
{
"for": "payment-card-number",
"error_type": "timeout invalid-card-number invalid-card-type",
"actions": [{
"type": "Say",
"phrase": "Bayview Taxi takes Visa and Mastercard. Enter the card number again, then press pound.",
}],
},
{
"for": "payment-processing",
"actions": [{"type": "Say", "phrase": "One moment while we charge your fare."}],
},
],
parameters=[{"name": "ride_id", "value": "R-1042"}],
)
p = (await finished).params
if p["result"] == "success":
print(f"Charged {p['payment_card_type']} {p['payment_card_number']}: {p['payment_confirmation_code']}")
text = "Your payment went through. Thanks for riding with Bayview Taxi."
else:
print(f"Payment failed: {p['result']} {p.get('payment_error', '')}")
text = "We couldn't take your payment. A dispatcher will call you back."
async def hang_up_after_playback(_event):
if call.state != "ended":
await call.hangup()
await call.play([{"type": "tts", "params": {"text": text}}], on_completed=hang_up_after_playback)
await call.wait_for_ended()
client.run()

Skip the security code via SWML

To take a payment without the security code, set security_code to the string "false". The SWML builders in the Server SDKs type security_code as a boolean, so these builder samples build the document with validation on, then set the string on the built pay verb. In the Relay client, set the security code option to "false" like any other option.

# Install: python -m pip install signalwire-sdk
# Save as skip_security_code_swml.py and run: python skip_security_code_swml.py
import json
from signalwire import SWMLBuilder, SWMLService
swml = (
SWMLBuilder(SWMLService(name="skip-security-code"))
.answer()
.pay(
payment_connector_url="<YOUR_PAYMENT_CONNECTOR_URL>",
charge_amount="24.50",
description="Bayview Taxi fare",
)
.say("The payment result is ${pay_result}.")
.hangup()
.build()
)
# The SDK types security_code as a boolean, but SWML takes the string
# "true" or "false", so set it on the built pay verb, past the SDK's check.
pay = next(verb["pay"] for verb in swml["sections"]["main"] if "pay" in verb)
pay["security_code"] = "false"
print(json.dumps(swml, indent=2))

Handle the payment result

Every payment ends with one result value. SWML stores it in pay_result, and Relay sends it as result in the final calling.call.pay event:

ResultWhat happened
successYour connector replied with a charge_id, or a token_id for a saved card
too-many-failed-attemptsAn entry failed SignalWire’s check, or timed out, on every one of the caller’s max_attempts tries
payment-connector-errorSignalWire couldn’t reach your payment connector, or got no response from it
internal-errorThe payment didn’t complete. When your connector declines the card or replies without a valid ID, payment_error is card-declined.
caller-interrupted-with-starThe caller pressed * to cancel
relay-pay-stopYour Relay code stopped collection
caller-hung-upThe caller hung up during the payment
failedSWML only: the pay method couldn’t start the payment, for example because payment_method holds an unsupported value

Alongside the result, SignalWire returns the card type, the card details masked as Payments and PCI compliance describes, the connector’s charge_id as payment_confirmation_code, and the reason for a failure in payment_error. On a charge, payment_token holds the token type you requested, such as reusable. On a saved card, it holds your connector’s token_id.

Handle the result via SWML

pay sets two variables for the rest of the document. Branch on pay_result with switch, as Charge a card via SWML does, or with cond. pay_payment_results holds the full result as a JSON string, which you can send to your server with the rest of the call’s variables:

{
"result": "success",
"payment_token": "reusable",
"payment_confirmation_code": "ch_3f9a1c2b7d4e8f60",
"payment_method": "credit-card",
"payment_card_number": "************1111",
"payment_card_type": "visa",
"payment_card_expiration_date": "1230",
"payment_card_security_code": "***",
"payment_card_postal_code": "94107",
"payment_error": "",
"connector_error": {}
}

On a decline, connector_error carries the error_code and error_message your connector returned.

Handle the result via WebSocket (Relay)

The final calling.call.pay event carries the same fields in params, with your connector’s error in payment_connector_error_code and payment_connector_error_message. Charge a card via WebSocket (Relay) shows how to wait for it.

SignalWire rejects a call.pay request it can’t start, such as one whose payment_method holds an unsupported value. call.pay then fails with an error, and no calling.call.pay event follows.

{
"event_type": "calling.call.pay",
"params": {
"result": "success",
"payment_token": "reusable",
"payment_confirmation_code": "ch_3f9a1c2b7d4e8f60",
"payment_method": "credit-card",
"payment_card_number": "************1111",
"payment_card_type": "visa",
"payment_card_expiration_date": "1230",
"payment_card_security_code": "***",
"payment_card_postal_code": "94107",
"payment_error": "",
"control_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"call_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}
}

Track payment progress with a status webhook

Set status_url on pay in SWML or on call.pay in Relay, and SignalWire sends your webhook a request after the caller enters each card detail, then for payment-processing, and last for payment-completed, payment-failed, or payment-canceled. The step is named in for, and the details collected so far arrive with the card number and security code masked. A Relay client receives the same progress as calling.call.pay events without a result.

JSON
{
"event_type": "calling.call.pay",
"params": {
"status_url": "<YOUR_STATUS_WEBHOOK_URL>",
"status_url_method": "POST",
"for": "security-code",
"error_type": "",
"attempt": "1",
"payment_method": "credit-card",
"payment_card_number": "************1111",
"payment_card_type": "visa",
"security_code": "***",
"expiration_date": "1230",
"control_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"call_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}
}

Compare the surfaces

SWMLWebSocket (Relay)
Start a paymentpaycall.pay
Result valuepay_result variableresult in the final calling.call.pay event
Full resultpay_payment_results variable, a JSON stringparams of the final calling.call.pay event
Connector’s errorconnector_error.code and connector_error.messagepayment_connector_error_code and payment_connector_error_message
Numeric optionsNumbers, such as max_attempts: 3Strings, such as "3"
Stop collectionRun the payment from Relaystop() on the returned action

Stop collecting a payment via WebSocket (Relay)

call.pay returns an action you can stop. The stop takes effect when the next prompt starts, so the caller can finish the entry in progress first. Collection then ends with the result relay-pay-stop and no closing prompt, so play your own message, as this handler does. A stop that arrives while the caller is entering the last card detail doesn’t cancel the payment: SignalWire still sends the card to your connector, and the result is your connector’s outcome.

This handler extends Charge a card via WebSocket (Relay). It keeps the action and stops it if the caller hasn’t finished within two minutes.

# Install: python -m pip install signalwire-sdk
# Save as stop_payment_relay.py and run: python stop_payment_relay.py
import asyncio
from signalwire.relay import RelayClient
client = RelayClient(
project="<YOUR_PROJECT_ID>",
token="<YOUR_API_TOKEN>",
contexts=["default"],
)
def is_pay_result(event):
# Progress events name the step in "for"; the last event carries "result".
return "result" in event.params
@client.on_call
async def handle_call(call):
await call.answer()
intro = await call.play([{
"type": "tts",
"params": {"text": "Thanks for riding with Bayview Taxi. Your fare is 24 dollars and 50 cents."},
}])
await intro.wait()
finished = asyncio.create_task(call.wait_for("calling.call.pay", predicate=is_pay_result))
action = await call.pay(
payment_connector_url="<YOUR_PAYMENT_CONNECTOR_URL>",
charge_amount="24.50",
description="Bayview Taxi fare",
)
try:
# Give the caller two minutes to finish entering the card.
event = await asyncio.wait_for(asyncio.shield(finished), timeout=120)
except asyncio.TimeoutError:
try:
await action.stop()
except Exception as err:
print(f"Couldn't stop the payment: {err}")
event = await finished # relay-pay-stop, unless stopped during the last card detail
p = event.params
if p["result"] == "success":
print(f"Charged {p['payment_card_type']} {p['payment_card_number']}: {p['payment_confirmation_code']}")
text = "Your payment went through. Thanks for riding with Bayview Taxi."
else:
print(f"Payment failed: {p['result']} {p.get('payment_error', '')}")
text = "We couldn't take your payment. A dispatcher will call you back."
async def hang_up_after_playback(_event):
if call.state != "ended":
await call.hangup()
await call.play([{"type": "tts", "params": {"text": text}}], on_completed=hang_up_after_playback)
await call.wait_for_ended()
client.run()

Take a payment from an AI agent

An AI agent takes a payment by calling a tool whose result runs pay. The caller types the card on the keypad, so the digits never reach the conversation, the transcript, or the model. In the Server SDKs, the tool returns a FunctionResult with its pay action, which takes the same options as pay in SWML.

Here Ada, the Bayview Taxi dispatcher, charges the fare when the rider is ready:

# Install: python -m pip install signalwire-sdk
# Save as fare_agent.py and run: python fare_agent.py
from signalwire import AgentBase, FunctionResult
agent = AgentBase(name="bayview-dispatcher", route="/agent")
agent.add_language("English", "en-US", "rime.spore")
agent.prompt_add_section(
"Role",
body="You are Ada, the dispatcher for Bayview Taxi. The rider's fare is 24 dollars and 50 cents. "
"When the rider is ready to pay, call take_payment. Never ask for card details out loud: "
"the rider enters them on the keypad.",
)
@agent.tool(name="take_payment", description="Charge the rider's fare to a card entered on the keypad")
def take_payment(args, raw_data):
return FunctionResult("Collecting the payment now.").pay(
payment_connector_url="<YOUR_PAYMENT_CONNECTOR_URL>",
charge_amount="24.50",
description="Bayview Taxi fare",
)
if __name__ == "__main__":
agent.run()

The tool returns this result. Its SWML runs pay with your options and the SDK’s defaults filled in, then sets ai_response, which tells the agent the payment’s pay_result. To change what the agent is told, pass your own AI response to pay.

JSON
{
"response": "Collecting the payment now.",
"action": [
{
"SWML": {
"version": "1.0.0",
"sections": {
"main": [
{
"pay": {
"payment_connector_url": "<YOUR_PAYMENT_CONNECTOR_URL>",
"input": "dtmf",
"payment_method": "credit-card",
"timeout": "5",
"max_attempts": "1",
"security_code": "true",
"min_postal_code_length": "0",
"token_type": "reusable",
"currency": "usd",
"language": "en-US",
"voice": "woman",
"valid_card_types": "visa mastercard amex",
"postal_code": "true",
"charge_amount": "24.50",
"description": "Bayview Taxi fare"
}
},
{
"set": {
"ai_response": "The payment status is ${pay_result}, do not mention anything else about collecting payment if successful."
}
}
]
}
}
}
]
}

Handling sensitive content covers taking a payment alongside the other ways to keep sensitive values out of an agent’s context.

Payments and PCI compliance

Card data on a call falls under the Payment Card Industry Data Security Standard (PCI DSS). SignalWire collects the card on the keypad and limits where the full details appear; your application and your connector keep their own part of the scope.

What SignalWire masks:

  • In Relay events, status webhooks, and pay_payment_results, the card number keeps only its last four digits and the security code is fully masked. The expiration date and postal code are not masked, so treat them as sensitive in your own logs.
  • While it collects card details, SignalWire keeps the caller’s keypad digits out of its logs.

While it collects card details, SignalWire also pauses any recording on the call that’s paying, so the card entry isn’t recorded. It resumes the recording once collection ends.

Your application handles the rest of its scope. Taps, streams, live transcription, and live translation keep receiving the call’s audio while the caller enters card details, so stop them before pay starts and restart them afterward. A recording on any other call isn’t paused, so pause it yourself, as Pause and resume a recording shows.

Your payment connector receives the full card number and security code, so it is in PCI DSS scope. Send the details only to your processor, log no more than the last four digits, and never store the security code.

An AI agent collects cards with pay rather than asking the caller to read them aloud. Use content redaction to mask any sensitive values a caller says anyway.

Compliance covers the regulated workloads SignalWire supports.

Next steps