Step 1: Set Up Your Node.js Project
- Initialize your Node.js project:
mkdir shopify-google-sheets
cd shopify-google-sheets
npm init -y
Install necessary packages:
npm install express body-parser googleapis
Step 2: Create the Server File
- Create a file named
server.js
and add the following code:
const express = require('express')
const bodyParser = require('body-parser')
const { google } = require('googleapis')
const keys = require('./credentials.json') // Google service account credentials
const app = express()
const PORT = 3000
app.use(bodyParser.json())
const auth = new google.auth.GoogleAuth({
credentials: keys,
scopes: ['https://www.googleapis.com/auth/spreadsheets'],
})
const sheets = google.sheets({ version: 'v4', auth })
async function appendOrderToSheet(orderData) {
const sheetId = 'your_google_sheet_id' // Replace with your Google Sheet ID
const range = 'Sheet1!A1' // Replace with your desired sheet and range
const values = [
[orderData.id, orderData.email, orderData.total_price, new Date(orderData.created_at).toLocaleString()],
// Add other order data fields as needed
]
const resource = {
values,
}
await sheets.spreadsheets.values.append({
spreadsheetId: sheetId,
range,
valueInputOption: 'RAW',
resource,
})
}
app.post('/webhook/orders/create', async (req, res) => {
const orderData = req.body
console.log('Order data received', orderData)
try {
await appendOrderToSheet(orderData)
res.status(200).send('Webhook received and order saved to Google Sheets')
} catch (error) {
console.error('Error saving order to Google Sheets:', error)
res.status(500).send('Error saving order to Google Sheets')
}
})
app.listen(PORT, () => {
console.log(`Server is running at port ${PORT}`)
})
Step 3: Expose Your Local Server to the Internet
To test webhooks locally, you need to expose your local server to the internet using a tool like ngrok.
- Install ngrok:
npm install -g ngrok
Start your server:
node server.js
Run ngrok to expose your local server:
ngrok http 3000
Step 4: Create the Webhook in Shopify
- Log in to your Shopify admin panel.
- Navigate to
Settings
>Notifications
>Create Webhook
. - Configure the webhook:
- Event: Select
Order creation
. - Format: JSON
- URL: Use the public URL provided by ngrok, e.g.,
http://<ngrok-id>.ngrok.io/webhook/orders/create
.
- Event: Select
- Save the webhook.
Step 5: Test the Webhook
- Create a test order in your Shopify store.
- Check your server logs. You should see the order data logged when the webhook is triggered.
- Check your Google Sheet. The order data should be appended to the specified range.
Additional Notes:
- Make sure your webhook endpoint verifies the HMAC signature for security. Shopify sends a
X-Shopify-Hmac-Sha256
header with each webhook request which you can use to verify the authenticity of the request.
Here’s an example of verifying the HMAC signature:
const crypto = require('crypto')
app.post('/webhook/orders/create', (req, res) => {
const hmac = req.headers['x-shopify-hmac-sha256']
const body = JSON.stringify(req.body)
const secret = 'your_shopify_secret'
const hash = crypto.createHmac('sha256', secret).update(body, 'utf8').digest('base64')
if (hash === hmac) {
const orderData = req.body
console.log('Verified order data received', orderData)
try {
await appendOrderToSheet(orderData)
res.status(200).send('Webhook received and order saved to Google Sheets')
} catch (error) {
console.error('Error saving order to Google Sheets:', error)
res.status(500).send('Error saving order to Google Sheets')
}
} else {
console.log('Failed to verify HMAC signature')
res.status(403).send('Forbidden')
}
})
This setup will ensure your webhook handling is secure and reliable, and your orders are saved to Google Sheets automatically.
Leave a Reply