Search code examples
paypal-sandboxpaypal

Paypal Express PHP - Posting JS variables in onAuthorize Method


I'm working on a Paypal Express Checkout in PHP and I try to post other variables on the redirect urls once the onAuthorize Method is executed.

I've tried to run an Ajax function once the onAuthorize Method is called but no luck so far. My variables can't get to the URLs set in redirect_urls.

onAuthorize Method:

onAuthorize: function (data, actions) {
  return actions.payment.execute()
    .then(function () {
      postAjax();
      actions.redirect();
    });
}

Ajax Function named postAjax

function postAjax() {
  jQuery.ajax({
    type: "POST",
    ataType: 'text',
    url: "<?php if ($langue == $fr) {echo "http://localhost/index.php/fr/confirmation";} else {echo "http://localhost/index.php/en/confirmation";}?>",
    data: {idFif : "testValue123"},
    success: function(){
      alert(data);
    }
  });
}

URL Redirection

redirect_urls: {
  return_url: '
    <?php if ($langue == $fr) {
       echo "http://localhost/index.php/fr/confirmation"; } 
       else {echo "http://localhost/index.php/en/confirmation";}?>'
    }

I'd love to post the values without having to create an external ajax function (postAjax() in this precise case) but I can't seem to find out how. Can somebody give me some pointers? Thanks a lot!


Solution

  • I strongly recommend for your case that you use the Paypal PHP SDK because the express checkout, yes it's easy, but I had experiences in which the user closes the browser when they had finished to pay on the paypal tab, so the ajax I launched when the payment was executed inside the onAuthorize()'s then() callback sometimes didn't finish to execute, instead, when running the server-side checkout, the paypal window closes once your code has been executed in it's entirety.

    So in your case, there is no other way you can post something to the server once the payment executes, ajax is your only choice. If you were to decide to implement the payment using the PHP SDK, you could do this:

    onAuthorize: function(data, actions) {
                    // Make a request to your server
                    return actions.request.post('urlServerPost', {
                        paymentID: data.paymentID,
                        payerID:   data.payerID,
                        variable1: 'something',
                        variable2: 'something2'
                    })
                    .then(function(res) {
                        //Your payment has already been approved and the process on the server has been finished also
                    });
                }