Search code examples
javascriptpostpaypalpaypal-sandboxpaypal-rest-sdk

Cannot send post request to test paypal integration in javascript app


I am trying to integrate paypal payment into a javascript application, but i am not able to test the orders processing because when i send a post request within createOrder function I get the following error:

Access to fetch at 'https://api-m.sandbox.paypal.com/create-paypal-order' from origin 'http://localhost:3000' 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.

here is muy code:

  createOrder(data, actions) {

        // Order is created on the server and the order id is returned
        return fetch("https://api-m.sandbox.paypal.com/create-paypal-order", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            // use the "body" param to optionally pass additional order information
            // like product skus and quantities
            body: JSON.stringify({
                orderID: data.orderID
            }),
        })
        .then((response) => response.json())
        .then((order) => order.id);
    }

Any help please ?


Solution

  • return fetch("https://api-m.sandbox.paypal.com/create-paypal-order", {
    

    The fetch needs to be to your own backend server, not the PayPal API. E.g.

    https://your-website-here.com/api/create-paypal-order
    

    Or similar. Assuming it is on the same site (it probably will and should be) you can omit the domain and just give an absolute (leading /) or relative (no leading /) path, same as you would an img or something in HTML

    return fetch("/api/create-paypal-order", {
    or
    return fetch("create-paypal-order", {
    

    This backend server route should in turn communicate with the PayPal API, and return/output only JSON (never any HTML or other debug text) as that's what the public client side code expects to parse as a response.

    Relatedly, API credentials (client secret and the temporary access_token they obtain) should never be used from client-side code. So essentially you must create a backend route and it acts as a proxy for PayPal API requests, though it may additionally do other operations as part of its work (like store successful capture txn IDs in your database along with the rest of an order record)