How to Set Up App Uninstall Webhook in Shopify
Published on Aug 25, 2024
Introduction
Setting up webhooks in Shopify is crucial for maintaining real-time communication between your app and the Shopify platform. One particularly important webhook is the app uninstall webhook, which notifies your app when a merchant uninstalls it. This guide will walk you through the process of setting up the app uninstall webhook using the Shopify CLI, React, and Node.js.
Understanding Webhooks in Shopify
What are Webhooks?
Webhooks are automated messages sent from apps to notify external systems about events that occur within the app. In the context of Shopify, webhooks allow your app to receive real-time notifications about various events happening in a merchant’s store.
Importance of the App Uninstall Webhook
The app uninstall webhook is particularly important because it allows your app to perform necessary cleanup tasks when a merchant removes your app from their store. This can include actions like removing stored data, canceling subscriptions, or updating your internal records.
Types of Shopify Webhooks
While this guide focuses on the app uninstall webhook, it’s worth noting that Shopify offers numerous webhook topics for various events, such as order creation, product updates, and customer data changes.
Setting Up the App Uninstall Webhook
Creating the Webhook Subscription
The first step in setting up the app uninstall webhook is to create a webhook subscription. This is typically done using Shopify’s GraphQL Admin API. Here’s a function that demonstrates how to add the webhook:
const { default: Shopify } = require('@shopify/shopify-api');
const callbackUrl = "https://your-app-url.com/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;
};
Calling the Webhook Creation Function
Once you have defined the addWebhook
function, you need to call it at the appropriate time. Typically, this is done after the authentication process is complete. Here’s an example of how to do this using the createShopifyAuth
middleware:
server.use(
createShopifyAuth({
async afterAuth(ctx) {
const { shop, accessToken, scope } = ctx.state.shopify;
addWebhook(shop, accessToken);
ctx.redirect(`/?shop=${shop}`);
},
})
);
Setting Up the Webhook Route
The final step is to set up a route in your server to handle the incoming webhook. This route should match the callbackUrl
you specified when creating the webhook subscription. Here’s an example using the Koa router:
router.post('/webhooks/app/uninstalled', handleUninstall);
Handling the Uninstall Webhook
Creating the Uninstall Handler
The handleUninstall
function is where you’ll process the webhook and perform any necessary cleanup actions. Here’s a basic example:
const handleUninstall = (ctx) => {
console.log("App uninstalled from shop:", ctx.request.headers['x-shopify-shop-domain']);
// Perform cleanup actions here
ctx.status = 200;
};
Common Issues and Solutions
When implementing the uninstall webhook, developers may encounter some common issues. Here are a few to be aware of:
Incorrect Header Access: Make sure you’re accessing the shop domain correctly from the headers. Use
ctx.request.headers['x-shopify-shop-domain']
instead ofctx.header["x-shopify-shop-domain"]
.Response Handling: Shopify expects a 200 status code in response to successful webhook processing. Ensure you’re setting the status correctly, like
ctx.status = 200
in Koa.Continuous Webhook Firing: If Shopify keeps sending the same webhook, it might be because you’re not responding correctly. Always send a 200 status code, even if you encounter an error during processing.
Best Practices for Webhook Implementation
Error Handling
Implement robust error handling in your webhook processing. Log errors for debugging, but always respond with a 200 status to acknowledge receipt of the webhook.
Verification
Always verify the authenticity of incoming webhooks using Shopify’s HMAC validation to ensure they’re genuinely from Shopify.
Asynchronous Processing
For time-consuming tasks, consider acknowledging the webhook immediately and processing the data asynchronously to avoid timeouts.
Conclusion
Setting up the app uninstall webhook is a crucial step in developing a robust Shopify app. By following this guide, you should now be able to successfully implement this important feature in your app. Remember to test thoroughly and handle edge cases to ensure a smooth experience for your users.
For more information on Shopify webhooks and app development, visit the official Shopify documentation at https://shopify.dev/api/admin-rest/webhook.
Take Our Quick Quiz:
Which primary product image do you think has the highest conversion rate?