Webhooks Tutorial

When testing your application locally, ngrok is a helpful tool for viewing the webhook responses that BigCommerce sends to your app. Ngrok creates a publicly accessible tunnel URL to an application running on your machine’s localhost. Ngrok also provides a web interface you can use to view HTTP request details.

In this tutorial, we’ll install ngrok, register a webhook on your store, and then observe the response when the webhook event is triggered.

If you would like to follow along, we have created a Postman collection with all the requests.

Run in Postman

Prerequisites

Create Project Folder

  1. Open the terminal and create a folder that will hold ngrok and the Node app, then move into that directory.
mkdir webhooks-test
cd webhooks-test

Install ngrok

Mac/Linux

  1. Visit https://ngrok.com/ and click download.
  2. Choose the version for your operating system.
  3. Unzip ngrok and place the application in the project folder that you created. This step can be accomplished in one command:
unzip /Users/your-computer/Downloads/ngrok-stable-darwin-amd64.zip -d /Users/your-computer/Documents/webhooks-test

Windows

  1. Visit https://ngrok.com/ and click download.
  2. Choose the version for your operating system.
  3. Unzip ngrok and place the application in the project folder that you created.
  4. Make sure ngrok is referenced in your PATH environment variable.

Checkpoint

At this point you should have a project folder with ngrok unzipped inside of it.

Create Express App

  1. In the terminal run npm init. You will be prompted with several questions about the app setup. Feel free to hit return to accept the default values. The final screen will look something like this:
{
  "name": "webhooks-test",
  "version": "1.0.0",
  "description": "webhooks-test",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}
  1. Take note of the value in “main”, index.js.

  2. Create a file in your project folder called index.js. Use the command touch index.js for Mac or copy nul > index.js for Windows.

  3. Install Express using the terminal in the same project folder. npm install express --save

Checkpoint

At this point your project folder should contain:

  • index.js
  • node_modules
  • package.json
  • ngrok
  • package-lock.json
  1. Copy and paste the following into index.js:
const express = require('express');
const app = express();

// when there's a post request to /webooks...
app.post('/webhooks', function (req, res) {
  
    // respond with 200 OK
    res.send('OK');
});

app.listen(3000, function () {
    console.log('Listening for webhooks on port 3000')
})

This app listens to requests on port 3000, then 200 responds once it receives a POST request to /webhooks.

From Express Website: app.METHOD(PATH, HANDLER)

  • app is an instance of express.
  • METHOD is an HTTP request method, in lowercase.
  • PATH is a path on the server.
  • HANDLER is the function executed when the route is matched.
  • Res.send is the body parameter that sends the HTTP response.

Start the App and ngrok

  1. Open two terminal tabs. In both tabs, navigate to your project folder.
  2. In one tab run the app. node index.js
  3. Start ngrok in the other tab. ./ngrok http 3000

node index.js

BIGCOMMERCE:webhooks your.computer$ node index.js
Listening for webhooks on port 3000

ngrok http 3000

ngrok running

ngrok returns two values we will need to register a webhook and observe the response:

  • Web Interface: Where you can monitor the hook from a browser. http://127.0.0.1:4040
  • Forwarding: The webhook destination. Make note of the https version. For example, https://6a35e97b.ngrok.io.
  1. Open a web browser and copy in your Web Interface URL: http://127.0.0.1:4040. This is where webhook payloads will appear when they fire.

ngrok Web Interface

#### ngrok Web Interface

Subscribe to the store/product/updated event:

  1. If you have not already done so, generate the API Access Token & Client ID with the Information & Settings scope set to Read-Only and the Products scope set to Read-Only.

  2. POST to https://api.bigcommerce.com/stores/{{store_hash}}/v2/hooks. Replace store_hash with the value from your store’s API path.

  3. In the request body, scope is the webhook event we are subscribing to, and destination is the ngrok forwarding url with /webhooks appended (the route specified in the Express app):

{
 "scope": "store/product/updated",
 "destination": "https://6a35e97b.ngrok.io/webhooks",
 "is_active": true
}
  1. Update the request headers to contain the following:
    Accept: application/json
    Content-Type: application/json
    X-Auth-Client: {{the OAuth client id}}
    X-Auth-Token: {{the OAuth token}}
  1. Check all the values and then send. If successful, the response will be 200 OK.

The id number displayed in the response is needed to disable the hook.

200 OK Response
{
  "id": 14263419,
  "client_id": "your-client-id",
  "store_hash": "your-store-hash",
  "scope": "store/product/updated",
  "destination": "https://6a35e97b.ngrok.io/webhooks",
  "headers": null,
  "is_active": true,
  "created_at": 1531256030,
  "updated_at": 1531256030
}

Trigger the Webhook Event

Webhooks can be triggered by actions performed by a shopper on the storefront or user within the control panel, or actions performed via API. To illustrate this point, we’ll demonstrate both methods.

Update via the Control Panel

  1. From your store’s control panel, navigate to Products > View. Choose a product and edit product details like name or description.
  2. Click Save.

BigCommerce Control Panel

#### BigCommerce Control Panel

  1. Visit the ngrok web interface address and check for a 200 response.

ngrok Web Interface

#### ngrok Web Interface

The Summary shows that the webhook has fired and our Express app has returned a 200 response along with the text OK. The response is generated by res.send(‘OK’) in our app code, but this text can be changed to say something different or even post the response to another app. For more info, see Express Routing.

The record of the HTTP request will also show in the terminal tab running ngrok.

ngrok Terminal Response

#### ngrok Terminal Response

Update Via the API

  1. Generate the API Access Token & Client ID. Set the Information & Settings scope to Read-Only and the Products scope to Modify.

  2. Create a PUT request to the product to be updated, replacing {{store-hash}} and {{product_id}} with values from your store:

https://api.bigcommerce.com/stores/{{store_hash}}/v3/catalog/products/124

In this example, the price of product_id 124 is being changed to 12.99:

{
  "price": 12.99
}

After hitting send, check the ngrok web interface. You may see a single event or several based on how many times the product has been updated in the previous step.

ngrok Web Interface

#### ngrok Web Interface

That’s it! In this walkthrough you created a webhook, set up a server to accept the response, and used ngrok to observe the webhook payload.

Want to keep going? Try changing the text in res.send() to a custom response, print the response to a webpage, or register a different webhook event.

URL Timeout

Unless you have a paid ngrok account, the destination URL will only be valid for a few hours. After that, the webhook will stop working. Send a DELETE request to the specific webhook ID to disable the hook.

Adding Custom Headers

For added security you can add custom headers to your webhook request. headers accepts any key:value pair as a string.

Example Webhook Custom Headers

{
"scope": "store/cart/lineItem/*",
  "destination": "https://myapp.herokuapp.com/",
  "is_active": true,
  "headers": {
    "User-Name": "Hello",
    "Password": "Goodbye"
  }
    
}

Troubleshooting

Getting a 404 error using the root (/) url?

Add this snippet to your code to respond to incoming get requests with ‘hello’:

app.get('/',(req, res)=>{
    res.send('Hello!');
}); 

Getting error ngrok not found?

There are two ways to fix this. Your local setup will determine which command will work. Use the command mv ngrok /usr/local/binto move ngrok to your local bin folder. This way it becomes available globally. Use the command ./ngrok http 3000 to run ngrok as a sudo user.


Windows Users

If you are having trouble getting ngrok started try setting the PATH. - What are PATH and other environment variables, and how can I set or use them?

Resources