Guide
Order confirmations
Text a buyer the moment their order is placed. Two requests do it: add the buyer with their consent, then send the text.
no_active_number.Before you start#
- Create an API key in the dashboard and keep it on your server. See Authentication.
- Check that your number can send:
GET /v1/accountlists your numbers, and one of them needs"status": "active". A number stayspendinguntil the carriers approve it. - Add a tick box to your checkout, as described next. Only buyers who tick it get texts.
Ask at checkout#
Put a tick box next to the phone number field. Leave it unticked, and keep it separate from accepting your terms of sale. Wording like this tells the buyer what they are agreeing to:
[ ] Text me updates about my order
from Demo Bakery at this number.
Message frequency varies. Message
and data rates may apply. Reply STOP
to opt out or HELP for help.- Use your own business name, and link your terms and privacy policy next to the box.
- Keep what the buyer saw and when they ticked it. It is your proof that they agreed.
- This wording covers order updates only. To send offers as well, say so in the wording and let the buyer choose.
- A buyer added this way is an ordinary subscribed contact, so a campaign sent to everyone includes them. If they agreed to order updates only, keep them out of marketing: send campaigns to a list they are not on, or to a segment where Signed up through is not API.
- This guide is not legal advice. The Compliance guide lists the rules the API enforces.
Add the buyer, with their consent#
When the order comes in with the box ticked, add the buyer with POST /v1/contacts. consent.attested: true is your confirmation that they agreed, and consent.source says where. Both are kept as their opt-in record.
curl -X POST https://app.smsblast.com/v1/contacts \
-H "Authorization: Bearer $SMSBLAST_API_KEY" \
-H "Idempotency-Key: $(openssl rand -hex 16)" \
-H "Content-Type: application/json" \
-d '{
"phone": "+14155550101",
"firstName": "Alice",
"consent": {
"attested": true,
"source": "Checkout opt-in box"
}
}'const res = await fetch('https://app.smsblast.com/v1/contacts', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.SMSBLAST_API_KEY}`,
'Idempotency-Key': crypto.randomUUID(),
'Content-Type': 'application/json',
},
body: JSON.stringify({
phone: '+14155550101',
firstName: 'Alice',
consent: {
attested: true,
source: 'Checkout opt-in box',
},
}),
});
console.log(res.status, await res.json());import os
import uuid
import requests
res = requests.post(
"https://app.smsblast.com/v1/contacts",
headers={
"Authorization": f"Bearer {os.environ['SMSBLAST_API_KEY']}",
"Idempotency-Key": str(uuid.uuid4()),
},
json={
"phone": "+14155550101",
"firstName": "Alice",
"consent": {
"attested": True,
"source": "Checkout opt-in box",
},
},
)
print(res.status_code, res.json())A new number answers 201:
{
"contact": {
"id": "0f8d5c3a-6b2e-4f1d-9a7c-3e5b8d2f1a60",
"phone": "+14155550101",
"first_name": "Alice",
"last_name": null,
"email": null,
"timezone": null,
"status": "subscribed",
"source": "api",
"fields": {},
"created_at": "2026-11-02T18:24:09.311Z",
"address_line1": "100 Example St",
"address_line2": null,
"city": "San Francisco",
"state": "CA",
"postal_code": "94110",
"postal_code_plus4": null,
"country": "US"
},
"merged": false,
"addedToList": false
}A number that is already one of your contacts answers 200 with merged: true. The details you sent are merged into the contact on file:
{
"contact": {
"id": "0f8d5c3a-6b2e-4f1d-9a7c-3e5b8d2f1a60",
"phone": "+14155550101",
"first_name": "Alice",
"last_name": "Moreno",
"email": "alice@example.com",
"timezone": "America/Los_Angeles",
"status": "subscribed",
"source": "import",
"fields": {
"favorite_bread": "Sourdough"
},
"created_at": "2026-11-02T18:24:09.311Z",
"address_line1": "100 Example St",
"address_line2": null,
"city": "San Francisco",
"state": "CA",
"postal_code": "94110",
"postal_code_plus4": null,
"country": "US"
},
"merged": true,
"addedToList": false
}- Treat
200and201the same way, then look atcontact.status. - If it is
unsubscribed, stop there. Merging never brings back someone who opted out, and no new opt-in is recorded. - Sending the same buyer again is safe. It merges, and nobody is added twice.
Send the confirmation#
Send the text with POST /v1/messages. Send the final wording: tags such as {first_name} are not filled in here. Say who you are and how to stop.
curl -X POST https://app.smsblast.com/v1/messages \
-H "Authorization: Bearer $SMSBLAST_API_KEY" \
-H 'Idempotency-Key: order-1042-confirmation' \
-H "Content-Type: application/json" \
-d '{
"to": "+14155550101",
"body": "Demo Bakery: thanks, Alice. Order 1042 is confirmed. Reply STOP to opt out."
}'const res = await fetch('https://app.smsblast.com/v1/messages', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.SMSBLAST_API_KEY}`,
'Idempotency-Key': 'order-1042-confirmation',
'Content-Type': 'application/json',
},
body: JSON.stringify({
to: '+14155550101',
body: 'Demo Bakery: thanks, Alice. Order 1042 is confirmed. Reply STOP to opt out.',
}),
});
console.log(res.status, await res.json());import os
import requests
res = requests.post(
"https://app.smsblast.com/v1/messages",
headers={
"Authorization": f"Bearer {os.environ['SMSBLAST_API_KEY']}",
"Idempotency-Key": "order-1042-confirmation",
},
json={
"to": "+14155550101",
"body": "Demo Bakery: thanks, Alice. Order 1042 is confirmed. Reply STOP to opt out.",
},
)
print(res.status_code, res.json())The answer is 201 with the text queued. It usually goes out within seconds. Keep message.id with the order:
{
"message": {
"id": "a4c6e8f0-2b4d-4f6a-8c0e-1d3f5a7c9e86",
"direction": "outbound",
"status": "queued",
"kind": "api",
"from": "+18335550100",
"to": "+14155550101",
"body": "Demo Bakery: thanks, Alice. Order 1042 is confirmed. Reply STOP to opt out.",
"mediaUrls": [],
"credits": 1,
"contactId": "0f8d5c3a-6b2e-4f1d-9a7c-3e5b8d2f1a60",
"campaignId": null,
"error": null,
"sendAt": null,
"createdAt": "2026-11-20T17:02:11.482Z",
"sentAt": null,
"deliveredAt": null
}
}One key per order#
Make the Idempotency-Key from the order, such as order-1042-confirmation, not a random value. Then a retry can never text the buyer twice.
- If the request times out, or answers
429or5xx, send it again with the same key and the same body. If the first try did get through, you get its answer back withIdempotent-Replayed: true. Either way only one text goes out. - The same body means the same bytes. A body that differs gets
idempotency_key_reused(422). - A refusal is remembered too. After
4xxanswers such asnot_a_contactorinsufficient_credits, fix the cause, then send with a new key, such asorder-1042-confirmation-2. - Keys are kept for 24 hours. Record on the order that its text was sent, and check that before you send, so a retry days later cannot text again.
What the errors mean#
A refused send has a JSON body with a stable error.code. This one is for a customer who opted out:
{
"error": {
"code": "unsubscribed",
"message": "This person has opted out and cannot be texted.",
"requestId": "req_8Fk2LqZ9xW1v"
}
}not_a_contact409The number is not one of your contacts.
What to do: Add the buyer with POST /v1/contacts and their consent, then send again with a new Idempotency-Key. Never add someone who did not agree.
unsubscribed409The customer opted out, for example by replying STOP.
What to do: Do not retry. They cannot be texted, even for order updates, until they text START themselves. Use another channel, such as email, and note it in your system.
no_active_number409Your account has no approved sending number yet.
What to do: Nothing was sent and no credits were taken. Sending starts once your number is approved. Check GET /v1/account: a number that can send has "status": "active". Then send again with a new Idempotency-Key.
insufficient_credits402Your balance is too low for this text. error.details has needed and available.
What to do: Buy credits or move to a bigger plan in the dashboard, then send again with a new Idempotency-Key.
The reference lists every code this request can return, and Errors explains the error body.
The whole recipe#
Both scripts add the buyer, send the confirmation with one key per order, retry safely and handle each refusal.
// order-texts.mjs (Node 20 or later): SMSBLAST_API_KEY=sb_... node order-texts.mjs
const API = 'https://app.smsblast.com';
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// POST with up to 4 tries. The body is turned into JSON once and every try sends the same
// Idempotency-Key, so a request that did get through is answered again, never done twice.
async function post(path, body, idempotencyKey) {
const json = JSON.stringify(body);
for (let attempt = 0; ; attempt++) {
const last = attempt === 3;
let res;
try {
res = await fetch(API + path, {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.SMSBLAST_API_KEY}`,
'Content-Type': 'application/json',
...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),
},
body: json,
});
} catch (err) {
if (last) throw err;
await sleep(1000 * 2 ** attempt);
continue;
}
const data = await res.json().catch(() => ({}));
const busy = data.error?.code === 'idempotency_in_progress';
if (last || !(res.status === 429 || res.status >= 500 || busy)) return { status: res.status, data };
const retryAfter = Number(res.headers.get('Retry-After') || 1) * 1000;
await sleep(res.status === 429 ? retryAfter : 1000 * 2 ** attempt);
}
}
// Call this when an order is placed.
async function confirmOrder(order) {
// 1. No tick at checkout, no text.
if (!order.smsConsent) return { sent: false, reason: 'no_consent' };
// 2. Add the buyer with their consent. 201 is a new contact, 200 means the number was one already.
const added = await post('/v1/contacts', {
phone: order.phone,
firstName: order.firstName,
consent: { attested: true, source: 'Checkout opt-in box' },
});
if (added.status !== 200 && added.status !== 201) {
return { sent: false, reason: added.data.error?.code ?? 'error' };
}
// Someone who replied STOP stays opted out and cannot be texted, even about an order.
if (added.data.contact.status !== 'subscribed') return { sent: false, reason: 'unsubscribed' };
// 3. Send the confirmation. One key per order, so a retry can never text the buyer twice.
const text = `Demo Bakery: thanks, ${order.firstName}. Order ${order.id} is confirmed. `
+ 'Reply STOP to opt out.';
const sent = await post('/v1/messages', { to: order.phone, body: text }, `order-${order.id}-confirmation`);
// Keep the id with the order, so you can match delivery events to it later.
if (sent.status === 201) return { sent: true, messageId: sent.data.message.id };
const error = sent.data.error ?? { code: 'error', message: `HTTP ${sent.status}` };
switch (error.code) {
case 'unsubscribed':
// They opted out after you added them. Do not retry. Use email for this customer.
break;
case 'no_active_number':
// Your number is not approved yet. Nothing was sent. Hold order texts until it is, then send
// with a new key. This refusal is remembered under this key for 24 hours.
break;
case 'insufficient_credits':
console.warn(`Order ${order.id}: need ${error.details.needed} credits, have ${error.details.available}`);
break;
default:
console.error(`Order ${order.id}: ${sent.status} ${error.code}: ${error.message}`, error.requestId);
}
return { sent: false, reason: error.code };
}
const order = { id: '1042', phone: '+14155550101', firstName: 'Alice', smsConsent: true };
console.log(await confirmOrder(order));# order_texts.py: pip install requests, then SMSBLAST_API_KEY=sb_... python order_texts.py
import json
import os
import time
import requests
API = "https://app.smsblast.com"
def post(path, body, idempotency_key=None, tries=4):
"""POST with retries. The body is turned into JSON once and every try sends the same
Idempotency-Key, so a request that did get through is answered again, never done twice."""
data = json.dumps(body)
headers = {
"Authorization": f"Bearer {os.environ['SMSBLAST_API_KEY']}",
"Content-Type": "application/json",
}
if idempotency_key:
headers["Idempotency-Key"] = idempotency_key
for attempt in range(tries):
last = attempt == tries - 1
try:
res = requests.post(API + path, headers=headers, data=data, timeout=30)
except requests.RequestException:
if last:
raise
time.sleep(2 ** attempt)
continue
try:
answer = res.json()
except ValueError:
answer = {}
code = (answer.get("error") or {}).get("code")
again = res.status_code == 429 or res.status_code >= 500 or code == "idempotency_in_progress"
if not again or last:
return res.status_code, answer
wait = int(res.headers.get("Retry-After", "1")) if res.status_code == 429 else 2 ** attempt
time.sleep(wait)
def confirm_order(order):
"""Call this when an order is placed."""
# 1. No tick at checkout, no text.
if not order.get("sms_consent"):
return {"sent": False, "reason": "no_consent"}
# 2. Add the buyer with their consent. 201 is a new contact, 200 means the number was one already.
status, added = post("/v1/contacts", {
"phone": order["phone"],
"firstName": order["first_name"],
"consent": {"attested": True, "source": "Checkout opt-in box"},
})
if status not in (200, 201):
return {"sent": False, "reason": (added.get("error") or {}).get("code", "error")}
# Someone who replied STOP stays opted out and cannot be texted, even about an order.
if added["contact"]["status"] != "subscribed":
return {"sent": False, "reason": "unsubscribed"}
# 3. Send the confirmation. One key per order, so a retry can never text the buyer twice.
text = (
f"Demo Bakery: thanks, {order['first_name']}. Order {order['id']} is confirmed. "
"Reply STOP to opt out."
)
key = f"order-{order['id']}-confirmation"
status, sent = post("/v1/messages", {"to": order["phone"], "body": text}, idempotency_key=key)
if status == 201:
# Keep the id with the order, so you can match delivery events to it later.
return {"sent": True, "message_id": sent["message"]["id"]}
error = sent.get("error") or {"code": "error", "message": f"HTTP {status}"}
if error["code"] == "unsubscribed":
pass # they opted out after you added them: do not retry, use email for this customer
elif error["code"] == "no_active_number":
# Your number is not approved yet. Nothing was sent. Hold order texts until it is, then send
# with a new key. This refusal is remembered under this key for 24 hours.
pass
elif error["code"] == "insufficient_credits":
details = error["details"]
print(f"Order {order['id']}: need {details['needed']} credits, have {details['available']}")
else:
print(f"Order {order['id']}: {status} {error['code']}: {error['message']}", error.get("requestId"))
return {"sent": False, "reason": error["code"]}
if __name__ == "__main__":
order = {"id": "1042", "phone": "+14155550101", "first_name": "Alice", "sms_consent": True}
print(confirm_order(order))Schedule a reminder#
Add sendAt to send a text later, up to a year ahead. Use a different key for each text about the same order.
curl -X POST https://app.smsblast.com/v1/messages \
-H "Authorization: Bearer $SMSBLAST_API_KEY" \
-H 'Idempotency-Key: order-1042-pickup-reminder' \
-H "Content-Type: application/json" \
-d '{
"to": "+14155550101",
"body": "Demo Bakery: order 1042 is ready for pickup until 6pm today. Reply STOP to opt out.",
"sendAt": "2026-12-01T17:00:00Z",
"respectQuietHours": true
}'const res = await fetch('https://app.smsblast.com/v1/messages', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.SMSBLAST_API_KEY}`,
'Idempotency-Key': 'order-1042-pickup-reminder',
'Content-Type': 'application/json',
},
body: JSON.stringify({
to: '+14155550101',
body: 'Demo Bakery: order 1042 is ready for pickup until 6pm today. Reply STOP to opt out.',
sendAt: '2026-12-01T17:00:00Z',
respectQuietHours: true,
}),
});
console.log(res.status, await res.json());import os
import requests
res = requests.post(
"https://app.smsblast.com/v1/messages",
headers={
"Authorization": f"Bearer {os.environ['SMSBLAST_API_KEY']}",
"Idempotency-Key": "order-1042-pickup-reminder",
},
json={
"to": "+14155550101",
"body": "Demo Bakery: order 1042 is ready for pickup until 6pm today. Reply STOP to opt out.",
"sendAt": "2026-12-01T17:00:00Z",
"respectQuietHours": True,
},
)
print(res.status_code, res.json()){
"message": {
"id": "a4c6e8f0-2b4d-4f6a-8c0e-1d3f5a7c9e86",
"direction": "outbound",
"status": "queued",
"kind": "api",
"from": "+18335550100",
"to": "+14155550101",
"body": "Demo Bakery: order 1042 is ready for pickup until 6pm today. Reply STOP to opt out.",
"mediaUrls": [],
"credits": 1,
"contactId": "0f8d5c3a-6b2e-4f1d-9a7c-3e5b8d2f1a60",
"campaignId": null,
"error": null,
"sendAt": "2026-12-01T17:00:00.000Z",
"createdAt": "2026-11-20T17:02:11.482Z",
"sentAt": null,
"deliveredAt": null
}
}- API texts go out at any hour.
respectQuietHours: trueholds the text until 8am to 9pm in the contact's time zone, or your account's when theirs is not known. Use it for reminders. - Credits are taken when the text is queued, not when it goes out.
- If the customer opts out before it is due, the text is not sent. It becomes
skippedand its credits come back. - There is no request to change or cancel a scheduled text, so schedule only what you are sure of.
- A
sendAtin the past sends the text now.
Track the link#
Send trackLinks: true and each link in the body is swapped for a short link made for this customer. Put the order number in your link, so you can tell which order a tap belongs to.
curl -X POST https://app.smsblast.com/v1/messages \
-H "Authorization: Bearer $SMSBLAST_API_KEY" \
-H 'Idempotency-Key: order-1042-shipped' \
-H "Content-Type: application/json" \
-d '{
"to": "+14155550101",
"body": "Demo Bakery: order 1042 is on its way. Track it: https://example.com/orders/1042 Reply STOP to opt out.",
"trackLinks": true
}'const res = await fetch('https://app.smsblast.com/v1/messages', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.SMSBLAST_API_KEY}`,
'Idempotency-Key': 'order-1042-shipped',
'Content-Type': 'application/json',
},
body: JSON.stringify({
to: '+14155550101',
body: 'Demo Bakery: order 1042 is on its way. Track it: https://example.com/orders/1042 Reply STOP to opt out.',
trackLinks: true,
}),
});
console.log(res.status, await res.json());import os
import requests
res = requests.post(
"https://app.smsblast.com/v1/messages",
headers={
"Authorization": f"Bearer {os.environ['SMSBLAST_API_KEY']}",
"Idempotency-Key": "order-1042-shipped",
},
json={
"to": "+14155550101",
"body": "Demo Bakery: order 1042 is on its way. Track it: https://example.com/orders/1042 Reply STOP to opt out.",
"trackLinks": True,
},
)
print(res.status_code, res.json())The answer shows the text as it will be sent, with the short link in place:
{
"message": {
"id": "a4c6e8f0-2b4d-4f6a-8c0e-1d3f5a7c9e86",
"direction": "outbound",
"status": "queued",
"kind": "api",
"from": "+18335550100",
"to": "+14155550101",
"body": "Demo Bakery: order 1042 is on its way. Track it: https://app.smsblast.com/s/Ab3dEf9 Reply STOP to opt out.",
"mediaUrls": [],
"credits": 1,
"contactId": "0f8d5c3a-6b2e-4f1d-9a7c-3e5b8d2f1a60",
"campaignId": null,
"error": null,
"sendAt": null,
"createdAt": "2026-11-20T17:02:11.482Z",
"sentAt": null,
"deliveredAt": null
}
}The first time the customer taps it, your webhook gets link.clicked. Later taps by the same person, and visits by link scanners, send no event.
{
"id": "evt_Qm4xT9rV2kLp8NwZ",
"type": "link.clicked",
"created": "2026-11-21T18:02:44.019Z",
"data": {
"link": {
"url": "https://example.com/orders/1042",
"campaignId": null,
"workflowId": null,
"clickedAt": "2026-11-21T18:02:44.019Z"
},
"contact": {
"id": "0f8d5c3a-6b2e-4f1d-9a7c-3e5b8d2f1a60",
"phone": "+14155550101",
"first_name": "Alice",
"last_name": null,
"status": "subscribed"
}
}
}Listen for delivery#
The 201 only says the text is queued. To learn what happened next, add a webhook for message.delivered and message.failed:
curl -X POST https://app.smsblast.com/v1/webhooks \
-H "Authorization: Bearer $SMSBLAST_API_KEY" \
-H "Idempotency-Key: $(openssl rand -hex 16)" \
-H "Content-Type: application/json" \
-d '{
"url": "https://example.com/webhooks/smsblast",
"events": [
"message.delivered",
"message.failed"
],
"description": "Order texts"
}'const res = await fetch('https://app.smsblast.com/v1/webhooks', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.SMSBLAST_API_KEY}`,
'Idempotency-Key': crypto.randomUUID(),
'Content-Type': 'application/json',
},
body: JSON.stringify({
url: 'https://example.com/webhooks/smsblast',
events: ['message.delivered', 'message.failed'],
description: 'Order texts',
}),
});
console.log(res.status, await res.json());import os
import uuid
import requests
res = requests.post(
"https://app.smsblast.com/v1/webhooks",
headers={
"Authorization": f"Bearer {os.environ['SMSBLAST_API_KEY']}",
"Idempotency-Key": str(uuid.uuid4()),
},
json={
"url": "https://example.com/webhooks/smsblast",
"events": ["message.delivered", "message.failed"],
"description": "Order texts",
},
)
print(res.status_code, res.json())Each event carries the whole text, with the same id the send answered. message.failed says why in data.message.error:
{
"id": "evt_Qm4xT9rV2kLp8NwZ",
"type": "message.failed",
"created": "2026-11-20T17:02:15.940Z",
"data": {
"message": {
"id": "a4c6e8f0-2b4d-4f6a-8c0e-1d3f5a7c9e86",
"direction": "outbound",
"status": "failed",
"kind": "api",
"from": "+18335550100",
"to": "+14155550101",
"body": "Demo Bakery: thanks, Alice. Order 1042 is confirmed. Reply STOP to opt out.",
"mediaUrls": [],
"credits": 1,
"contactId": "0f8d5c3a-6b2e-4f1d-9a7c-3e5b8d2f1a60",
"campaignId": null,
"error": "Number is not reachable",
"sendAt": null,
"createdAt": "2026-11-20T17:02:11.482Z",
"sentAt": "2026-11-20T17:02:12.104Z",
"deliveredAt": null
}
}
}Handle the two events in your receiver:
// Inside your webhook receiver, after the signature check (see the Webhooks guide).
// markOrderText is your own code: find the order by the message id you kept when you sent.
const { message } = event.data;
switch (event.type) {
case 'message.delivered':
await markOrderText(message.id, 'delivered'); // the carrier confirmed it reached the phone
break;
case 'message.failed':
await markOrderText(message.id, 'failed', message.error); // why, such as "Number is not reachable"
break;
}# Inside your webhook receiver, after the signature check (see the Webhooks guide).
# mark_order_text is your own code: find the order by the message id you kept when you sent.
message = event["data"]["message"]
if event["type"] == "message.delivered":
mark_order_text(message["id"], "delivered") # the carrier confirmed it reached the phone
elif event["type"] == "message.failed":
mark_order_text(message["id"], "failed", message["error"]) # why, such as "Number is not reachable"// Inside your webhook receiver, after the signature check (see the Webhooks guide).
// mark_order_text is your own code: find the order by the message id you kept when you sent.
$message = $event['data']['message'];
switch ($event['type']) {
case 'message.delivered':
mark_order_text($message['id'], 'delivered'); // the carrier confirmed it reached the phone
break;
case 'message.failed':
mark_order_text($message['id'], 'failed', $message['error']); // why, such as "Number is not reachable"
break;
}- Check the signature of every delivery first. The Webhooks guide has complete receivers in Node.js, Python and PHP.
- A text that never reached the carrier is refunded. A text skipped because the customer opted out first sends no event.
- Without a webhook, ask for the text with
GET /v1/messages/{id}and read itsstatus. - Listen for
contact.opted_outas well, so your system stops sending order texts to that customer.