Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Build the confirmation flow as ordinary order-management software connected to WhatsApp: save a COD order, send a configured WhatsApp template that asks the customer to reply with a decision and order reference, then use an HTTPS webhook to update the matching order. WhatsApp does not provide a COD-specific order-matching feature; your application must identify the order and decide what fulfillment should do.

What you need before coding

Meta hosts the WhatsApp Cloud API. Its documented setup prerequisites include a Meta business portfolio, a WhatsApp Business Account (WABA), and a business phone number. A test setup and a production business configuration are not interchangeable; use the account and number intended for the environment you are configuring. See Meta’s Cloud API documentation for the platform setup details.

  • A Meta app and Cloud API credentials for the selected environment, including an access token, phone number ID, WABA, and app secret.
  • A message template that is available to your account and suitable for initiating this message. The example sends a template with two body parameters; configure its text and placeholders to match. Check the current platform documentation and account settings for the template payload and messaging rules before going live. The older archived Node.js SDK template reference describes sending an approved and enabled template, but it is not a reliable source for current policy details.
  • A public webhook URL reachable over HTTPS with a valid SSL certificate. Configure the app’s webhook and subscribe it to the WABA so Meta can deliver message notifications. See Meta’s webhook reference.
  • Node.js 18 or later, which provides the built-in fetch used below.

This example uses plain-text replies rather than interactive buttons. The customer replies with YES ORDER-123 or NO ORDER-123; including the reference lets the application match a reply to the right order even when a customer has multiple pending orders.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set up the project and database

Create a project directory, then install the two dependencies:

#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
npm init -y
npm install express better-sqlite3

Save the following as server.js. The SQLite database stores order state and inbound message IDs, so a process restart does not erase the workflow or deduplication record. For a multi-instance production deployment, use a shared durable database and a queue or equivalent reliable event-processing design rather than a local SQLite file.

Full example: send, receive, match, and update

Set the environment variables listed after the code before starting the server. The code exposes POST /orders as a small integration endpoint for an order system; protect it with your own authentication before exposing it beyond a trusted internal network.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
const express = require('express');
const Database = require('better-sqlite3');
const crypto = require('node:crypto');

const required = [
  'PORT', 'VERIFY_TOKEN', 'META_APP_SECRET', 'WHATSAPP_ACCESS_TOKEN',
  'PHONE_NUMBER_ID', 'GRAPH_API_VERSION', 'TEMPLATE_NAME', 'TEMPLATE_LANGUAGE'
];
for (const name of required) {
  if (!process.env[name]) throw new Error(`Missing environment variable: ${name}`);
}

const app = express();
const db = new Database(process.env.DB_PATH || './cod-orders.sqlite');
db.pragma('journal_mode = WAL');
db.exec(`
  CREATE TABLE IF NOT EXISTS orders (
    order_id TEXT PRIMARY KEY,
    phone TEXT NOT NULL,
    amount TEXT NOT NULL,
    status TEXT NOT NULL,
    updated_at TEXT NOT NULL
  );
  CREATE INDEX IF NOT EXISTS orders_phone_status ON orders(phone, status);
  CREATE TABLE IF NOT EXISTS inbound_messages (
    message_id TEXT PRIMARY KEY,
    received_at TEXT NOT NULL
  );
`);

function now() {
  return new Date().toISOString();
}

function normalizePhone(value) {
  // Store the customer's number in international format without a leading +.
  const phone = String(value || '').replace(/[\s()+.-]/g, '');
  if (!/^\d{8,15}$/.test(phone)) throw new Error('Phone must be an international number with 8 to 15 digits.');
  return phone;
}

function validSignature(rawBody, signature) {
  if (!signature || !signature.startsWith('sha256=')) return false;
  const expected = Buffer.from(
    'sha256=' + crypto.createHmac('sha256', process.env.META_APP_SECRET).update(rawBody).digest('hex')
  );
  const supplied = Buffer.from(signature);
  return expected.length === supplied.length && crypto.timingSafeEqual(expected, supplied);
}

app.use(express.json({
  verify: (req, res, buffer) => { req.rawBody = Buffer.from(buffer); }
}));

// Meta calls this GET endpoint when verifying the webhook URL.
app.get('/webhook', (req, res) => {
  const mode = req.query['hub.mode'];
  const token = req.query['hub.verify_token'];
  const challenge = req.query['hub.challenge'];
  if (mode === 'subscribe' && token === process.env.VERIFY_TOKEN && challenge) {
    return res.status(200).send(challenge);
  }
  return res.sendStatus(403);
});

