DEV Community

Cover image for Building a Serverless Bridge: Syncing Magento 2 Orders to Google Sheets in Real-Time
Hayrullah Kar
Hayrullah Kar

Posted on

Building a Serverless Bridge: Syncing Magento 2 Orders to Google Sheets in Real-Time

E-commerce operations live and die by data velocity. For enterprise engineering teams running Magento 2 (Adobe Commerce), extracting transactional order data for downstream fulfillment, accounting, or B2B sales pipelines can be a persistent infrastructure bottleneck.

Most companies either rely on archaic end-of-day CSV exports or pay hundreds of dollars a month for third-party middleware connectors that choke under heavy seasonal API polling limits.

Today, we will eliminate the middleman entirely. We are building a direct, serverless, event-driven data bridge between Magento 2 and Google Workspace using native observers and a lightweight Google Apps Script endpoint to ingest order data the exact second a checkout is completed.


1. System Architecture Diagram

Instead of wasteful API polling loops, we deploy an event-driven push topology utilizing an HTTP POST transaction.

[Storefront Checkout Completion]


[Magento 2 Observer Interceptor] ──> sales_order_place_after


[Outbound HTTPS POST Payload] ──> Cryptographic SHA Token Validation

This model is completely standalone. No middleware, no background pooling daemons, and zero infrastructure costs.


2. Setting Up the Google Workspace Web App Listener

First, open a fresh Google Sheet, name the active sheet container LiveOrders, and set up your tracking schema headers in Row 1: Magento Order ID, Status, Grand Total, and Customer Email.

Navigate to Extensions > Apps Script and deploy the following webhook listener. To prevent bad actors from executing brute-force payload floods into your sheets, we implement a cryptographic static token gate:

// Code.gs

// Cryptographic token shared only by your Magento Node and Apps Script
const WEBHOOK_SECRET = "MageSheet_Super_Secret_2026"; 

function doPost(e) {
  try {
    const payload = JSON.parse(e.postData.contents);

    // Security Gate: Verify token integrity
    if (payload.secret !== WEBHOOK_SECRET) {
      return ContentService.createTextOutput("Forbidden: Invalid Secret Key").setStatusCode(403);
    }

    const order = payload.order_data;
    const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("LiveOrders");

    // Execute atomic append operation
    sheet.appendRow([
      order.increment_id,
      order.status,
      order.grand_total,
      order.customer_email
    ]);

    return ContentService.createTextOutput(JSON.stringify({"status": "success"}))
      .setMimeType(ContentService.MimeType.JSON);

  } catch (error) {
    return ContentService.createTextOutput("Error: " + error.message).setStatusCode(500);
  }
}
Enter fullscreen mode Exit fullscreen mode

Production Deployment Strategy:
In the Apps Script IDE, select Deploy > New deployment.

Choose Web app.

Configure the deployment parameters exactly: Execute as: Me, Who has access: Anyone. (Mandatory for unauthenticated webhook targets).

Save and copy the production execute endpoint URL.

  1. Registering the Native Event Observer in Magento 2 Magento 2 features a robust event-driven dependency injection layout. To intercept successful checkout actions without hacking core models, we initialize a clean module interceptor under the namespace MageSheet_GoogleSync.

Define your event trigger target inside your module configuration space at app/code/MageSheet/GoogleSync/etc/events.xml:

<?xml version="1.0"?>
<config xmlns:xsi="[http://www.w3.org/2001/XMLSchema-instance](http://www.w3.org/2001/XMLSchema-instance)" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="sales_order_place_after">
        <observer name="magesheet_sync_order_to_google" instance="MageSheet\GoogleSync\Observer\SyncOrder" />
    </event>
</config>
Enter fullscreen mode Exit fullscreen mode

Next, compose the operational execution logic within your Observer handler file at app/code/MageSheet/GoogleSync/Observer/SyncOrder.php:

<?php
namespace MageSheet\GoogleSync\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\HTTP\Client\Curl;

class SyncOrder implements ObserverInterface
{
    protected $curl;

    public function __construct(Curl $curl)
    {
        $this->curl = $curl;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $order = $observer->getEvent()->getOrder();

        // Target endpoint generated during the Apps Script Web App step
        $googleAppUrl = "[https://script.google.com/macros/s/AKfycby..._YOUR_DEPLOYMENT_ID/exec](https://script.google.com/macros/s/AKfycby..._YOUR_DEPLOYMENT_ID/exec)";

        $payload = [
            "secret" => "MageSheet_Super_Secret_2026",
            "order_data" => [
                "increment_id" => $order->getIncrementId(),
                "status" => $order->getStatus(),
                "grand_total" => $order->getGrandTotal(),
                "customer_email" => $order->getCustomerEmail()
            ]
        ];

        $this->curl->addHeader("Content-Type", "application/json");
        $this->curl->post($googleAppUrl, json_encode($payload));
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. ⚠️ Production Warning: Moving from Synchronous to Asynchronous Processing While executing the raw cURL code block directly inside the observer scope passes staging and development benchmarks, doing so synchronously in high-traffic production environments is an absolute anti-pattern.

A synchronous implementation blocks PHP execution threads on the core storefront layout. Your customer's browser will hang on the "Place Order" screen until Google Apps Script completes its cell allocation and resolves the network response. If Google’s cloud network encounters a 2-second latency spike, your core checkout path stalls by 2 seconds—exponentially spiking cart abandonment rates.

The Decoupled Engineering Blueprint
For production environments, you must decouple the outbound HTTP transaction from the main customer thread. You have two clear options:

Magento Message Queues (Recommended): Publish the raw order array to an AMQP broker (like RabbitMQ). An active consumer worker processes the queue asynchronously in the background, firing payloads to Apps Script without interfering with the user experience.

Cron Worker Ingestion: Write data rows to a temporary database collection (magesheet_sync_queue) during checkout, and process entries sequentially using a background PHP CLI process executing on a recurring cron schema.

  1. Enterprise Downstream Expansion Once your order events flow smoothly into Google Workspace, you have an agile data baseline. You can instantly expand this architecture to run downstream automation workflows without adding heavy overhead:

Real-Time Data Visualizations: Connect the raw sheet data range to a Looker Studio view for instant performance monitoring.

Logistics Webhooks: Trigger automated SpreadsheetApp event hooks to dispatch shipments straight to 3PL vendor networks.

Automated Accounting: Instantly compile row arrays into branded PDF purchase invoices saved to a shared secure corporate Google Drive.

The full architectural blueprint with production-ready code examples and deep-dive optimization strategies is available on the MageSheet blog.

Read the complete technical guide here: Syncing Magento 2 Orders to Google Sheets in Real-Time

For enterprise data automation pipelines, custom ERP integrations, and advanced Google Workspace engineering designed to handle high transaction volumes, explore our platform library at MageSheet.

Top comments (0)