Get offline access token from koa

Solved
Tourist
6 2 0

Hi, a newbie here.

Sorry for the basic question but can't find the answer elsewhere.

 

I am building an app which will execute background queries and mutations (not initiated from UI). So I am trying to get an offline access token but so far no luck. I am using Koa to authenticate against Shopify so I guess this is how it is supposed to work:

 
const server = new Koa();
server.use(session(server));
server.keys = [SHOPIFY_API_SECRET_KEY];
server.use(
    createShopifyAuth({
        apiKey: SHOPIFY_API_KEY,
        secret: SHOPIFY_API_SECRET_KEY,
        scopes: ['read_products', 'write_products', 'read_orders', 'write_orders'],
        async afterAuth(ctx) {
            const { shop, accessToken } = ctx.session;
            ctx.cookies.set('shopOrigin', shop, { httpOnly: false });

            //get offline access token
            //1. get code and hmac from URL <== how to get those
            //2. verify hmac
            //3. send POST to https://{shop}.myshopify.com/admin/oauth/access_token supplying client_id, client_secret and code from above


            ctx.redirect('/');
        },
    }),
);

Any advice how to get code and hmac from URL?

Thanks.

 
0 Likes
Highlighted

Success.

Tourist
6 2 0

Found the answer. ctx.query it is!

0 Likes
Tourist
6 2 0

Copying comment from another thread for the sake of full info:

 

Well, apparently you don't need to exchange the code to access token manually. koa-shopify-auth allows to request an offline access token as specified here: https://www.npmjs.com/package/@shopify/koa-shopify-auth

 

So final code look like this:

app.prepare().then(() => {
    const server = new Koa();    server.use(session(server));    server.keys = [SHOPIFY_API_SECRET_KEY];    server.use(        createShopifyAuth({            apiKey: SHOPIFY_API_KEY,            secret: SHOPIFY_API_SECRET_KEY,            scopes: ['read_products', 'write_products', 'read_orders', 'write_orders'],            accessMode: 'offline',
            async afterAuth(ctx) {
                const { shop, accessToken } = ctx.session;                ctx.cookies.set('shopOrigin', shop, { httpOnly: false });                console.log(`=========access token (offline):`, accessToken);
...

this access token can be used to execute GQL queries.

0 Likes