Use Webhooks to Build a New Customer Notification App with BigCommerce and Twilio

Karen White
BigCommerce Developer Blog
8 min readSep 5, 2019

One of my favorite movie sequences is the breakfast-making Rube Goldberg machine in the opening of Pee-wee’s Big Adventure. Pee-wee starts his morning routine — as one does — by activating an elaborate, multi-step contraption that cracks eggs, fries bacon, and flips pancakes. Each step of the sequence triggers another action: Pee-wee lights a candle which burns through a string, which causes an anvil to drop, which turns a mechanical belt, which sends an egg down a chute to be cracked into a frying pan.

While a breakfast-making machine is not exactly like an app, there are some parallels (humor me here). In both cases, an action triggers a responsive action. When building an app, we often need to know when an event has happened so the app can respond with an appropriate action — and that’s where webhooks come in.

Let’s consider a real-world example. An order fulfillment app that connects to an ecommerce store would need to know when a new order comes in. Every time there’s a new order, the app should fetch the details of that order and pass the data to modules that handle printing the shipping label or decrementing inventory from a third-party management tool.

Webhooks allow apps to react to events that happen in other applications, in real time. You can subscribe to specific events, like when a new order is placed or a new customer registers an account, and the webhook service sends you a notification via HTTP request when the event occurs. Without webhooks, you’d need to periodically poll the resource for changes — for example, by requesting all orders on an interval to check for new ones. Webhooks allow you to respond to changes almost immediately, without wasting resources on periodic checks.

Build a New Customer Notification App

Now it’s time to build our own breakfast making contraption — er, app. To demonstrate how webhooks let you translate real-time events into real-world action, we’ll build a simple Node app that sends you a text message each time a new customer registers an account on a BigCommerce store. To do this, we’ll register a webhook for the “new customer” event in BigCommerce, and we’ll use Twilio to send the text.

If you’d like to skip straight to the code, you can see the full project on GitHub.

