Lotfi
Lotfi

Reputation: 320

PayPal Checkout client-side: Can users change the order amount in JavaScript?

I'm using PayPal Checkout to make basic payment the client side, I'm asking if it's safe as I don't want the user to change the amount.

This code is the same as given in the docs.

<script>
  paypal.Buttons({
    createOrder: function(data, actions) {
      // This function sets up the details of the transaction, including the amount and line item details.
      return actions.order.create({
        purchase_units: [{
          amount: {
            value: '100'
          }
        }]
      });
    }
  }).render('#paypal-button-container');
</script>

Upvotes: 6

Views: 1600

Answers (1)

Preston PHX
Preston PHX

Reputation: 30379

Yes, the client-side-only solution can change the order amount. (As of 2024, it is deprecated) To control the amount and validate successful capture, you should use a server-side integration.

Follow the PayPal Checkout integration guide and make 2 routes (URL paths) on your server, one for 'Create Order' and one for 'Capture Order'. You can use the newest PayPal Server SDK (may require login) for the routes' API calls to PayPal, or your own HTTPS implementation of first getting an access_token and then doing the v2/checkout/orders call. Both of your routes should return only JSON data (no HTML or text). Inside the 2nd route, when the capture API is successful you should

  • verify the amount was correct
  • store its resulting payment details in your database (particularly purchase_units[0].payments.captures[0].id, which is the PayPal transaction ID)
  • perform any necessary business logic (such as sending confirmation emails or reserving product)

.. all right before forwarding your return JSON to the frontend caller. In the event of an error forward the JSON details of it as well, since the frontend must handle such cases (restart the checkout if the error is recoverable, or show a failure message if not)

Once you have your 2 server routes available, pair them with this frontend approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server . (If you need to send any additional data from the client to the server, such as an items array or selected options, add a body parameter to the fetch with a value that is a JSON string or object)

Upvotes: 8

Related Questions