简体   繁体   English

PayPal Express Checkout JS - 窗口不断加载

[英]PayPal Express Checkout JS - Window Keeps Loading

I am implementing PayPal Express Checkout with a custom online store.我正在使用自定义在线商店实施 PayPal Express Checkout。 These attempts are happening on a live server.这些尝试发生在实时服务器上。

There are no error shown in the Developer Console, the PayPal window that opens just keeps loading with the Lock Symbol.开发人员控制台中没有显示错误,打开的 PayPal 窗口只是不断加载锁定符号。

In all of my research, I have found this answer to be the one that defines the issue: https://stackoverflow.com/a/47446311在我所有的研究中,我发现这个答案是定义问题的答案: https : //stackoverflow.com/a/47446311

In another application that I have integrated with PayPal, I tried removing the "Return" and had the same symptoms as I am having with this application.在我与 PayPal 集成的另一个应用程序中,我尝试删除“返回”并出现与我在此应用程序中遇到的相同症状。 But in this application, I have clearly added the "Return".但是在这个应用程序中,我清楚地添加了“返回”。

Any help is appreciated!任何帮助表示赞赏!

Here is the code Sample:这是代码示例:

paypal.Button.render({
      env: 'sandbox', // 'production' Or 'sandbox',

      commit: true, // Show a 'Pay Now' button

      client: {
      sandbox:    'SANDBOX-ID',
      production: 'PRODUCTION-ID'
    },

      style: {
        color: 'gold',
        size: 'medium'
      },

      payment: function(data, actions) {
        /* 
         * Set up the payment here 
         */
                //Cart Calculation Total...
        var pptotal = document.getElementById('final_price').innerHTML.replace('$','');

        if (window.XMLHttpRequest) {
          // code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
        } else {  // code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function() {
          if (this.readyState==4 && this.status==200) {
            //console.log(this.responseText);
            var r = JSON.parse(this.responseText);
            //Setup variables for payment...
            if(r.response === 'GOOD'){
              pp_payment.payment = {};
              pp_payment.payment.transactions = [];
              var trans_obj = {};
              trans_obj.amount = {};
              trans_obj.amount.total = parseFloat(pptotal).toFixed(2);
              trans_obj.amount.currency = "USD";
              trans_obj.description = "Purchase Details";
              trans_obj.item_list = {};
              var items_array = [];
              var items_obj = {};

              var icount = r.item.length;
              for(var i = 0; i < icount; i++){
                var x = r.item[i];
                items_obj.name = x.pname;
                items_obj.quantity = x.pqty;
                items_obj.price = parseFloat(x.pprice).toFixed(2);
                items_obj.tax = "0.00";
                items_obj.sku = x.pid;
                items_obj.currency = "USD";
                items_array.push(items_obj);
                var items_obj = {};
              }
              trans_obj.item_list.items = items_array;
              pp_payment.payment.transactions.push(trans_obj);



              return actions.payment.create(pp_payment);

            }else{
              console.warn('An Error occurred while calculating the cart');
              alert('An Error occurred while calculating the cart');
            }

          }
        }
        xmlhttp.open("GET","my-cart/php/get-cart-items.php",true);
        xmlhttp.send();

        //End Cart Calculation.

      },

EDIT:编辑:

I have made the switch to the new PayPal Smart Buttons API as suggested, and now it is throwing an error: Uncaught Error: Expected an order id to be passed我已按照建议切换到新的 PayPal 智能按钮 API,现在它抛出一个错误: Uncaught Error: Expected an order id to be passed

When I use this same code snippet (Below) in the PayPal API Tester here: https://developer.paypal.com/demo/checkout/#/pattern/client I dont have any errors at all.当我在此处的 PayPal API 测试器中使用相同的代码片段(如下)时: https : //developer.paypal.com/demo/checkout/#/pattern/client我根本没有任何错误。

Wondering what I am doing wrong?想知道我做错了什么?

// Render the PayPal button into #paypal-button-container
paypal.Buttons({

  // Set up the transaction
  createOrder: function(data, actions) {

    //Cart Calculation...
    var rpptotal = document.getElementById('final_price').innerHTML.replace('$', '');
    var pptotal = parseFloat(rpptotal).toFixed(2);

    if (window.XMLHttpRequest) {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        console.log(this.responseText);
        var r = JSON.parse(this.responseText);
        //Setup variables for payment...
        if (r.response === 'GOOD') {
          pp_payment.purchase_units = [];
          var trans_obj = {};
          //trans_obj.orderID = getRandomNumber(100000,999999);
          trans_obj.amount = {};
          trans_obj.amount.value = pptotal;
          //trans_obj.amount.currency_code = "USD";
          trans_obj.amount.breakdown = {};
          trans_obj.amount.breakdown.item_total = {};
          trans_obj.amount.breakdown.item_total.value = pptotal;
          trans_obj.amount.breakdown.item_total.currency_code = "USD";
          //trans_obj.description = "Purchase Details";
          trans_obj.items = [];
          var items_array = [];
          var items_obj = {};

          var icount = r.item.length;
          for (var i = 0; i < icount; i++) {
            var x = r.item[i];
            items_obj.name = x.pname;
            items_obj.unit_amount = {};
            items_obj.quantity = x.pqty;
            items_obj.unit_amount.value = x.pprice;
            //items_obj.tax = "0";
            items_obj.sku = x.pid;
            items_obj.unit_amount.currency_code = "USD";
            trans_obj.items.push(items_obj);
            var items_obj = {};
          }
          //trans_obj.items = items_array;
          //pp_payment['purchase_units'].push(trans_obj);
          pp_payment.purchase_units.push(trans_obj);
          console.log(pp_payment);
          console.log(JSON.stringify(pp_payment));
          //pp_payment = JSON.stringify(pp_payment);
          //End Payment Variable Setup.

          return actions.order.create(pp_payment);

        } else {
          console.warn('An Error occurred while calculating the cart');
          alert('An Error occurred while calculating the cart');
        }
      }
    }
    xmlhttp.open("GET", "my-cart/php/get-cart-items.php", true);
    xmlhttp.send();
  },

  // Finalize the transaction
  onApprove: function(data, actions) {
    alert('APPROVED');
    return actions.order.capture().then(function(details) {
      // Show a success message to the buyer
      alert('Transaction completed by ' + details.payer.name.given_name + '!');
    });
  }


}).render('#paypal-button');

After much trial and error, I was able to find the cause of my issue.经过多次反复试验,我能够找到问题的原因。

It seems that having an XHR request within the function of createOrder caused a de-synchronization of the returned data from PayPal.似乎在createOrder函数中createOrder XHR 请求createOrder导致从 PayPal 返回的数据不同步。 (Not too sure on the exact reason for this, but it was the issue) (不太确定具体原因,但这就是问题所在)

The XHR Request is necessary in order to build the payment JSON object that is needed to pass to the actions.order.create() function. XHR 请求是构建支付 JSON 对象所必需的,该对象需要传递给actions.order.create()函数。 I just built a simple function that housed the XHR request and added an additional step in the UI (a button "Continue to Checkout") which called this function to build the payment object and open up the rendered PayPal Checkout button.我刚刚构建了一个简单的函数来容纳 XHR 请求,并在 UI 中添加了一个额外的步骤(一个按钮“继续结账”),它调用这个函数来构建支付对象并打开呈现的 PayPal Checkout 按钮。

Once I put the XHR request outside of the createOrder function, all functions properly!一旦我将 XHR 请求放在createOrder函数之外,所有功能都正常!

Here is the updated code:这是更新后的代码:

var pp_payment = {};
var ppitems;

//Random Number Generator...
function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}

