Shopify graphql admin api and webhook script ERROR ==> please help me

Edith_Jenkins1
New Member
6 0 0

Hi, everyone.

 

require('isomorphic-fetch');
const dotenv = require('dotenv');
const Koa = require('koa');
const next = require('next');
const { default: createShopifyAuth } = require('@shopify/koa-shopify-auth');
const { verifyRequest } = require('@shopify/koa-shopify-auth');
const session = require('koa-session');

dotenv.config();

const { default: graphQLProxy } = require('@shopify/koa-shopify-graphql-proxy');
const { ApiVersion } = require('@shopify/koa-shopify-graphql-proxy');

const { receiveWebhook, registerWebhook } = require('@shopify/koa-shopify-webhooks');

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

const { SHOPIFY_API_SECRET_KEY, SHOPIFY_API_KEY, SHOPIFY_APP_URL } = process.env;

const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');

app.prepare().then(() => {
  const server = new Koa();
  const router = new Router();
  server.use(session({ secure: true, sameSite: 'none' }, server));

  server.keys = [SHOPIFY_API_SECRET_KEY];

  server.use(
    createShopifyAuth({
      apiKey: SHOPIFY_API_KEY,
      secret: SHOPIFY_API_SECRET_KEY,
      scopes: ['write_products', 'write_orders'],
      async afterAuth(ctx) {
        const { shop, accessToken, scope } = ctx.session;
        ctx.cookies.set('shopOrigin', shop, {
          httpOnly: false,
          secure: true,
          sameSite: 'none'
        });

        const registerProductsUpdate = await registerWebhook({
          address: `${SHOPIFY_APP_URL.replace(/https:\/\//, "")}/webhooks/products/update`,
          topic: 'PRODUCTS_UPDATE',
          accessToken: accessToken,
          shop: shop,
          ApiVersion: ApiVersion.October20
        });
        if (registerProductsUpdate.success) {
          console.log('Successfully registered webhook PRODUCTS_UPDATE !');
        } else {
          console.log('Failed to register webhook PRODUCTS_UPDATE ', registerProductsUpdate.result);
        }




        const registerOrderCreate = await registerWebhook({
          address: `${SHOPIFY_APP_URL.replace(/https:\/\//, "")}/webhooks/orders/create`,
          topic: 'ORDERS_CREATE',
          accessToken: accessToken,
          shop: shop,
          ApiVersion: ApiVersion.October20
        });
        if (registerOrderCreate.success) {
          console.log('Successfully registered webhook ORDERS_CREATE !');
        } else {
          console.log('Failed to register webhook ORDERS_CREATE ', registerOrderCreate.result);
        }

        ctx.redirect(`/?shop=${shop}`);

      },
    }),
  );

  const webhook = receiveWebhook({ secret: SHOPIFY_API_SECRET_KEY });

  router.post('/webhooks/products/update', webhook, (ctx) => {
    try {
      console.log(`Webhook processed, returned status code 200`);
    } catch (error) {
      console.log(`Failed to process webhook: ${error}`);
    }
  });
  router.post('/webhooks/orders/create', webhook, (ctx) => {
    try {
      console.log(`Webhook processed, returned status code 200`);
    } catch (error) {
      console.log(`Failed to process webhook: ${error}`);
    }
  });




  server.use(graphQLProxy({ version: ApiVersion.October20 }));

  const handleRequest = async (ctx) => {
    await handle(ctx.req, ctx.res);
    ctx.respond = false;
    ctx.res.statusCode = 200;
  };

  router.get("(/_next/static/.*)", handleRequest); // Static content is clear
  router.get("/_next/webpack-hmr", handleRequest); // Webpack content is clear
  router.get("(.*)", verifyRequest(), handleRequest); // Everything else must have sessions

  server
    .use(router.allowedMethods())
    .use(router.routes());

  server.listen(port, () => {
    console.log(`> Ready on http://localhost:${port}`);
  });
});

 

 

But I got the error 

 

FetchError: invalid json response body at https://*****.myshopify.com/admin/api/undefined/graphql.json reason: Unexpected end of JSON input

 

I can't register any webhook.

Please help me asap

 

0 Likes
Kevin_A
Shopify Staff
Shopify Staff
244 32 45

Hey @Edith_Jenkins1 

It doesn't look like you are defining an API version there. That could possibly be the problem. 

Kevin_A | Developer Support @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit Shopify.dev or the Shopify Web Design and Development Blog

0 Likes
Edith_Jenkins1
New Member
6 0 0

As you see, I define api version 

ApiVersion: ApiVersion.October20 

 

0 Likes
Kevin_A
Shopify Staff
Shopify Staff
244 32 45

Hey @Edith_Jenkins1 

Ah yes I missed that. Can you log the x-request-id response header if possible and send me that? 

Kevin_A | Developer Support @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit Shopify.dev or the Shopify Web Design and Development Blog

0 Likes