function processMessage(message) {
  if (!message || !message.id || !message.from) return;
  const sender = normalizePhone(message.from);
  if (message.type !== 'text' || !message.text || typeof message.text.body !== 'string') return;

  const match = message.text.body.trim().match(/^(YES|NO)\s+([A-Za-z0-9_-]{1,64})$/i);
  const insertMessage = db.prepare(
    'INSERT OR IGNORE INTO inbound_messages (message_id, received_at) VALUES (?, ?)'
  );
  const setStatus = db.prepare(
    `UPDATE orders SET status = ?, updated_at = ?
     WHERE order_id = ? AND phone = ? AND status = 'awaiting_confirmation'`
  );

  const apply = db.transaction(() => {
    const inserted = insertMessage.run(message.id, now());
    if (inserted.changes === 0) return 'duplicate';
    if (!match) return 'unrecognized';
    const status = match[1].toUpperCase() === 'YES' ? 'confirmed' : 'customer_declined';
    const updated = setStatus.run(status, now(), match[2], sender);
    return updated.changes === 1 ? status : 'unmatched_or_not_pending';
  });
  const result = apply();
  console.log(JSON.stringify({ messageId: message.id, result }));
}

app.post('/webhook', (req, res) => {
  if (!validSignature(req.rawBody || Buffer.alloc(0), req.get('x-hub-signature-256'))) {
    return res.sendStatus(401);
  }

  try {
    const entries = Array.isArray(req.body?.entry) ? req.body.entry : [];
    for (const entry of entries) {
      for (const change of (entry.changes || [])) {
        const messages = change.value?.messages || [];
        for (const message of messages) processMessage(message);
      }
    }
    // The event has been parsed and safely recorded before it is acknowledged.
    return res.sendStatus(200);
  } catch (error) {
    console.error('Webhook processing failed:', error.message);
    return res.sendStatus(500);
  }
});

app.post('/orders', async (req, res) => {
  let orderId;
  let phone;
  let amount;
  try {
    orderId = String(req.body?.order_id || '').trim();
    if (!/^[A-Za-z0-9_-]{1,64}$/.test(orderId)) {
      return res.status(400).json({ error: 'order_id must be 1 to 64 letters, digits, underscores, or hyphens.' });
    }
    phone = normalizePhone(req.body?.phone);
    amount = Number(req.body?.amount);
    if (!Number.isFinite(amount) || amount <= 0) {
      return res.status(400).json({ error: 'amount must be a positive number.' });
    }
  } catch (error) {
    return res.status(400).json({ error: error.message });
  }

  const amountText = amount.toFixed(2);
  try {
    db.prepare(
      'INSERT INTO orders (order_id, phone, amount, status, updated_at) VALUES (?, ?, ?, ?, ?)'
    ).run(orderId, phone, amountText, 'awaiting_confirmation', now());
  } catch (error) {
    if (String(error.code).startsWith('SQLITE_CONSTRAINT')) {
      return res.status(409).json({ error: 'That order_id already exists.' });
    }
    console.error(error);
    return res.sendStatus(500);
  }

  const payload = {
    messaging_product: 'whatsapp',
    to: phone,
    type: 'template',
    template: {
      name: process.env.TEMPLATE_NAME,
      language: { code: process.env.TEMPLATE_LANGUAGE },
      components: [{
        type: 'body',
        parameters: [
          { type: 'text', text: orderId },
          { type: 'text', text: amountText }
        ]
      }]
    }
  };

  try {
    const response = await fetch(
      `https://graph.facebook.com/${process.env.GRAPH_API_VERSION}/${process.env.PHONE_NUMBER_ID}/messages`,
      {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${process.env.WHATSAPP_ACCESS_TOKEN}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
      }
    );
    const responseBody = await response.json().catch(() => ({}));
    if (!response.ok) {
      db.prepare('UPDATE orders SET status = ?, updated_at = ? WHERE order_id = ?')
        .run('send_failed', now(), orderId);
      console.error('Message send failed:', response.status, responseBody);
      return res.status(502).json({ error: 'Message send failed; inspect server logs and correct the order state before retrying.' });
    }
    return res.status(202).json({ order_id: orderId, status: 'awaiting_confirmation' });
  } catch (error) {
    db.prepare('UPDATE orders SET status = ?, updated_at = ? WHERE order_id = ?')
      .run('send_failed', now(), orderId);
    console.error('Message request failed:', error.message);
    return res.status(502).json({ error: 'Could not reach the messaging API; inspect server logs and correct the order state before retrying.' });
  }
});

