Search code examples
javascriptdjangopaypalpaypal-sandbox

Get response from PayPal buttton in django


I have integrated PayPal buttons into my project. I am sharing my code here for PayPal Buttons.

<script src="https://www.paypal.com/sdk/js?client-id=MyClientID&currency=USD" data-sdk-integration-source="button-factory"></script>

<script>
function initPayPalButton() {
    paypal
      .Buttons({
        style: {
          shape: "rect",
          color: "blue",
          layout: "horizontal",
          label: "buynow",
        },

        createOrder: function (data, actions) {
          return actions.order.create({
            purchase_units: [{amount: {currency_code: "USD", value: totalAmount}}],
          });
        },

        onApprove: function (data, actions) {
          return actions.order.capture().then(function (orderData) {
            // Full available details
            console.log("Capture result", orderData, JSON.stringify(orderData, null, 2));

            // Show a success message within this page, e.g.
            const element = document.getElementById("paypal-button-container");
            element.innerHTML = "";
            element.innerHTML = "<h3>Thank you for your payment!</h3>";

            // Or go to another URL:  actions.redirect('thank_you.html');
          });
        },

        onError: function (err) {
          console.log(err);
        },
      })
      .render("#paypal-button-container");
  }
  initPayPalButton();
</script>
<div class="paypalButton-mainDiv">
  <div id="smart-button-container">
    <div style="text-align: center">
      <div id="paypal-button-container"></div>
    </div>
  </div>
</div>

But I am not able to get the response back from this code after Payment. I need to get the response and want to store it in my database.


Solution

  • It seems that no data persistence happens when you have a successful payment.

    You can use onApprove to get the response after payment and then send it to your server using an AJAX call or a form submit. That would look something like this:

        onApprove: function (data, actions) {
          return actions.order.capture().then(function (orderData) {
            // [anything before]
    
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/<your-server-endpoint>');
            // optional: set header
            // xhr.setRequestHeader(/*<headers you need>*/);
            xhr.onload = function() {
              if (xhr.status === 200) {
                console.log('Response received: ' + xhr.responseText);
              }
            };
            xhr.send(JSON.stringify(orderData));
    
            // [anything after, e.g. element.innerHTML = <html> OR go to another URL ]
    
          });
        },
    

    Even more ideally, you can use a form, rather than AJAX; in that case, you need to create a hidden <input> element that stores the response and then submit the form using JavaScript.

    The exact specifications of these are up to you, and are doable as per the standard JS documentation.