In many markets, including India, Pakistan, the Middle East and parts of Africa and Latin America, Cash on Delivery (COD) is how a large share of customers pay. It's also how stores lose money: someone places an order with a fake name or a wrong number, the courier can't deliver, the parcel comes back, and you pay shipping both ways.
One of the cheapest fixes is to ask the customer to confirm the order with a one-time code sent to their WhatsApp before you ship. In this tutorial we'll build that flow in Node.js for a Shopify or WooCommerce store, using the Authly OTP API. I'm the maker of Authly, but the pattern works with any OTP provider.
The flow
- A customer places a COD order on your store.
- Your store sends a webhook to your server.
- Your server sends a verification code to the customer's phone, on WhatsApp (with Telegram as fallback).
- The customer enters the code on a confirmation page.
- If it's correct, the order is marked confirmed and goes to fulfilment.
- If nobody confirms within a set time (for example 24 hours), the order is put on hold or cancelled.
The code proves one thing: that the number on the order belongs to a real person who is reachable and willing to receive the parcel.
What it costs, in rough terms
Here's an illustrative calculation. These numbers are examples, so replace them with your own:
1,000 COD orders a month, customers in Pakistan
OTP cost: 1,000 × $0.020 = $20 (WhatsApp, per delivered OTP)
If 5% of COD orders turn out to be fake or unreachable,
and each failed delivery costs you $3 in shipping and handling:
50 × $3 = $150 lost per month
If confirmation catches even part of those orders, it pays for itself. Check current rates on the pricing page. Your real numbers depend on your return rate, shipping costs and country mix.
Setup
mkdir cod-confirm && cd cod-confirm
npm init -y
npm install express authly-otp libphonenumber-js
Add "type": "module" to package.json, and set your environment variables:
export AUTHLY_API_KEY="your_api_key"
export SHOPIFY_WEBHOOK_SECRET="your_shopify_webhook_secret"
export DEFAULT_COUNTRY="PK" # country used to parse numbers without a +code
New Authly accounts get a free test quota (7 WhatsApp, 7 Telegram and 100 Email OTPs), enough to test this flow end to end.
Step 1: Receive the order webhook (Shopify example)
Shopify signs each webhook with an HMAC. Verify it against the raw request body before trusting anything:
import express from "express";
import crypto from "crypto";
import Authly from "authly-otp";
import { parsePhoneNumberFromString } from "libphonenumber-js";
const app = express();
const authly = new Authly(process.env.AUTHLY_API_KEY);
// In production, use a database (or Redis with TTL) instead of a Map
const pending = new Map(); // orderId -> { otpId, phone, expiresAt, attempts }
function validShopifyHmac(rawBody, header) {
const digest = crypto
.createHmac("sha256", process.env.SHOPIFY_WEBHOOK_SECRET)
.update(rawBody)
.digest("base64");
const a = Buffer.from(digest);
const b = Buffer.from(header || "");
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
function isCod(order) {
// Adjust to how COD appears in your store's payment gateway names
return (order.payment_gateway_names || []).some((n) => /cash on delivery|cod/i.test(n));
}
function getPhone(order) {
const raw = order.phone || order.shipping_address?.phone || order.billing_address?.phone;
const parsed = parsePhoneNumberFromString(raw || "", process.env.DEFAULT_COUNTRY);
return parsed && parsed.isValid() ? parsed.number : null; // E.164, e.g. +923001234567
}
app.post("/webhooks/orders-create", express.raw({ type: "application/json" }), async (req, res) => {
if (!validShopifyHmac(req.body, req.get("X-Shopify-Hmac-Sha256"))) {
return res.sendStatus(401);
}
res.sendStatus(200); // acknowledge quickly, then do the work
const order = JSON.parse(req.body.toString("utf8"));
if (!isCod(order)) return;
const phone = getPhone(order);
if (!phone) {
// No valid phone number: flag the order for manual review
console.warn(`Order ${order.id}: no valid phone, needs manual review`);
return;
}
try {
const { otpId } = await authly.otp.send({
to: phone,
channel: "whatsapp",
fallbackChannel: "telegram",
lang: "en",
});
pending.set(String(order.id), {
otpId,
phone,
expiresAt: Date.now() + 24 * 60 * 60 * 1000, // 24 hours to confirm
attempts: 0,
});
} catch (err) {
console.error(`Order ${order.id}: could not send OTP`, err.message);
}
});
Notes:
- We acknowledge the webhook first (Shopify expects a quick response) and process afterwards.
- Phone numbers are normalised to E.164 with
libphonenumber-js. A badly formatted number is one of the most common reasons a code never arrives. - If there's no valid number, the order is flagged for manual review instead of being silently confirmed.
For WooCommerce, the idea is the same. Its webhooks are signed with a different header (X-WC-Webhook-Signature), and the order JSON has billing.phone and payment_method fields, so you'd adjust validShopifyHmac, isCod and getPhone.
Step 2: The confirmation endpoint
Customers need a page to enter the code. This endpoint verifies it:
app.use(express.json());
app.post("/confirm", async (req, res) => {
const { orderId, code } = req.body;
const record = pending.get(String(orderId));
if (!record || Date.now() > record.expiresAt) {
return res.status(400).json({ error: "This confirmation link has expired." });
}
if (record.attempts >= 5) {
pending.delete(String(orderId));
return res.status(429).json({ error: "Too many attempts. Please contact the store." });
}
record.attempts += 1;
try {
const result = await authly.otp.verify({ otpId: record.otpId, code: String(code) });
if (!result.verified) {
return res.status(400).json({ error: "That code isn't right. Please try again." });
}
pending.delete(String(orderId));
await markOrderConfirmed(orderId); // your store API call (see below)
res.json({ confirmed: true });
} catch (err) {
res.status(400).json({ error: "That code isn't right. Please try again." });
}
});
async function markOrderConfirmed(orderId) {
// Example idea: add a "cod-confirmed" tag to the order using the Shopify Admin API,
// so your fulfilment workflow only picks up confirmed orders.
}
A very small confirmation page can post to this endpoint:
<form id="f">
<p>Enter the 6-digit code we sent to your WhatsApp to confirm your order.</p>
<input id="code" inputmode="numeric" autocomplete="one-time-code" maxlength="6" required />
<button>Confirm order</button>
<p id="msg" role="status" aria-live="polite"></p>
</form>
<script>
const orderId = new URLSearchParams(location.search).get("order");
document.getElementById("f").addEventListener("submit", async (e) => {
e.preventDefault();
const res = await fetch("/confirm", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ orderId, code: document.getElementById("code").value }),
});
const data = await res.json();
document.getElementById("msg").textContent = res.ok ? "Order confirmed. Thank you!" : data.error;
});
</script>
You'll need to give the customer the link to this page, for example on the order status page or in the order confirmation email: https://yourstore.com/confirm?order=12345.
Step 3: Handle orders nobody confirms
Run a job every hour to deal with expired confirmations:
setInterval(async () => {
for (const [orderId, record] of pending) {
if (Date.now() > record.expiresAt) {
pending.delete(orderId);
await holdOrCancelOrder(orderId); // tag as "unconfirmed" or cancel, per your policy
}
}
}, 60 * 60 * 1000);
What to do with unconfirmed orders is a business decision. Many stores put them on hold and contact the customer first, because some real customers simply miss the message.
Production checklist
-
Persist state in a database or Redis, not an in-memory
Map. Restarts would lose every pending order. -
Rate limit the
/confirmendpoint per IP and per order. - Limit resends. Allow at most a couple of new codes per order, with a cooldown.
- Tell customers at checkout that they'll receive a WhatsApp code to confirm the order, so a message from an unknown number doesn't surprise them.
- Respect privacy rules. Use the phone number only for order confirmation and delivery, and mention it in your privacy policy.
- Offer a fallback for customers who can't use WhatsApp or Telegram (an email code or a call from your team).
- Test with a real order in a development store before turning it on for customers.
An alternative: no code entry
Typing a code adds a step. Some flows let the customer tap a link or scan a code on WhatsApp to confirm instead. Authly supports click/scan-to-verify on WhatsApp, which can make confirmation faster for mobile shoppers. See the docs for how it works.
Wrapping up
Confirming COD orders with a one-time code is a small change with a clear payoff: fewer fake orders, fewer returned parcels and a cleaner list of real buyers. The code above is a starting point, so adapt it to your store, your policy for unconfirmed orders and your market.
If you try it, tell me in the comments how your store handles COD returns today. I'd like to hear which countries and platforms people are dealing with, and I'll cover WooCommerce in a follow-up if there's interest.
Top comments (0)