app.listen(Number(process.env.PORT), () => {
  console.log(`COD bot listening on port ${process.env.PORT}`);
});

The two components parameters correspond to a template body containing two placeholders: the order reference and amount. Configure a matching template and language for the account, and verify the request format against the current Cloud API documentation and your configured template before sending live messages. The code uses an environment-provided Graph API version rather than assuming a version remains supported.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Configure and run it

Provide these values through your deployment environment or a local environment file kept out of source control:

Rank #3
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
  • PORT: local listening port, such as 3000.
  • VERIFY_TOKEN: a secret string you choose and enter in the webhook configuration.
  • META_APP_SECRET: the app secret used to verify webhook signatures.
  • WHATSAPP_ACCESS_TOKEN: an access token authorized for the configured messaging assets.
  • PHONE_NUMBER_ID: the Cloud API phone number ID, not the customer-facing phone number.
  • GRAPH_API_VERSION: a currently supported Graph API version for your app.
  • TEMPLATE_NAME and TEMPLATE_LANGUAGE: the configured template name and language code.
  • DB_PATH (optional): database file path; defaults to ./cod-orders.sqlite.

Start the app with node server.js. In your Meta app’s webhook configuration, set the callback URL to the public HTTPS address ending in /webhook, use the same verification token, complete verification, and subscribe the app to the WABA for message events. Webhook notifications require a server reachable from Facebook over HTTPS with a valid SSL certificate and a WABA subscription, as described in the webhook reference.

After the endpoint is protected and reachable from your order system, create a test order:

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
curl -X POST https://your-public-host.example/orders 
  -H 'Content-Type: application/json' 
  -d '{"order_id":"ORDER-123","phone":"919876543210","amount":1499}'

Replace the example host and number with values for your environment. The example expects the phone number in international digits-only format. A successful API request returns HTTP 202 and an order reference; it does not prove that a customer read the message or will reply. The customer can then reply YES ORDER-123 or NO ORDER-123.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How replies become fulfillment decisions

For inbound messages, the documented message object includes sender number, message ID, timestamp, and message type. This implementation reads the sender, ID, type, and text body, then stores the message ID before applying a state change. Interactive responses have their own representation in the webhook message object; this example deliberately handles text only. See Meta’s messages object reference.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Customer reply Order update Fulfillment interpretation
YES ORDER-123 confirmed Customer confirmed; eligible for the next step in your fulfillment workflow.
NO ORDER-123 customer_declined Customer declined; hold fulfillment and route according to your operations policy.
Any other text or unknown reference No order status change Review or contact through an approved workflow; do not infer intent.

The stored order ID and phone number must both match, and only an order still awaiting confirmation can change. The unique inbound message ID prevents a repeated webhook delivery from applying the same event twice. The API reference documents the message ID and webhook object, not a COD-specific association rule; order matching and state management are application responsibilities.

Production checks and failure handling

  • Secure the order endpoint. Add authentication and restrict which services can create orders. Never expose a token or app secret in browser code, logs, or a public repository.
  • Handle ambiguous or stale orders deliberately. This implementation requires an exact order reference and pending status. Add expiry timestamps and a human-review state if your operations need them; do not silently attach a reply to the newest order for a phone number.
  • Recover from send failures. A failed API request marks the order send_failed. Inspect the logged API error, correct the underlying issue, and provide an operator-controlled retry or cancellation path. Avoid blindly resending on every client retry.
  • Plan for operational scale. The sample processes events synchronously and uses SQLite. For bursts or multiple app instances, durably enqueue verified webhook events, return success after enqueueing, and process them with idempotent workers backed by shared storage.
  • Log minimally. The sample logs a provider message ID and processing result, not the full webhook or customer message. Protect any operational logs that could reveal personal information.
  • Review current messaging policy and local requirements. An older Meta-hosted Node.js SDK quickstart is marked archived and describes a 24-hour session after a user reply. Treat that as historical SDK guidance, not proof of current policy; verify live Meta documentation and account settings. The code is not a determination of Indian legal compliance. Archived SDK quickstart.

Keep the data model limited to what the confirmation flow needs, and define your own access, retention, consent, and opt-out processes with current authoritative guidance applicable to your business. This tutorial does not establish India-specific legal requirements.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.