javascriptphppaypalpaypal-rest-sdkpaypal-buttons

Paypal Smart Payment Buttons — how to create order server-side and pass order ID to Paypal Buttons setup?


I'm integrating Paypal Checkout and following in their documentation for how to set up the client SDK here.

I would like to not set up the order items and sum on the client side, but instead use the server side setup for orders mentioned at the end of step 4. Using their PHP SDK I can manage to setup the order no problem, but where I am struggling to get things to work is how to pass this created order to the client. The return object for the created order has the ID and URLs to initiate capture it, but following the links actually provides a different UX from clicking the Paypal Button, so I would like to use the Button still, but with the created order.

Using their example code:

  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: '0.01'
          }
        }]
      });
    },
    onApprove: function(data, actions) {
      // This function captures the funds from the transaction.
      return actions.order.capture().then(function(details) {
        // This function shows a transaction success message to your buyer.
        alert('Transaction completed by ' + details.payer.name.given_name);
      });
    }
  }).render('#paypal-button-container');
  //This function displays Smart Payment Buttons on your web page.

Essentially I have an order ID from my server side call and would not need to use the "createOrder" call, but how can I pass my order ID to the paypal.Buttons() setup so that when the user clicks on the rendered Paypal Button they are sent to approve the order I created?

P.S.: I get that you verify and capture the order after, but why would anybody ever want to set up the order charge in their client side Javascript? To me that just seems like a fundamentally wrong idea. Am I missing something here?


Solution

  • The solution was fairly obvious, but somehow I didn't stumble upon it when looking earlier. createOrder needs to return the order ID, this can be done as documented:

    method: 'post',
        headers: {
          'content-type': 'application/json'
        }
      }).then(function(res) {
        return res.json();
      }).then(function(data) {
        return data.orderID; // Use the same key name for order ID on the client and server
      });