How to set up the app uninstall webhook

Solved
MarcoDo
Excursionist
16 4 1

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.

MarcoDo
Excursionist
16 4 1

This is an accepted solution.

already solved in the text above.

0 Likes