Home
Blog
Integrating WhatsApp Into Shopify

March 7, 2023

Integrating WhatsApp Into Shopify

By Rashed Talukder

As a Shopify developer for medium or large-scale businesses, you know how important it is to have seamless communication with your customers. To achieve this, you can leverage the WhatsApp Business Platform to help you send automated messages to thousands of customers and scale the process efficiently as your customer base grows.

This tutorial walks through the process of connecting WhatsApp to Shopify and sending WhatsApp notification messages to customers based on events they trigger in the store, such as adding a product to their cart or placing an order. To do this we will be using the Cloud API, hosted by Meta.

Prerequisites

To follow this tutorial, you'll need to:

Completing the last step will grant a temporary access token. You’ll need it for the rest of this tutorial, so hang on to it.

Once you’ve met these requirements, you can proceed with the rest of the tutorial.

Create a Message Template on WhatsApp

WhatsApp message templates help you create multiple message formats that you can use more than once to message customers after they’ve given your app permission to do so.

Follow these steps to create a template for an order notification message:

  • Sign in to your Business Manager and choose your business account.
  • Click on the three-line icon at the top left corner of the page and click WhatsApp Manager.
  • Using the side navigation, hover on the Account Tools icon and click Message templates.
  • Click Create Template at the top right corner of the page.
  • On the following page, choose the Transactional option for your category, then give the template a name (in this case, “order_confirmation”) and select its language.
  • Click Continue to proceed to the template editor.

Now that the order_confirmation template is set up, it's time to define its outline. Here's how the message should appear to the customer:

  • We have received your order!

  • Hi [customer’s name],

  • Thanks for shopping with us.

  • We're now processing your order (23190). Your package will be shipped to you within the next 2-3 business days (excluding holidays and weekends).

  • When that happens, you'll get another email from us.

In your template editor, choose Text for the Header section. The “We have received…” paragraph will be the Header, with the remainder of the message copied into the Body section.

Next, click Add variable twice beneath the Body text box to add two variables. Copy and paste the first variable — {{1}} — in place of the customer name. Next, copy and paste the second variable — {{2}} — in place of the order number inside the bracket.

When you're done, your message should look like this. You can check the preview area on the same page.

Click Submit to save the message template.

Now that the template is ready, you can use the WhatsApp Business Platform to create a webhook in your Shopify admin and map an application that automatically sends the message to a customer when they place an order.

Using Webhooks to Send Notifications to an Express Server

Say you want to send an automated message to customers whenever they place an order from your Shopify store. You could check the store for new orders every five minutes or so. However, sending constant API requests to your shop is inefficient — especially if no new orders have been made.

It's far more efficient for a webhook to listen for the “order creation” event on your store and notify you each time a customer places an order.

Here are the basic steps to create an “order creation” webhook and map it to an express server.

Set up a Node.js Project

Start by creating a folder named “whatsapp-demo” for your project.

Next, launch the command terminal cd in “whatsapp-demo” and execute the following command to initialize a Node.js project:

npm init -y

Install express, the library used to create a web server on Node.js, by running the following command:

npm i express

Now that your development environment is set, you’ll create the express server.

Create an Express Server

Create a file named test.js inside the whatsapp-demo folder. Open it with your preferred source-code editor and copy-paste the following code into it:

const express = require('express')
const app = express()

app.post('/webhooks/orders/create', (req, res) => {
 console.log('Yes, We got an order!')
 res.sendStatus(200)
})

app.listen(3000, () => console.log('Now running on port 3000!'))

Using the above code, you’ve set up a basic express server that displays a message on the server's terminal when the webhook sends an “order creation” notification.

Before mapping it to the Shopify webhook, you must first set up a tunnel.

Set Up an HTTPS Traffic Tunnel

When setting up a webhook, Shopify requires you to provide a public URL where it'll send the notification.

If you're following this tutorial on a public server, use its URL. If you're following this tutorial on your local machine, you’ll need to create a tunnel with a publicly accessible HTTPS URL.

First, install ngrok by executing the following command:

npm install -g ngrok

Next, launch a different terminal window and run the following command to get the tunneled URL for your local server:

ngrok http 3000
Forwarding                    https://xxxx-xxx-xxx-xxx-xxx.ngrok.io

Take note of the URL because you'll need it in the next step. Note that if you restart this client, you’ll get a new URL and need to update all references to it.

Create a Webhook in Shopify

Go into your Shopify’s store’s admin and navigate to Settings > Notifications. Once you’re there, scroll down to Webhooks and click on Create webhook.

Add a webhook for “order creation” and specify your tunnel URL or public URL you created in the previous section.

Run your local server on a different terminal with node index.js, then click Send test notification.

If everything goes well, you'll receive this message on your server's terminal: “Yes we got an order.”

Now you have a working connection between your Shopify store and Express server. Next, you'll send the WhatsApp message template to the customer after they place an order.

Send a Custom Message with the "order_notification" Template

First, install Axios by running the following command on your terminal:

npm i axios

You'll use Axios to make the POST request responsible for sending the WhatsApp message to the customer.

After Axios is installed, create another file in your project folder named customMessage.js, then import axios and express into the file with the following code:

const axios = require('axios').default
const express = require('express')
const app = express()

Next, create a route to handle the order creation notification from Shopify by running the following:.

app.post('/webhooks/orders/create', async (req, res) => {
const body = await getRawBody(req);

const order = JSON.parse(body.toString());

console.log("Yes, We got an order!", order.customer.phone);
  
// Remaining code will go here

})

When Shopify calls /webhooks/orders/create with an order, the order details will be sent to the route inside of res, the second argument of your async callback function and a JavaScript object.

Next, grab the customer's phone number, first name, and order ID from the order details, and use them to construct the API request parameters:

        const data = {
        "messaging_product": "whatsapp", 
         "to": `${order.customer.phone}`, 
        "type": "template", 
         "template": { 
        "name": "order_confirmation", 
        "language": { "code": "en_GB" },
        "components": [
        {
          "type": "body",
          "parameters": [
          {
            "type": "text",
            "text": `${order.customer.first_name}`
          },
          {
            "type": "text",
            "text": `${order.id}`
          }
        ]
      }
    ] 
  } 
} 

The above object contains all the parameters required to complete the request. Ensure the template name specified in the object matches the one created earlier in your WhatsApp Business Manager.

Next, create a config object with a nested headers object. Inside headers, set your WhatsApp access token as the value of Authorization (replace ACCESS_TOKEN with the token), and application/json as Content-Type:

 const config = {
 headers: { Authorization: `Bearer <ACCESS_TOKEN>`, 'Content-Type':   'application/json'}
};

Next, create a POST request with Axios and pass both the config object and the data object as arguments. Nest then and catch methods to show the result (or the error message if the promise fails):

  if (order.customer.phone) {
   return res.sendStatus(403);
  } else {
  axios
  .post(
    "https://graph.facebook.com/<API_VERSION>/<YOUR_WABA_ID>/messages",
  data,
  config
  )
  .then((result) => console.log(result))
  .catch((err) => console.log(err));

  return res.sendStatus(200);
}

Replace YOUR_WABA_ID with your WhatsApp Business ID from your WhatsApp App dashboard and API_VERSION with a compatible Cloud API version (default v15.0)

The app is set!

To test it, the ngrok tunnel should still be running, and you’ll need to start the express server in a separate terminal:

node customMessages.js

Other Shopify Events

In addition to order placement, Shopify offers over 50 webhooks for different events. You can subscribe for cart creation and updates, product collection creation and updates, successful and failed billing attempts, and many others.

To use any of these webhooks, follow a similar pattern as described above by creating a new webhook in your Shopify admin and registering the topic as a route in your express server.

As you’ve seen, the WhatsApp Business Platform helps you communicate seamlessly with your customers both manually or programmatically based on events in your Shopify store.

Shopify’s WhatsApp integration allows you to send bulk messages to your customers in real time. Messages can be sent automatically (for example, based on an event) or manually. Not only is it easy to set up, but also quite scalable. Pairing WhatsApp and Shopify makes customer communication consistent, effective, and impactful.

For more on how you can integrate WhatsApp into your apps and projects, see our other developer tutorials.


Get our newsletter

Sign up for monthly updates from Meta for Developers.

Sign up