Home > Software engineering >  Updating server-side information from PayPal's JavaScript SDK
Updating server-side information from PayPal's JavaScript SDK

Time:12-16

Is it possible to securely call a PHP script to update server-side info (a database entry or file) if and only if the onApprove callback in PayPal's JavaScript SDK is triggered?

If this is not possible, how would I refactor the web app to update server-side info only when payment is approved?

CodePudding user response:

The JS SDK's actions.order.create() and actions.order.capture() functions are for very simple use cases, not what you're trying to do. You should change to a server-side creation and capture integration instead.

Use the v2/checkout/orders API and make two routes (url paths) on your server, one for 'Create Order' and one for 'Capture Order'. You could use the (recently deprecated) Checkout-PHP-SDK for the routes' API calls to PayPal, or your own HTTPS implementation of first getting an access token and then doing the call. Both of your routes should return/output only JSON data (no HTML or text). Inside the 2nd route, when the capture API is successful you should verify the amount was correct and store its resulting payment details in your database (particularly purchase_units[0].payments.captures[0].id, which is the PayPal transaction ID) and perform any necessary business logic (such as reserving product or sending an email) immediately before forwarding 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.

Pair those 2 routes 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)

  • Related