Webhooks

Integration Overview

In this guide you'll learn how to use webhooks to automate specific events between 3rd party services, like email or sms,after the checkout has been captured.

For the purpose of this guide, we’ll be integrating with the Twilio SDK for Node.js:

Let’s get started

You'll need is a callback URL on the public internet. This URL will accept POST HTTP requests from the Chec API, verify the request signature and lifetime, then ask Twilio to message you with something encouraging.

mkdir twilio-handler && cd twilio-handler
yarn add twilio @chec/webhook-verifier
touch index.js 

Setup

Head over to Twilio and sign up for an account. Once you’re logged in, grab your “account SID” and “auth token”, open up your code editor and put them into in your index.js file. You’ll need to register a phone with Twilio when you sign up, and get a number for Twilio to send from - this can be done in the “Phone numbers > Active numbers” section. We’re also going to add signingKey with an empty value, which we’ll fill out when we register the webhook later on.

const http = require('http');
const twilio = require('twilio');
const { verifyWebhook } = require('@chec/webhook-verifier');

// Your Account SID from www.twilio.com/console
const accountSid = 'AC1234f0dd3r420024106c0576ee28abc';
// Your Auth Token from www.twilio.com/console
const authToken = '1a2b3c4d5e6f7g8habc123zyx987';
// Your Chec webhook signing key, from the Chec Dashboard webhooks view
const signingKey = 'todo';
// The phone numbers to send from and to
const phoneNumbers = {
  from: '+123456789', // A Twilio phone number you purchased at twilio.com/console
  to: '+1987654321',
};

const client = new twilio(accountSid, authToken);

const requestListener = (request, response) => {
  // Handle request body chunking
  const chunks = [];
  request.on('data', chunk => chunks.push(chunk));
  request.on('end', () => {
    // Get the request body/payload
    const data = JSON.parse(Buffer.concat(chunks));

    // Verify the signature
    try {
      verifyWebhook(data, signingKey);
    } catch (error) {
      console.error('Signature verification failed:', error);
      response.writeHead(500);
      response.end();
      return;
    }

    // All good, send to Twilio
    const orderId = data.payload.id || 'Test request';
    const orderValue = data.payload.order
      ? data.payload.order.total_with_tax.formatted_with_symbol
      : '$0.00';
    const messageBody = `Keep up the good work, order fu is strong! ${orderId} for ${orderValue}.`;

    client.messages.create({
      body: messageBody,
      to: phoneNumbers.to,
      from: phoneNumbers.from,
    })
      .then((message) => console.log(`Sent message: ${message.sid}`))
      .catch((error) => console.error(error));

    response.writeHead(200);
    response.end();

    console.log(`${data.response_code} for ${data.event}`);
  });
};

const server = http.createServer(requestListener);
server.listen(8080);

console.log('Listening for incoming webhooks...');

This callback performs the following tasks;

  • Verify the signature. We use the @chec/webhook-verifier NPM package for this. It’s important to verify the signature of incoming webhooks so you can verify that they actually came from Chec, and not a manipulator-in-the-middle attack.
  • Send an SMS using Twilio. This part’s pretty straight forward - we load up the Twilio SDK, tell it where to send the message, what the message should be, and which number it should come from (ensure both numbers you use are registered in the Twilio console).

Next we need to actually run this web server, and expose it to the world. You can easily spin up a local server by running node index.js in your terminal. You’ll also need to expose it to the world though, so we’d recommend using ngrok for this - a useful web proxy for exposing local servers to the world. Head over there, sign up for a free account and install ngrok.

cd twilio-handler
node index.js
 # Listening for incoming webhooks...

# Open a new console tab/window:
cd twilio-handler
ngrok http 8080
# Forwarding https://f3cb1bb6.ngrok.io -> http://localhost:8080

Now we’ve got a functioning callback handler, we can tell Chec about it! Head to the Chec Dashboard and go to Setup → Webhooks. Click “Add webhook”. Select orders.create from the events list, enter your ngrok URL, and save the webhook.

Adding a webhook

Now you can view the webhook, and you’ll see the signing key on the details panel here as well. Copy this key and put it into the signingKey variable in your project. You’ll need to restart your node index.js command so it picks up the new variable value.

At this point you can make a test request from the Chec Dashboard, and you should get a text message sent to your phone!

Test the full process by going and placing a test order on your account. You can disable the webhook if you start getting irritated by the frequency of messages (probably a good problem to have).

You’ll also see a history of the most recent delivery attempts to your webhook callback URL:

Webhook delivery history view

What's next?

Webhooks give you the power to augment parts of your eCommerce business outside of the scope of the Commerce.js. You can set all of this up using our API as well, so check out the Chec webhooks API documentation and get started!