Step 1: Set Up Your Node.js Server
- Install Dependencies: Ensure you have
express
andbody-parser
installed. You can install them using npm:
npm install express body-parser
- Create Your Server: Create a file named
server.js
and set up your Express server to listen for POST requests on a specific endpoint, as shown in your code snippet.
Here’s the code from your image with a few additions:
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const PORT = 3000
app.use(bodyParser.json())
app.post('/webhook/orders/create', (req, res) => {
const orderData = req.body
console.log('Order data received', orderData)
res.status(200).send('Webhook received')
})
app.listen(PORT, () => {
console.log(`Server is running at port ${PORT}`)
})
Step 2: Create Webhook in Shopify Admin
- Log In to Shopify Admin: Go to your Shopify admin dashboard.
- Navigate to Webhooks:
- Go to
Settings
>Notifications
. - Scroll down to the Webhooks section and click on
Create webhook
.
- Go to
- Configure the Webhook:
- Event: Choose the event you want to subscribe to (e.g.,
Orders Create
). - Format: Choose
JSON
. - URL: Enter the URL where your server is running, e.g.,
https://yourdomain.com/webhook/orders/create
. If you’re running it locally, you can use a tool like ngrok to expose your local server to the internet. - Save: Click
Save webhook
.
- Event: Choose the event you want to subscribe to (e.g.,
Step 3: Test Your Webhook
- Trigger the Event: In your Shopify store, perform an action that triggers the webhook (e.g., create a new order).
- Check the Server Logs: Your server should log the webhook data received.
Additional Tips
- Security: Verify the integrity of the webhook requests to ensure they come from Shopify. You can do this by checking the
X-Shopify-Hmac-Sha256
header. - Error Handling: Implement proper error handling in your server code to deal with potential issues.
Example: Verifying Webhook Integrity
Here’s an example of how you might verify the HMAC signature to ensure the request is from Shopify:
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_key'
const hash = crypto
.createHmac('sha256', secret)
.update(body, 'utf8', 'hex')
.digest('base64')
if (hash === hmac) {
console.log('Order data received', req.body)
res.status(200).send('Webhook received')
} else {
res.status(403).send('Invalid signature')
}
})
This setup should get you started with handling Shopify webhooks using Node.js. If you have any more questions or need further assistance, feel free to ask!
4o
Leave a Reply