@shopify/shopify-app-express 注册webhook
时间: 2024-01-13 10:05:08 浏览: 142
要在基于@shopify/shopify-app-express的应用程序中注册Shopify Webhook,可以使用该框架提供的webhook路由。下面是一个示例代码来注册一个Webhook:
```javascript
const { default: createShopifyAuth } = require('@shopify/koa-shopify-auth');
const { default: Shopify, ApiVersion } = require('@shopify/shopify-api');
const { verifyRequest } = require('@shopify/koa-shopify-auth');
const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const app = new Koa();
const router = new Router();
const webhook = {
topic: 'products/create',
address: 'https://your-app.com/webhooks/products/create',
format: 'json',
};
app.use(bodyParser());
const shopifyAuth = createShopifyAuth({
// Your Shopify app API key and secret
apiKey: process.env.SHOPIFY_API_KEY,
secret: process.env.SHOPIFY_API_SECRET,
// Your app URL
appUrl: process.env.APP_URL,
// Scopes to request on the merchant's behalf
scopes: ['read_products', 'write_products', 'read_script_tags', 'write_script_tags'],
// After authentication, redirect to the shop's home page
afterAuth(ctx) {
const { shop } = ctx.state.shopify;
ctx.redirect(`https://${shop}/admin/apps/${process.env.SHOPIFY_API_KEY}`);
},
});
// Register webhook
router.post('/webhooks/products/create', verifyRequest({ returnHeader: true }), (ctx) => {
console.log('New product created:', ctx.request.body);
ctx.status = 200;
});
(async function() {
// Create an instance of Shopify
const shopify = new Shopify({
apiKey: process.env.SHOPIFY_API_KEY,
apiSecretKey: process.env.SHOPIFY_API_SECRET,
shopName: ctx.session.shop,
accessToken: accessToken,
apiVersion: ApiVersion.October20,
autoLimit: { calls: 2, interval: 1000, bucketSize: 35 },
});
// Register webhook
await shopify.webhook.create(webhook);
// Use the shopifyAuth middleware
app.use(shopifyAuth);
app.use(router.allowedMethods());
app.use(router.routes());
app.listen(process.env.PORT, () => {
console.log(`Server listening on port ${process.env.PORT}`);
});
})();
```
在上面的代码中,我们首先创建一个Shopify实例,并使用它来注册Webhook。然后,我们使用@shopify/shopify-app-express框架创建一个HTTP服务器,并为Webhook的URL路径创建一个POST路由。在路由处理程序中,我们可以处理接收到的Webhook数据。最后,我们使用Shopify API将Webhook注册到商店中。
注意,我们在Webhook地址中使用了公共URL,这意味着您需要在您的应用程序中设置公共URL,并将其用作Webhook地址。此外,您需要在Shopify后台中配置相应的Webhook主题,以便将Webhook发送到正确的URL地址。
阅读全文