单击PayPal Express Checkout按钮并带有验证按钮

时间:2018-06-21 14:32:21

标签: javascript paypal express-checkout

我正在对新的PayPal Express Checkout JavaScript按钮进行编码,因此当单击它时,将运行一些验证,并基于该验证来继续或抑制按钮体验。

此演示显示了一些验证,但并不完全是我需要的。 https://developer.paypal.com/demo/checkout/#/pattern/validation

我有这个测试用例,您可以尝试:https://jsfiddle.net/gardavis/51kvtjax-此代码使用PayPal的脚本:https://www.paypalobjects.com/api/checkout.js

这是我正在尝试工作的jsfiddle的一部分...

// Called when page displays
validate: function(actions) {
    console.log("validate called");
    actions.disable(); // Allow for validation in onClick()
    paypalActions = actions; // Save for later enable()/disable() calls
},

// Called for every click on the PayPal button even if actions.disabled
onClick: function() {
    console.log('onClick called');
    // Do validations and if OK, continue on to PayPal popup
    var zip = document.querySelector('#zipcode').value;
    var isValid = zip.length >= 5;
    // Issue: fix to continue if valid, suppress popup if invalid
    if (isValid) {
        document.querySelector('#msg').style.display = 'none';
        paypalActions.enable();
        // TODO: Simulate click of PayPal button to display popup
    } else {
        document.querySelector('#msg').style.display = 'block';
        paypalActions.disable(); // Too late
    }
},

validate()调用一次,基本上是在页面加载时调用。验证还为时尚早。单击按钮时会调用onClick()函数,这是进行验证的好地方,但是如果有效,我将无法继续,如果无效,则无法显示错误。

该演示程序在validate()函数范围内使用一个复选框事件,因此它能够启用/禁用PayPal弹出窗口(如果禁用,onClick()仍然有效)。演示的onClick()仅显示/隐藏错误消息。

有人知道如何在onClick()中进行验证吗?

3 个答案:

答案 0 :(得分:0)

我添加了一个新字段来验证这是客户名称,我添加了一个验证,如果有效,它会显示paypal弹出窗口,您可以复制代码并更新小提琴并进行检查:

<div style="font-family:arial;font-size:14px;">
<p id="msgZip" style="display:none;color:#c00">Please enter a 5-digit zip code</p>
<p><label><input id="zipcode" style="width:50px"> Zip Code</label></p>

<p id="msgName" style="display:none;color:#c00">Please enter your name</p>
<p><label><input id="customername" style="width:50px"> Customer name</label></p>

<div id="paypal-button-container"></div>

<hr/>
<p>
Enter a 5-character zip code and click the checkout button. Validation takes place and since
it is valid, the PayPal experience should display.</p>
<p>A second click on the button does so since the earlier successful validation enabled the button.
</p>
</div>

JavaScript

var paypalActions;
// Render the PayPal button
paypal.Button.render({
  env: 'sandbox', // sandbox | production
  commit: true, // Show Pay Now button

  style: {
    label: 'checkout',
    size: 'medium', // small | medium | large | responsive
    shape: 'rect', // pill | rect
    color: 'gold' // gold | blue | silver | black
  },

  client: {
    sandbox: 'AZDxjDScFpQtjWTOUtWKbyN_bDt4OgqaF4eYXlewfBP4-8aqX3PiV8e1GWU6liB2CUXlkA59kJXE7M6R',
    production: '--not used--'
  },

  // Called when page displays
  validate: function(actions) {
    console.log("validate called");
    actions.disable(); // Allow for validation in onClick()
    paypalActions = actions; // Save for later enable()/disable() calls
  },

  // Called for every click on the PayPal button even if actions.disabled
  onClick: function(e) {
    console.log('onClick called');

    var msgErrors = 0;

    // Do validations and if OK, continue on to PayPal popup
    var zip = document.querySelector('#zipcode').value;
    var isValid = zip.length >= 5;

            // Issue: fix to continue if valid, suppress popup if invalid
    if (isValid) {
      document.querySelector('#msgZip').style.display = 'none';          
      // TODO: Simulate click of PayPal button to display popup
    } else {
      document.querySelector('#msgZip').style.display = 'block'; 
      msgErrors +=1;
    }

     var name = document.querySelector('#customername').value;
    isValid = name.length > 0;
    formValid = isValid;

    if (isValid) {
      document.querySelector('#msgName').style.display = 'none';          
    } else {
      document.querySelector('#msgName').style.display = 'block';
      msgErrors +=1;
    }   

    if (msgErrors == 0) {
      paypalActions.enable();
      // TODO: Simulate click of PayPal button to display popup
    } else {
      paypalActions.disable(); // Too late
    }        

  },

  // Buyer clicked the PayPal button.
  payment: function(data, actions) {
    console.log('payment called');
    return actions.payment.create({
      payment: {
        transactions: [{
          amount: {
            total: '0.01',
            currency: 'USD'
          }
        }]
      }
    });
  },

  // Buyer logged in and authorized the payment
  onAuthorize: function(data, actions) {
    console.log('onAuthorize called');
    return actions.payment.execute().then(function() {
      window.alert('Payment Complete!');
    });
  },

}, '#paypal-button-container');

答案 1 :(得分:0)

剩下的问题是您必须单击两次按钮,因为第一次执行actions.enable();来启用按钮操作。因此,您在第二次单击后就开始了结帐过程。

为解决这个问题,我使用了一个/多个事件监听器,并从那里启用或禁用了操作:

validate: function(actions) {
  actions.disable();
  // i added a 'validate' class value for each element i track
  document.querySelectorAll('.validate').forEach(item => {
    item.addEventListener('change', event => {
      var valid = true; // set it to false if any rule is violated
      /**********************************/
      /* set your validation rules here */
      /**********************************/
      if (valid) {
        actions.enable();
      } else {
        actions.disable();
      }
    });
  });
}

您仍然可以在onClick函数中进行一些CSS样式更改(例如输入字段的红色边框)

答案 2 :(得分:0)

禁用/允许按钮为时已晚,因此您必须在用户进行实际点击之前验证每次输入更改和启用/禁用PayPal按钮的所有内容。