Get products using Offline accessToken

Get products using Offline accessToken

rmohan
Shopify Partner
1 0 0

Hi, I am new to Shopify. Created an app and I have obtained the  accessToken after initiating oAuth in my application. I am storing the accessToken in the database.

A background Job need to access the products from my store and update some details.

I am using Node 'shopify/shopify-api' package.

 

As per the documentation I need to call `new shopify.clients.Rest({session});`. I am not sure how can I get session.

Since I am in the Worker Job, there is no request context or cookies to get the session. Can you pls help?

 

//Example code from shopify Readme
const
sessionId = await shopify.session.getCurrentId({ rawRequest: req, rawResponse: res, }); // use sessionId to retrieve session from app's session storage // getSessionFromStorage() must be provided by application const session = await getSessionFromStorage(sessionId); const client = new shopify.clients.Rest({session});

 

Reply 1 (1)

BSSCommerce-B2B
Shopify Partner
1211 316 371

Hi @rmohan,

I hope you are doing well.

you are developing a worker job using access token, you should call GraphQL or REST API by Node's Fetch API instead of Shopify API package

BSSCommerceB2B_0-1724285049911.png

here an example

try {
        const query =  `query {
                      products(first: 10) {
                        edges {
                          node {
                            id
                            title
                          }
                        }
                      }
                    }`

        let response = await fetch(`https://${domain}/admin/api/2024-07/graphql.json`,{
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-Shopify-Access-Token': `${accessToken}`
          }
});
        let data = await response.json()
    } catch (e) {
        console.error(e.message);
    }

 

If your worker job is running on the same server with your app, then first, you should know which type of session storage your app is using. It can be memory (no way to get) or a db like redis, SQLite (easy to connect). After you retrieve session from storage, parse it like this

import { Session } from "@shopify/shopify-api";

async function retrieveProducts(domain) {
...
// const sessionId = ... (it usually be `offline_${domain}`)
// const sessionObj = queryFromDB(sessionId);
const session = new Session(sessionObj);
...
}

 I hope my information is useful to you. 🤗

 

If our suggestions are useful, please let us know by giving it a like, marking it as a solution.


BSS: B2B Wholesale Solution |BSS: B2B Portal, Quote, Net 30 | B: B2B Lock Password Protect


Need help from our expert? Kindly share your request with us via community@bsscommerce.com


BSS Commerce - Full-service eCommerce Agency