1

I'm trying to get a basic Web Payments Request API demo to work. As far as I understand, a pop up should show, asking which credit card I would like to use, when I run this code:

<html>
    <head>
    </head>
    <body>
        <h1>Pay here</h1>
        <script>
            if(window.PaymentRequest){
                alert("Payment request exists!");

                const supportedPaymentMethods = [ {
                        supportedMethods: ["basic-card"]
                    }
                ];

                const paymentDetails = {
                    total: {
                        label: "Total Cost",
                        amount: {
                            currency: "GBP",
                            value: 1
                        }
                    }
                };

                const options = {};

                const paymentRequest =  new PaymentRequest(
                    supportedMethods, paymentDetails, options
                );

                paymentRequest.show();
            }
        </script>
    </body>
</html>

But not much happens. What does happen is that the alert message shows up. I'm just trying to get the basics working. I don't believe this code will send money to anyone because no account is mentioned. I hope to make the next step. Please help! Thanks.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
khalidsafir
  • 165
  • 1
  • 9
  • Payment APIs usually have to be called from the server, not the client, because they need the vendor's private key. – Barmar Dec 23 '17 at 12:52
  • There's a new api produced by Google. All the examples I've seen are html and javascript. All client code, as far as I understand. – khalidsafir Dec 23 '17 at 14:56

1 Answers1

1

I've finally found a working demo. It saves your credit card details in the browser and displays it in an easy to use format (without form fields). It does not send the credit card details to the payment system, it just prepares it:

<button id="buyButton">Buy</button>

<script>
/**
 * Builds PaymentRequest for credit cards, but does not show any UI yet.
 *
 * @return {PaymentRequest} The PaymentRequest oject.
 */
function initPaymentRequest() {
  let networks = ['amex', 'diners', 'discover', 'jcb', 'mastercard', 'unionpay', 'visa', 'mir'];
  let types = ['debit', 'credit', 'prepaid'];
  let supportedInstruments = [{
      supportedMethods: networks,
  }, {
      supportedMethods: ['basic-card'],
      data: {supportedNetworks: networks, supportedTypes: types},
  }];

  let details = {
    total: {label: 'Donation', amount: {currency: 'USD', value: '55.00'}},
    displayItems: [{
      label: 'Original donation amount',
        amount: {currency: 'USD', value: '65.00'},
      },{
        label: 'Friends and family discount',
        amount: {currency: 'USD', value: '-10.00'},
      }
    ]
  };

  return new PaymentRequest(supportedInstruments, details);
}

/**
 * Invokes PaymentRequest for credit cards.
 *
 * @param {PaymentRequest} request The PaymentRequest object.
 */
function onBuyClicked(request) {
  request.show().then(function(instrumentResponse) {
    sendPaymentToServer(instrumentResponse);
  })
  .catch(function(err) {
    ChromeSamples.setStatus(err);
  });
}

/**
 * Simulates processing the payment data on the server.
 *
 * @param {PaymentResponse} instrumentResponse The payment information to
 * process.
 */
function sendPaymentToServer(instrumentResponse) {
  // There's no server-side component of these samples. No transactions are
  // processed and no money exchanged hands. Instantaneous transactions are not
  // realistic. Add a 2 second delay to make it seem more real.
  window.setTimeout(function() {
    instrumentResponse.complete('success')
      .then(function() {
        document.getElementById('result').innerHTML = instrumentToJsonString(instrumentResponse);
      })
      .catch(function(err) {
        ChromeSamples.setStatus(err);
      });
    }, 2000);
  }

  /**
  * Converts the payment instrument into a JSON string.
  *
  * @private
  * @param {PaymentResponse} instrument The instrument to convert.
  * @return {string} The JSON string representation of the instrument.
  */

  function instrumentToJsonString(instrument) {
    let details = instrument.details;
    details.cardNumber = 'XXXX-XXXX-XXXX-' + details.cardNumber.substr(12);
    details.cardSecurityCode = '***';

    return JSON.stringify({
      methodName: instrument.methodName,
      details: details,
    }, undefined, 2);
  }

  const payButton = document.getElementById('buyButton');
  payButton.setAttribute('style', 'display: none;');
  if (window.PaymentRequest) {
    let request = initPaymentRequest();
    payButton.setAttribute('style', 'display: inline;');
    payButton.addEventListener('click', function() {
      onBuyClicked(request);
      request = initPaymentRequest();
    });
  } else {
    ChromeSamples.setStatus('This browser does not support web payments');
  }
</script>

You can copy/paste the code above and save as HTML and load it from your local drive (no need for any fancy stuff like loading it from a secure https URL like I thought).

khalidsafir
  • 165
  • 1
  • 9