Here’s the basic workflow:

  1. First, we’ll fetch all registered webhooks from the BigCommerce store and check to see if we already have a store/customer/created or store/customer/* webhook. If we don’t, we’ll create one.
  2. When a customer registers an account on the store, a webhook will fire. We’ll create a route to receive the webhook POST request.
  3. Next, the app should parse out the customer ID from the webhook payload and use it to make an API request for the customer’s full details. We’ll grab the customer’s first and last name from the response.
  4. Lastly, we’ll use Twilio to send ourselves a text message, alerting us that a customer has registered a new account.

Let’s get started!

Install Dependencies

Begin by creating the basic project structure and installing dependencies. Create a new folder to hold the project and navigate to the directory:

mkdir webhook-app
cd webhook-app

Be sure you have Node installed. I used Node v 10.x for this project.

node --version

Create a package.json file for your project by running the ‘npm init command’. You can hit enter to select the default for each prompt.

npm init

Install the dependencies in your project directory:

npm install --save dotenv node-bigcommerce body-parser express twilio

Create API Accounts

We’ll need API credentials from two different services for this tutorial: BigCommerce and Twilio.

Twilio

Start by signing up for a Twilio account. Follow the Just Exploring project template, and then navigate to the Buy a Number page in your Console. Follow the instructions in Twilio’s documentation to Buy a Number (using your free trial credits).

Navigate back to the Console Dashboard and note two values: the Account SID and Auth Token. We’ll need both of these, as well as the trial phone number, for this tutorial.

BigCommerce

Sign up for a BigCommerce trial. Follow the instructions in the BigCommerce developer documentation to create an API account. Save your credentials; you’ll need the Client ID and Access Token for this tutorial, as well as the store hash from the API path (located on the main Create an API Account screen).

Install ngrok

In order to work with webhooks while the app is running locally, we’ll need to use ngrok to tunnel the destination route to a publicly accessible URL. Install ngrok using the instructions at https://ngrok.com/download

Configure Environment Variables

Create a new file in the root of your project and save it as .env. The .env file will hold our app’s environment variables. Paste the following into the file contents, replacing the placeholder values with the credentials obtained in the previous steps:

ACCOUNTSID=Twilio Account SID
AUTHTOKEN= Twilio Auth Token
CLIENTID=BigCommerce Client ID
ACCESSTOKEN=BigCommerce Access Token
STOREHASH=BigCommerce store hash

Create a new file in your project’s root and save it as app.js. Paste the following at the top of the file:

const http = require('http');
const express = require('express');
const bodyParser = require('body-parser')
const dotenv = require('dotenv');
dotenv.config();
const BigCommerce = require('node-bigcommerce');
const bigCommerce = new BigCommerce({
clientId: process.env.CLIENTID,
accessToken: process.env.ACCESSTOKEN,
storeHash: process.env.STOREHASH,
responseType: 'json'
});
const accountSid = process.env.ACCOUNTSID;
const authToken = process.env.AUTHTOKEN;
const client = require('twilio')(accountSid, authToken);
const app = express();
app.use(bodyParser.json())

Register the webhook

Before creating a new webhook on the store, it’s important to make sure we don’t already have one registered. It’s possible for an app to register multiple BigCommerce webhooks for the same event; when the event fires, the webhook service will send off multiple notifications. In this case, we want to make sure we’re only dealing with a single notification.

We’ll use the BigCommerce Node client developed by Conversio to request all of the webhooks currently registered by our app. Note that webhooks are tied to a particular Client ID — we’ll only be able to read and write to the webhooks registered by our app, not by other apps.

The scope property represents the type of event that triggers the webhook. After fetching the webhook data, we’ll save the scopes to an array and check to see if store/customer/created or store/customer/* are present. Either of those scopes will cause a webhook to be sent when a new customer is created.

If neither scope is present in the array, we know that we’ll need to create a new webhook. We’ll send a POST request to the BigCommerce /hooks endpoint with this request body to register the hook:

{
"scope": "store/customer/created",
"destination": "https://xxxxxx.ngrok.io/webhooks",
"is_active": true
}

Don’t worry about the destination URL just yet — we’ll replace this placeholder value with a real ngrok tunnel URL once we’re ready to start up the app.

bigCommerce.get('/hooks')
.then(data => {
let webhooks = data;
let scopes = webhooks.map(a => a.scope);
const hookBody = {
"scope": "store/customer/created",
"destination": "https://xxxxxx.ngrok.io/webhooks",
"is_active": true
}

console.log(scopes);
if (scopes.indexOf("store/customer/created") > -1 || scopes.indexOf("store/customer/*") > -1) {
console.log("Customer webhook already exists");
} else {
bigCommerce.post('/hooks', hookBody)
.then(data => {
console.log('Customer webhook created');
})
}
});

Respond to the webhook

Next, we’ll create a route to handle the POST request from the BigCommerce webhook service. Let’s break down what’s happening here:

app.post('/webhooks', function (req, res) {
res.send('OK');
let webhook = req.body;
let customerId = webhook.data.id;
console.log(customerId);
bigCommerce.get(`/customers/${customerId}`)
.then(data => {
let firstName = data.first_name;
let lastName = data.last_name;
sendText(firstName, lastName);
})
});

When the app receives a post request to the /webhooks route, the first thing we’ll do is send back a 200 — OK response. This lets the BigCommerce webhook service know that we received the request. If the BigCommerce webhook service didn’t receive an OK response within 10 seconds, it would resend the request at increasing intervals before disabling the request after 48 hours.

The webhook payload contains the ID of the new customer. We’ll save the customer ID as a variable and pass it to a second request that will fetch the full customer details from the BigCommerce API. We’ll save the customer’s first and last name from the response and pass them to a function to send the text message, which we’ll create next.

Send the text message

We’ll use the Twilio Communications API to send the text message. In the following function, replace the ‘from’ value with the programmatic phone number from your Twilio dashboard, and replace the ‘to’ value with your own phone number.

function sendText(firstName, lastName){
client.messages
.create({
body: `${firstName} ${lastName} just registered an account on your store!`,
from: '+15127777777',
to: '+15125555555'
})
.then(message => console.log(message.sid));
}

Start the server

Add this to the bottom of your app.js file to start the Express server on port 1337:

http.createServer(app).listen(1337, () => {
console.log('Express server listening on port 1337');
});

Open a terminal window and start ngrok on port 1337. If you haven’t moved ngrok to your $PATH, you’ll need to provide the path to where you unzipped the ngrok executable on your local machine.

./ngrok http 1337

Copy the ngrok http forwarding URL from the terminal:

And supply it as the destination URL for your hookBody object in app.js:

const hookBody = {
"scope": "store/customer/created",
"destination": "https://a015a931.ngrok.io/webhooks",
"is_active": true
}

Now, start the app. Open a second terminal window and run this command from your project directory:

node app.js

Note that if you’ve started the app before replacing the destination URL with the ngrok tunnel URL from your current session, the app has likely already registered a webhook pointing to the placeholder URL. But not to worry — you can use Postman to delete the webhook and start over, or just update the existing hook’s destination URL to point to your ngrok tunnel URL. Just be sure to use the same BigCommerce client ID and token in Postman that you use in your app.

Test the app

With both the app and ngrok running, navigate to the front end of your BigCommerce site and register a new customer account. Within a few seconds, you should receive a text message:

‘Sent from your Twilio trial account — Karen White just registered a new account on your store!’

woo-hoo, new customers!

Conclusion

Congrats! You just used webhooks to kick off a chain of events that begins with a new customer account registration and results in a text message notification.

This tutorial is a simple demo to get you started with webhooks, but you can take it further by deploying your app to a hosting platform like Heroku or adapting the concept for another event type.

Get inspired — check out the full list of BigCommerce webhook events in the developer documentation and see what use cases you can come up with. And if you have questions or run into any issues, you can tweet us @BigCommerceDevs or comment below.

--

--

Karen White
BigCommerce Developer Blog

Developer Marketing at Atlassian. Formerly at BigCommerce, Rasa. I think Voyager was the best Star Trek.