Артём Юрков
Артём Юрков

Reputation: 121

Paypal SDK, how to change currency dynamically without reinjecting and reinitializing the SDK itself?

My website has products in several currencies up for sale on the same page, so a person can click the product that sold in EUR and pay in euros, or they can click the product that is sold in USD and pay in usd and so on...

The problem is that once you initialise the new PayPal SDK, you cannot change the currency that it accepts without:

  1. destroying the element
  2. changing the link to the SDK, so that it would accept a different currency
  3. manually injecting it into the page
  4. reinitialising it

As you can probably understand it is not very fast, stable or safe at the same time. Am I missing something? I know that you could send the currency as a parameter in the old Express Checkout version.

The PayPal documentation is infuriating, it is missing a lot of information and doesn't have a big community around it, so I could not find the answer to my question anywhere.

I have tried sending the currency in the payment parameters, but if it is different from the initialised currency, it throws a currency mismatch error once you try to confirm the payment.

Right now I am manually reinjecting and reinitialising the paypal SDK with the correct currency if the user clicks on the option of paying with PayPal, but it is slow and requires hardcoding sleep (although it is probably due to my lack of knowledge, there are probably better ways).

Here's the pseudocode of my current setup that is not acceptable:

initialisePaypalSDK(currency) {
    destroy old initialisation
    change link to paypal with new currency
    inject new link to page
    initialise the new sdk
    sleep until the paypal variable is defined
    showPayPalButton()
}

I expect that there is an easier and a safer way of changing the currency than this. Thanks.

Upvotes: 12

Views: 2694

Answers (3)

Alejandro Castillo
Alejandro Castillo

Reputation: 1

You can add the script once the currency has been selected.

let myScript = document.createElement("script");
    myScript.setAttribute(
      "src",
      "https://www.paypal.com/sdk/js?client-id="your cliend id"&components=buttons&currency=" + currencyVariable
    );
    let head = document.head;
    head.insertBefore(myScript, head.firstElementChild);

    myScript.addEventListener("load", scriptLoaded, false);

    function scriptLoaded() {
      console.log("Script is ready to rock and roll!");
      paypal
        .Buttons({
          style: {
            layout: "vertical",
            color: "blue",
            shape: "rect",
            label: "paypal",
          },
          createOrder: function (data, actions) {
            // Set up the transaction
            return actions.order.create({
              purchase_units: [
                {
                  amount: {
                    value: traspasoCantidad,
                  },
                  payee: {
                  },
                  description: "",
                },
              ],
              application_context: {
              },
            });
          },
          onApprove: function (data, actions) {
            return actions.order.capture().then(function (details) {
              /* window.location.href = "approve.html"; */
            });
          },
          onError: function (err) {
            myApp.alert("Ha ocurrido un error al hacer el traspaso", "ERROR");
          },
        })
        .render("#paypal-button-container");
    }

Upvotes: 0

jaynetics
jaynetics

Reputation: 1313

For those using React, this is now possible with the new library @paypal/react-paypal-js. From the README:

The usePayPalScriptReducer hook can be used to reload the JS SDK script when parameters like currency change. It provides the action resetOptions for reloading with new parameters. For example, here's how you can use it to change currency.

// get the state for the sdk script and the dispatch method
const [{ options }, dispatch] = usePayPalScriptReducer();
const [currency, setCurrency] = useState(options.currency);

function onCurrencyChange({ target: { value } }) {
    setCurrency(value);
    dispatch({
        type: "resetOptions",
        value: {
            ...scriptProviderOptions,
            currency: value,
        },
    });
}

return (
    <>
        <select value={currency} onChange={onCurrencyChange}>
            <option value="USD">United States dollar</option>
            <option value="EUR">Euro</option>
        </select>
        <PayPalButtons />
    </>
);

Upvotes: 0

Vitaly Radchik
Vitaly Radchik

Reputation: 125

You can use a backend to solve this issue. First, define createOrder function like this:

const createOrder = async (data, actions) => {
  return await axios.get('/yourbackend/api/get_order_id')
}

const onApprove = (data, actions) => {
// ... code to handle the payment status
}

paypal.Buttons({createOrder, onApprove}).render('#paypal-button-container')

Then just implement REST Api for order creation (/v2/checkout/orders) on your backend. Then return id of the created payment.

Upvotes: 1

Related Questions