Node.js APP. Koa.js Server. Oauth Problem

Luka_Musashvili
New Member
1 0 0

Hi Shopify support team. I have an issue about Shopify custom apps (built in node.js) I had no any problems before, but my server keeps getting following error after I updated package.json and Shopify API version:
InternalServerError: Cannot complete OAuth process. Could not find an OAuth cookie for shop url: [my shop's name]

Here's my code:
require('isomorphic-fetch');
const dotenv = require('dotenv');
const Koa = require('koa');
const next = require('next');
const fs = require('fs');
const { default: createShopifyAuth } = require('@shopify/koa-shopify-auth');
const { verifyRequest } = require('@shopify/koa-shopify-auth');
const { default: Shopify, ApiVersion } = require('@shopify/shopify-api');
const Router = require('koa-router');
const path=require ("path")
const multer = require('@koa/multer')

dotenv.config();

Shopify.Context.initialize({
API_KEY: process.env.SHOPIFY_API_KEY,
API_SECRET_KEY: process.env.SHOPIFY_API_SECRET,
SCOPES: process.env.SHOPIFY_API_SCOPES.split(","),
HOST_NAME: process.env.SHOPIFY_APP_URL.replace(/https:\/\//, ""),
API_VERSION: ApiVersion.April21,
IS_EMBEDDED_APP: true,
SESSION_STORAGE: new Shopify.Session.MemorySessionStorage(),
});

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

const ACTIVE_SHOPIFY_SHOPS = {};

app.prepare().then(() => {
const server = new Koa();
const router = new Router();
server.keys = [Shopify.Context.API_SECRET_KEY];

server.use(
createShopifyAuth({
async afterAuth(ctx) {
const { shop, scope, accessToken } = ctx.state.shopify;
ACTIVE_SHOPIFY_SHOPS[shop] = scope;
ctx.cookies.set('shopOrigin', shop, { httpOnly: false });
ctx.cookies.set('accessToken', accessToken );
ctx.redirect("/");
console.log(shop, scope, accessToken);
/* Register webhook for orders paid */
// const registrationOrderPaid = await Shopify.Webhooks.Registry.register({
// shop,
// accessToken,
// path: '/getorders',
// topic: 'orders/paid',
// apiVersion: ApiVersion.April21,
// webhookHandler: (_topic, _shop, body) => {
// console.log('received order paid webhook: ');
// const obj = JSON.parse(body);
// console.log(obj);
// filter(obj);
// function filter(obj){
// var countryCode = obj.shipping_address.country_code;
// var ProductNum = obj.line_items.length;
// var SKUTrue = 0;
// for (i=0;i<ProductNum;i++){
// var SKU = obj.line_items[i].sku;
// if (SKU == "XYZ"){
// SKUTrue += 1;
// }
// }
// if(countryCode == "DE" || SKUTrue > 0){
// console.log('send it (obj)')
// } else{
// console.log('dont send it')
// }
// }
// },
// });

// if (registrationOrderPaid.success) {
// console.log('Successfully registered Order Paid webhook!');
// } else {
// console.log('Failed to register Order Paid webhook', registrationOrderPaid.result);
// }
},
}),
);

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

router.get("/", async (ctx) => {
const shop = ctx.query.shop;
console.log(shop);
if (ACTIVE_SHOPIFY_SHOPS[shop] === undefined) {
ctx.redirect(`/auth?shop=${shop}`);
} else {
await handleRequest(ctx);
}
});

//#region Multer
//Upload File Storage Path and File Naming
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(__dirname ,'/public'))
},
filename: function (req, file, cb) {
let type = file.originalname.split('.')[1]
cb(null, `${req.body.case}-${req.body.order}-${Date.now().toString(16)}.${type}`)
}
})
//File upload restrictions
const limits = {
fields: 10,//Number of non-file fields
fileSize: 1000 * 2048,//File Size Unit b
files: 1//Number of documents
}
const upload = multer({storage,limits})
//#endregion
//#region post /user/file
router.post('/user/file', upload.single('file'), async (ctx,next)=>{
ctx.body = {
code: 1,
data: ctx.file,
fulldata: ctx
}
ctx.error
await next();
})
//#endregion
//#region get /user/files
router.get('/user/files', async (ctx,next) => {
//const Folder = './public/';
//fs.readdir(Folder, (err, files) => {
// ctx.body = files;
// console.log(ctx.body);
// ctx.error
//});
ctx.body = {mycode : 1}
ctx.error
console.log(ctx.body);
await next();
})
//#endregion

router.post('/getorders', async (ctx) => {
await Shopify.Webhooks.Registry.process(ctx.req, ctx.res);
console.log(`Webhook processed with status code 200`);
});


router.get("(/_next/static/.*)", handleRequest);
router.get("/_next/webpack-hmr", handleRequest);
router.get("(.*)", verifyRequest(), handleRequest);

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

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

This is what I get if I uncomment the webhook part:
InternalServerError: Cannot read property 'webhookSubscriptions' of undefined

0 Likes