Topics covering webhook creation & management, event handling, Pub/Sub, and Eventbridge, in Shopify apps.
Hey all, I have been struggling to set up the app uninstall webhook with the Shopify-cli code and with the react/node.js tutorial course.
However, I found the solution and want to share it here in case anybody else needs help.
I use one function called "addWebhook.js":
const { default: Shopify } = require('@shopify/shopify-api');
const callbackUrl = "https://myngrok.ngrok.io/webhooks/app/uninstalled";
const topic = "APP_UNINSTALLED";
export const addWebhook = async (shop, accessToken) => {
const query = `mutation {
webhookSubscriptionCreate(
topic: ${topic},
webhookSubscription: {
callbackUrl: "${callbackUrl}",
format: JSON
}
)
{
webhookSubscription {
id
}
userErrors {
field
message
}
}
}`;
const client = new Shopify.Clients.Graphql(shop, accessToken);
const response = await client.query({
data: query,
});
try {
console.log("body.errors", response.body.errors);
console.log("body data", response.body.data);
}
catch (err ) {
console.log("err", err)
}
return 0;
};
Then I call the function afterAuth, which successfully sets up the webhook subscription. (Note: The same way you can subscribe to any other webhook topic)
e.g.
server.use(
createShopifyAuth({
async afterAuth(ctx) {
const { shop, accessToken, scope } = ctx.state.shopify;
addWebhook(shop, accessToken);
// Redirect to app with shop parameter upon auth
ctx.redirect(`/?shop=${shop}`);
},
})
)
in my server.js file, you can then just set up the route which you specified as the callbackUrl.
router.post('/webhooks/app/uninstalled', handleUninstall);
I use Koa, so in the above snippet router is imported from "koa-router".
Thats all you need to do to setup the app uninstall webhook.
Solved! Go to the solution
This is an accepted solution.
already solved in the text above.
This is an accepted solution.
already solved in the text above.
Hey can you share your handleUninstallFunction ? I am unable to send back res to shopify webhook and hence it keeps on firing again and again .
const handleUninstall = (req, res) => {
console.log(" in handle uninstall " , req);
ActiveShops.removeShop(req.header["x-shopify-shop-domain"]);
res.status(200).end();
};
This is what i have done but it says res.status is not a function
May be you mistakenly retrieve shop_url
Update as below:
ActiveShops.removeShop(req.header["x-shopify-shop-domain"]) to
ActiveShops.removeShop(req.headers['x-shopify-shop-domain'])