@happy-gastro/shopify
v1.0.0
Published
A Node.js package to integrate with Shopify for fetching products, collections, orders, and managing webhooks.
Maintainers
Readme
Happy Gastro Shopify Integration (@happy-gastro/shopify)
A robust, modular Node.js package for seamless integration with the Shopify Admin API. This library simplifies fetching products, collections, and orders, and provides dedicated services for managing and verifying webhooks.
Its class-based design allows you to import and use only the functionality you need.
Features
- Modular services for Products, Collections, Orders, and Webhooks.
- Simple, class-based instantiation.
- Fetches products, orders, custom collections, and smart collections.
- Creates and deletes webhooks.
- Securely verifies incoming webhooks using HMAC-SHA256 signature.
- Written in TypeScript with full type support.
Installation
npm install @happy-gastro/shopify axios express body-parserQuick Start
1. Configure the Client
First, create a configuration object with your Shopify store credentials. The webhookSecret is optional and only needed if you are verifying incoming webhooks.
- shopDomain: Your store's
.myshopify.comdomain (e.g.,your-store.myshopify.com). - accessToken: Your Admin API access token (starts with
shpat_). - apiVersion: The API version you want to use (e.g.,
2024-04). - webhookSecret (Optional): Your webhook signature secret key.
import { ShopifyConnectionKeys } from '@happy-gastro/shopify';
const shopifyConfig: ShopifyConnectionKeys = {
shopDomain: process.env.SHOPIFY_SHOP_DOMAIN!,
accessToken: process.env.SHOPIFY_ACCESS_TOKEN!,
apiVersion: '2024-04',
webhookSecret: process.env.SHOPIFY_WEBHOOK_SECRET, // Only needed for webhook verification
};2. Use Individual Services
Instantiate classes for the resources you want to interact with.
Fetching Products
import { Products } from '@happy-gastro/shopify';
const productsService = new Products(shopifyConfig);
async function fetchProducts() {
try {
const products = await productsService.getAll();
console.log(`Fetched ${products.length} products.`);
// Now you can sync this data with your local database.
} catch (error) {
console.error('Failed to fetch Shopify products:', error);
}
}
fetchProducts();Managing Webhooks with Express
This package makes it easy to create and verify webhooks. Below is an example of an Express server that sets up a webhook for new orders and verifies the incoming requests.
// See example/server.ts for a full working example.
import express from 'express';
import bodyParser from 'body-parser';
import { Webhooks, verifyShopifyWebhook } from '@happy-gastro/shopify';
const app = express();
const port = 3000;
const webhooksService = new Webhooks(shopifyConfig);
// IMPORTANT: Use bodyParser.raw to get the raw body for HMAC verification
app.post('/webhooks/orders/create', bodyParser.raw({ type: 'application/json' }), (req, res) => {
if (!shopifyConfig.webhookSecret) {
console.error('Webhook secret is not configured.');
return res.status(500).send('Webhook secret not configured.');
}
const isVerified = verifyShopifyWebhook({
rawBody: req.body, // req.body is a buffer here
hmacHeader: req.get('X-Shopify-Hmac-Sha256'),
secret: shopifyConfig.webhookSecret,
});
if (!isVerified) {
return res.status(401).send('Webhook not verified');
}
const orderData = JSON.parse(req.body.toString());
console.log(`Received a new order: #${orderData.order_number}`);
res.status(200).send('Webhook received');
});
// An endpoint to register the webhook
app.get('/setup-webhook', async (req, res) => {
const callbackUrl = 'https://your-public-server-url.com/webhooks/orders/create';
const webhook = await webhooksService.create({ topic: 'orders/create', address: callbackUrl });
res.json({ message: 'Webhook created!', webhook });
});
app.listen(port, () => console.log(`Server listening at http://localhost:${port}`));API Reference
Services
new Products(keys: ShopifyConnectionKeys)new Collections(keys: ShopifyConnectionKeys)new Orders(keys: ShopifyConnectionKeys)new Webhooks(keys: ShopifyConnectionKeys)
Service Methods
products.getAll(): Promise<ShopifyProduct[]>collections.getAll(): Promise<ShopifyCollection[]>orders.getAll(): Promise<ShopifyOrder[]>webhooks.create(options: { topic: string, address: string, format?: string }): Promise<ShopifyWebhook>webhooks.delete(webhookId: string): Promise<void>
Utility Functions
verifyShopifyWebhook(options: { rawBody: Buffer, hmacHeader: string | undefined, secret: string }): boolean: Verifies the HMAC signature of an incoming Shopify webhook request.
