How can I resolve a CORS error in Shopify Billing API?

JuiceN2
Tourist
4 0 4

Hey,


App is written on shopify-node-js-template.

I am having issues with CORS when trying to make redirect to Shopify Billing (API) page.

 

 

Access to fetch at 'https://[SHOPIFY_STORE].myshopify.com/admin/charges/[UID]/[UID]/RecurringApplicationCharge/confirm_recurring_application_charge?signature=[SIGNATURE]' 

(redirected from 'https://[APP_URL].herokuapp.com/api/select-plan') from origin 'https://[APP_URL].herokuapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 

If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

 

 

Flow:
1) On frontend I have a simple form that makes a POST request to /api/select-plan.

 

 

const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
        body: JSON.stringify({
          selectedPlan: selected[0],
        })
    };

    const response = await fetch("/api/select-plan", requestOptions);

    var body = await response.json();
    console.log(body);
    if(body.status == "success"){
       console.log(body.message);
    } else {
      console.log(body.message);
    }

 

 


2) Backend code: 

 

app.post('/api/select-plan', async (_req, res, next) => {
  const session = res.locals.shopify.session;
  const confirmationUrl = await shopify.api.billing.request({
    session: res.locals.shopify.session,
    plan: _req.body.selectedPlan,
    isTest: true,
  });
  res.redirect(confirmationUrl);
  next
  
});

 

 

 

Does anyone have a clue how I could fix this?

Reply 1 (1)

growcommerce
Shopify Partner
4 0 0

Please try with blow codes.

API response:

 

const billingResponse = await shopify.api.billing.request({
      session,
      plan: plan_select,
      trialDays: 7,
      isTest: true,
      returnObject: true,
    });
    
    res.status(200).send({success: true, confirmationUrl: billingResponse.confirmationUrl});

 


React code 

 

import createApp from '@shopify/app-bridge';
import {Redirect} from '@shopify/app-bridge/actions';

.......
.......
const config = {
    // The client ID provided for your application in the Partner Dashboard.
    apiKey: "Your client ID",
    // The host of the specific shop that's embedding your app. This value is provided by Shopify as a URL query parameter that's appended to your application URL when your app is loaded inside the Shopify admin.
    host: new URLSearchParams(location.search).get("host"),
    forceRedirect: true
  };
  const app = createApp(config);
  const redirect = Redirect.create(app);
redirect.dispatch(Redirect.Action.REMOTE, {
          url: data.confirmationUrl,
          newContext: true,
 });