How to execute Shopify Admin API when webhooks are captured

Solved

How to execute Shopify Admin API when webhooks are captured

vinh0225
Shopify Partner
4 1 0

I am using "shopify-app-remix-template" for building my shopify app. I want to get some information from Shopify using Shopify Admin API when I capture "CARTS_UPDATE" webhook. But I can't get "AdminAPIContext" in webhooks.jsx file. What should I do? I share my code at the below.

- I tried to use admin from "const { admin } = await authenticate.webhook(request)", but it doesn't have graphql function so that "admin.graphql" was not working.

- I tried "const { admin } = await authenticate.admin(request);" but it says 

Click to expand...
[shopify-app/DEBUG] Request is from a bot, skipping auth

 

 

 

 

 

 

 

 

 

// shopify.server.js
import "@shopify/shopify-app-remix/adapters/node";
import {
  AppDistribution,
  DeliveryMethod,
  shopifyApp,
  LATEST_API_VERSION,
} from "@shopify/shopify-app-remix/server";
import { PrismaSessionStorage } from "@shopify/shopify-app-session-storage-prisma";
import { restResources } from "@shopify/shopify-api/rest/admin/2023-10";
import { LogSeverity } from "@shopify/shopify-app-remix/server";

import prisma from "./db.server";

const shopify = shopifyApp({
  apiKey: process.env.SHOPIFY_API_KEY,
  apiSecretKey: process.env.SHOPIFY_API_SECRET || "",
  apiVersion: LATEST_API_VERSION,
  scopes: process.env.SCOPES?.split(","),
  appUrl: process.env.SHOPIFY_APP_URL || "",
  authPathPrefix: "/auth",
  sessionStorage: new PrismaSessionStorage(prisma),
  distribution: AppDistribution.AppStore,
  restResources,
  logger: {
    level: LogSeverity.Debug
  },
  webhooks: {
    APP_UNINSTALLED: {
      deliveryMethod: DeliveryMethod.Http,
      callbackUrl: "/webhooks",
    },
    CARTS_UPDATE: {
      deliveryMethod: DeliveryMethod.Http,
      callbackUrl: "/webhooks",
      callback: async (topic, shopDomain, session, admin, payload) => {},
    }
  },
  hooks: {
    afterAuth: async ({ session }) => {
      shopify.registerWebhooks({ session });
    },
  },
  ...(process.env.SHOP_CUSTOM_DOMAIN
    ? { customShopDomains: [process.env.SHOP_CUSTOM_DOMAIN] }
    : {}),
});

export default shopify;
export const apiVersion = LATEST_API_VERSION;
export const addDocumentResponseHeaders = shopify.addDocumentResponseHeaders;
export const authenticate = shopify.authenticate;
export const unauthenticated = shopify.unauthenticated;
export const login = shopify.login;
export const registerWebhooks = shopify.registerWebhooks;
export const sessionStorage = shopify.sessionStorage;

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

// webhooks.jsx
import { authenticate } from "../shopify.server";
import db from "../db.server";

const updateOrders = (graphql) => {
  try {
      const response = await graphql(`
          query getOrders {
            orders (first: 30, query: "status:any") {
              edges {
                node {
                  id
                  name
                  note
                  updatedAt
                }
              }
            }
          }
        `);
        const responseJson = await response.json();
  
        const orders = responseJson?.data?.orders?.edges?.map(
          (edge) => edge.node
        ) || [[]];
  
        console.log("Orders to store: ", orders);
    } catch (exception) {
      console.log("Failed to get orders.", exception);
    }
};

export const action = async ({ request }) => {
  const { topic, shop, session, admin, payload } = await authenticate.webhook(
    request
  );
  if (!admin) {
    // The admin context isn't returned if the webhook fired after a shop was uninstalled.
    throw new Response();
  }

  switch (topic) {
    case "APP_UNINSTALLED":
      if (session) {
        await db.session.deleteMany({ where: { shop } });
      }
      break;
    case "CARTS_UPDATE":
      console.log("Cart Updated!");
      const { admin } = await authenticate.admin(request);
      updateOrders(admin.graphql);
      break;
    case "CUSTOMERS_DATA_REQUEST":
    case "CUSTOMERS_REDACT":
    case "SHOP_REDACT":
    default:
      throw new Response("Unhandled webhook topic", { status: 404 });
  }

  throw new Response();
};

 

 

 

 

 

 

 

 

 

 

Accepted Solution (1)

vinh0225
Shopify Partner
4 1 0

This is an accepted solution.

Reply 1 (1)

vinh0225
Shopify Partner
4 1 0

This is an accepted solution.