shopifyshopify-appshopify-apishopify-api-nodeshopify-activemerchant

Oauth error invalid_request: The authorization code was not found or was already used " shopify. showing error like this when i hit api with code


{
    "client_id":"",
    "client_secret":"",
    "code":""
}
https://test-app.myshopify.com/admin/oauth/access_token

when iam hiting api to this endpoint for getting offline access token showing error like that says The authorization code was not found or was already used.

 app.get("/auth/callback", async (req, res) => {
        try {
          console.log("redirectUrl", req);
          const session = await Shopify.Auth.validateAuthCallback(
            req,
            res,
            req.query
          );
    
          const host = req.query.host;
          const code = req.query.code
          app.set(
            "active-shopify-shops",
            Object.assign(app.get("active-shopify-shops"), {
              [session.shop]: session.scope,
            })
          );
    
          const response = await Shopify.Webhooks.Registry.register({
            shop: session.shop,
            accessToken: session.accessToken,
            topic: "APP_UNINSTALLED",
            path: "/webhooks",
          });
    
          if (!response["APP_UNINSTALLED"].success) {
            console.log(
              `Failed to register APP_UNINSTALLED webhook: ${response.result}`
            );
          }
    
          // Redirect to app with shop parameter upon auth
          res.redirect(`/?shop=${session.shop}&host=${host}&code=${code}`);
        } catch (e) {
         
          }
        }
      });

taking code from the redirect URL and sent to iframe and post api from next webapp I cant able to find where the code is using from my side or it is a backend issue. currently I'm using access Token from the app to connect to shopify. is any refresh token available to refresh the token. we need a offline token that never expire.


Solution

  • finally I fount an answer.

    on server folder -> index.js there is a variable called USE_ONLINE_TOKENS Make its false and on middleware -> auth.js

    const redirectUrl = await Shopify.Auth.beginAuth(
      req,
      res,
      req.query.shop,
      "/auth/callback",
      false
    );
    

    this will create an offline token that will never expiries