Search code examples
javascriptandroidandroid-pay

Android Pay Mobile Web on Nexus unexpected error


I've started trying to get android pay working on one of our sites. I've set up a basic set up script to create a vanilla payment on a test site.

Everything seems to be going fine until the user clicks the element which triggers Android Pay. When the user clicks there's a "slide up" from the OS but it dies before anything is displayed and I get an error stating:

"Request Failed

An unexpected error has occured. Please try again later."

There's nothing in the console or the debugger to give any kind of indication what the nature of the error is.

Here is the JS:

<script>

    if (window.PaymentRequest) {

        var request = createPaymentRequest();

      request.canMakePayment()
          .then(function (result) {
            if (result) {
              addPayWithGoogleButton();
            }
          })
          .catch(function (err) {
            showErrorForDebugging(
                'canMakePayment() error! ' + err.name + ' error: ' + err.message);
          });
    } else {
      showErrorForDebugging('PaymentRequest API not available.');
    }

    /**
     * Add a purchase button alongside the existing checkout option
     */
    function addPayWithGoogleButton() {
      var payWithGoogleButton = document.createElement('button');
      payWithGoogleButton.appendChild(document.createTextNode('Purchase'));
      payWithGoogleButton.addEventListener('click', onPayWithGoogleClicked);
      document.getElementById('checkout').appendChild(payWithGoogleButton);
    }

    /**
     * Show purchase chooser when buy button clicked
     */
    function onPayWithGoogleClicked() {
      createPaymentRequest()
          .show()
          .then(function(response) {
            // Dismiss payment dialog
            response.complete('success');
            handlePaymentResponse(response);
          })
          .catch(function(err) {
            showErrorForDebugging('show() error! ' + err.name + ' error: ' + err.message);
          });
    }

    /**
     * Configure support for the Google Payments API
     *
     * @returns {object} data attribute suitable for PaymentMethodData
     */
    function getGooglePaymentsConfiguration() {
      return {
        // Merchant ID available after approval by Google.
        // 'merchantId':'01234567890123456789',
        'environment': 'TEST',
        'apiVersion': 1,
        'allowedPaymentMethods': ['CARD', 'TOKENIZED_CARD'],
        'paymentMethodTokenizationParameters': {
          'tokenizationType': 'PAYMENT_GATEWAY',
          // Check with your payment gateway on the parameters to pass.
          'parameters': {}
        },
        'cardRequirements': {
          'allowedCardNetworks': ['AMEX', 'DISCOVER', 'MASTERCARD', 'VISA'],
          'billingAddressRequired': true,
          'billingAddressFormat': 'MIN'
        },
        'phoneNumberRequired': true,
        'emailRequired': true,
        'shippingAddressRequired': true
      };
    }

    /**
     * Create a PaymentRequest
     *
     * @returns {PaymentRequest}
     */
    function createPaymentRequest() {
      // Support Google Payment API.
      var methodData = [{
        'supportedMethods': ['https://google.com/pay'],
        'data': getGooglePaymentsConfiguration()
      }];

      var details = {
        total: {label: 'Test Purchase', amount: {currency: 'USD', value: '1.00'}}
      };

      return new PaymentRequest(methodData, details);
    }

    /**
     * Process a PaymentResponse
     *
     * @param {PaymentResponse} response returned when user approves the purchase request
     */
    function handlePaymentResponse(response) {
      var formattedResponse = document.createElement('pre');
      formattedResponse.appendChild(
          document.createTextNode(JSON.stringify(response.toJSON(), null, 2)));
      document.getElementById('checkout')
          .insertAdjacentElement('afterend', formattedResponse);
    }

    /**
     * Display an error message
     *
     * @param {string} text message to display
     */
    function showErrorForDebugging(text) {
      var errorDisplay = document.createElement('code');
      errorDisplay.style.color = 'red';
      errorDisplay.appendChild(document.createTextNode(text));
      var p = document.createElement('p');
      p.appendChild(errorDisplay);
      document.getElementById('checkout').insertAdjacentElement('afterend', p);
    }
</script>

Solution

  • For anyone else who runs into this - the tutorial code appears to have been at fault. We fixed it by changing the code from this:

    function createPaymentRequest() {
      // Support Google Payment API.
      var methodData = [{
        'supportedMethods': ['https://google.com/pay'],
        'data': getGooglePaymentsConfiguration()
      }];
    
      var details = {
        total: {label: 'Test Purchase', amount: {currency: 'USD', value: '1.00'}}
      };
    
      return new PaymentRequest(methodData, details);
    }
    

    to this:

    function createPaymentRequest() {
          // Support Google Payment API.
          var methodData = [{
            'supportedMethods': 'basic-card',
            'data': getGooglePaymentsConfiguration()
          }];
    
          var details = {
            total: {label: 'Test Purchase', amount: {currency: 'USD', value: '1.00'}}
          };
    
          return new PaymentRequest(methodData, details);
        }