function prepare_order(){
  //Cart Calculation...
    var rpptotal = document.getElementById('final_price').innerHTML.replace('$', '');
    var pptotal = parseFloat(rpptotal).toFixed(2);

    pp_payment = {};//Clear the pp_payment variable...

    if (window.XMLHttpRequest) {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        console.log(this.responseText);
        var r = JSON.parse(this.responseText);
        //Setup variables for payment...
        if (r.response === 'GOOD') {
          pp_payment.purchase_units = [];
          var trans_obj = {};
          trans_obj.amount = {};
          trans_obj.amount.value = pptotal;
          trans_obj.amount.breakdown = {};
          trans_obj.amount.breakdown.item_total = {};
          trans_obj.amount.breakdown.item_total.value = pptotal;
          trans_obj.amount.breakdown.item_total.currency_code = "USD";
          trans_obj.items = [];
          var items_array = [];
          var items_obj = {};

          var icount = r.item.length;
          for (var i = 0; i < icount; i++) {
            var x = r.item[i];
            items_obj.name = x.pname;
            items_obj.unit_amount = {};
            items_obj.quantity = x.pqty;
            items_obj.unit_amount.value = x.pprice;
            items_obj.sku = x.pid;
            items_obj.unit_amount.currency_code = "USD";
            trans_obj.items.push(items_obj);
            var items_obj = {};
          }
          pp_payment.purchase_units.push(trans_obj);
          console.log('Order Created...');
          console.log(pp_payment);
          //End Payment Variable Setup.

          document.getElementById('pre-pp-btn').style.display = 'none';
          document.getElementById('paypal-button').style.display = 'inline';

        } else {
          console.warn('An Error occurred while calculating the cart');
          alert('An Error occurred while calculating the cart');
        }
      }
    }
    xmlhttp.open("GET", "my-cart/php/get-cart-items.php", true);
    xmlhttp.send();
}

// Render the PayPal button into #paypal-button-container
paypal.Buttons({

  // Set up the transaction
  createOrder: function(data, actions) {
    return actions.order.create(pp_payment);
  },

  // Finalize the transaction
  onApprove: function(data, actions) {
    alert('APPROVED');
    return actions.order.capture().then(function(details) {
      // Show a success message to the buyer
      alert('Transaction completed by ' + details.payer.name.given_name + '!');
    });
  }


}).render('#paypal-button');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM