Automate Shopify Orders to Google Sheets with Node.js and Webhooks | Shopify Tutorial

In today’s fast-paced e-commerce environment, automating workflows can save time and reduce errors, making business operations more efficient. One powerful way to achieve this in Shopify is by automating the process of recording orders in Google Sheets using Node.js and Shopify Webhooks. This tutorial will guide you through the steps to set up this automation, leveraging the Shopify API and Webhooks to ensure that every new order placed on your Shopify store is automatically added to a Google Sheets document. By the end of this tutorial, you’ll have a fully functional Node.js app that seamlessly integrates Shopify orders with Google Sheets.

Why Automate Shopify Orders to Google Sheets?

Before diving into the technical details, let’s explore why automating Shopify orders to Google Sheets is beneficial:

  • Real-Time Data Access: Automatically logging orders in Google Sheets allows you to access real-time order data in a familiar format, enabling quick analysis and reporting.
  • Data Backup: Google Sheets provides an additional layer of data backup, ensuring that your order information is safely stored outside of Shopify.
  • Simplified Reporting: With orders automatically recorded in Google Sheets, you can easily create custom reports and dashboards without needing to export data manually from Shopify.

Prerequisites

Before you begin, ensure you have the following prerequisites in place:

  • Node.js and npm: Make sure Node.js and npm (Node Package Manager) are installed on your machine.
  • Shopify Store: You need a Shopify store to connect to the Shopify API and set up webhooks.
  • Google Account: A Google account is required to create and manage Google Sheets.
  • Google Sheets API Enabled: Enable the Google Sheets API for your project in the Google Cloud Console and obtain the necessary credentials.

Step 1: Set Up a New Node.js Project

The first step is to set up a new Node.js project that will handle the Shopify Webhooks and interact with the Google Sheets API.

Initialize a New Node.js Project

Create a new directory for your project and navigate into it:

bashCopy codemkdir shopify-google-sheets
cd shopify-google-sheets

Initialize a new Node.js project:

bashCopy codenpm init -y

This command will create a package.json file, which will keep track of your project’s dependencies and scripts.

Install Required Packages

Next, install the required packages for your project:

bashCopy codenpm install express body-parser @shopify/shopify-api googleapis
  • express: A web framework for Node.js.
  • body-parser: Middleware for parsing incoming request bodies.
  • @shopify/shopify-api: A library to interact with the Shopify API.
  • googleapis: Google API client library for Node.js, used to interact with Google Sheets.

Step 2: Set Up Google Sheets API

To interact with Google Sheets, you need to set up API access.

Enable Google Sheets API

  1. Go to the Google Cloud Console.
  2. Create a new project or select an existing project.
  3. Navigate to the “APIs & Services” section and enable the “Google Sheets API.”
  4. Create credentials for a “Service Account” and download the JSON key file. This file will be used to authenticate your Node.js app with Google Sheets.

Configure Google Sheets API in Your Project

Place the downloaded JSON key file in your project directory. Then, create a new file named googleSheets.js to handle interactions with the Google Sheets API:

javascriptCopy codeconst { google } = require('googleapis');
const sheets = google.sheets('v4');
const auth = new google.auth.GoogleAuth({
  keyFile: 'path-to-your-json-key-file.json',
  scopes: ['https://www.googleapis.com/auth/spreadsheets'],
});

async function appendOrderToSheet(orderData) {
  const authClient = await auth.getClient();
  const spreadsheetId = 'your-spreadsheet-id';
  const range = 'Sheet1!A:E';

  const values = [
    [
      orderData.id,
      orderData.customer.email,
      orderData.total_price,
      orderData.created_at,
      orderData.line_items.map(item => item.name).join(', ')
    ],
  ];

  const resource = { values };
  await sheets.spreadsheets.values.append({
    auth: authClient,
    spreadsheetId,
    range,
    valueInputOption: 'USER_ENTERED',
    resource,
  });
}

module.exports = { appendOrderToSheet };

In this code:

  • Google Sheets API: The googleapis library is used to interact with the Google Sheets API.
  • appendOrderToSheet: This function adds a new row to your Google Sheet with order details.

Step 3: Set Up Shopify Webhooks

Shopify Webhooks allow your app to listen for specific events, such as when a new order is created.

Create a Webhook Endpoint

Create a new file named server.js to set up an Express server that will handle incoming Webhook requests:

javascriptCopy codeconst express = require('express');
const bodyParser = require('body-parser');
const { appendOrderToSheet } = require('./googleSheets');
const { Shopify, ApiVersion } = require('@shopify/shopify-api');

const app = express();
const port = process.env.PORT || 3000;

app.use(bodyParser.json());

app.post('/webhook/orders/create', async (req, res) => {
  try {
    const orderData = req.body;
    await appendOrderToSheet(orderData);
    res.status(200).send('Order received and logged.');
  } catch (error) {
    console.error('Error logging order to Google Sheets:', error);
    res.status(500).send('Internal Server Error');
  }
});

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

In this code:

  • /webhook/orders/create: This endpoint listens for Shopify order creation events and logs the order details to Google Sheets.
  • Express Server: The Express server handles incoming requests and responds accordingly.

Register the Webhook in Shopify

To register the Webhook in Shopify, you can use the Shopify Admin API. Here’s an example of how to do this using the @shopify/shopify-api library:

javascriptCopy codeconst { Shopify } = require('@shopify/shopify-api');

Shopify.Context.initialize({
  API_KEY: process.env.SHOPIFY_API_KEY,
  API_SECRET_KEY: process.env.SHOPIFY_API_SECRET,
  SCOPES: process.env.SCOPES.split(','),
  HOST_NAME: process.env.HOST.replace(/https?:\/\//, ''),
  API_VERSION: ApiVersion.October20,
  IS_EMBEDDED_APP: false,
  SESSION_STORAGE: new Shopify.Session.MemorySessionStorage(),
});

async function createWebhook() {
  const response = await Shopify.Webhooks.Registry.register({
    shop: process.env.SHOP,
    accessToken: process.env.SHOPIFY_ACCESS_TOKEN,
    path: '/webhook/orders/create',
    topic: 'ORDERS_CREATE',
    webhookHandler: async (topic, shop, body) => {
      console.log('Order webhook received:', body);
    },
  });

  if (!response.success) {
    console.log(`Failed to register webhook: ${response.result}`);
  } else {
    console.log('Webhook registered successfully!');
  }
}

createWebhook();

This script registers a Webhook with Shopify to listen for the ORDERS_CREATE event and directs it to the /webhook/orders/create endpoint on your server.

Step 4: Test Your Setup

With everything in place, it’s time to test your setup.

  1. Start Your Server: Run your Express server by executing:bashCopy codenode server.js
  2. Place a Test Order: Go to your Shopify store and place a test order.
  3. Check Google Sheets: Open your Google Sheet and verify that the order details have been logged.

Conclusion

By following this tutorial, you’ve set up an automated system that records Shopify orders in Google Sheets using Node.js and Webhooks. This integration ensures that your order data is always up-to-date and accessible in a format that’s easy to analyze and report. With the power of Shopify’s API and Google Sheets, you can further customize this setup to fit your specific business needs, such as adding more detailed order data or triggering other automation tasks.

As you continue to explore Shopify app development, mastering these integrations will allow you to build more efficient, data-driven solutions that enhance the functionality of your Shopify store.

Leave a Reply

Your email address will not be published. Required fields are marked *