How to integrate billing in shopify-api-js

I am following the tutorial in https://shopify.dev/apps/getting-started/create and have successfully setup a test app that has frontend and backend running.

Now I am trying to test billing. I am following the instructions in https://github.com/Shopify/shopify-api-js/blob/main/docs/guides/billing.md and https://github.com/Shopify/shopify-api-js/blob/main/docs/reference/billing/check.md

I put the following codes in my web/index.js but it is not working.

async function billingMiddleware(req, res, next) {

  const session = res.locals.shopify.session;

  const hasPayment = await shopify.billing.check({
    session,
    plans: ['My billing plan'],
    isTest: true,
  });

  if (hasPayment) {
    next();
  } else {
    // Either request payment now (if single plan) or redirect to plan selection page (if multiple plans available), e.g.
    const confirmationUrl = await shopify.billing.request({
      session,
      plan: 'My billing plan',
      isTest: true,
    });

    res.redirect(confirmationUrl);
  }
}

app.use('/*', billingMiddleware);

I am not sure if it is the right thing to retrieve the session from

res.locals.shopify.session because the doc said I need to do the following

  // use sessionId to retrieve session from app's session storage
  // In this example, getSessionFromStorage() must be provided by app
  const session = await getSessionFromStorage(sessionId);

I see this error

2023-01-06 14:25:39 | backend | TypeError: Cannot read properties of undefined (reading ‘session’)

Anyone can share or point me to example how this is implemented? I just want to test out a simple global gate where user will be redirected to the billing page if they have not paid.

Hey @Thomas_Kwan :waving_hand:

After a bit of digging and searching for the generic error Cannot read properties of undefined (reading ‘session’) , there are many examples of the error in Stackoverflow, eg. here and here. Have you already worked through the library docs example of session storage configuration?

If so, and you still feel there is an issue with our library or example apps - please consider creating a Github issue in the repo for the official Node.js library and include as much detail as possible. Otherwise, keep an eye out here on the forums should someone else in the community have additional insights.

Cheers!

This is the problem with shopify docs, its soooo INCOMPLETE and some outdated.
shopify.session.getCurrentId wont work in the latest node boilerplate it should be shopify.api.session.getCurrentId
but the problem now is they didnt give us example of

getSessionFromStorage()

Hi @geobertz , any news about a solution?
Thank you for your help.