Tutorial de PaymentRequest de la API de Google Pay

La API Google Pay se puede usar junto con otros métodos de pago admitidos en PaymentRequest.

Paso 1: Crea un objeto PaymentDataRequest

Configura un objeto PaymentDataRequest que especifique tu pasarela de pago y los métodos de pago aceptados. Te recomendamos que obtengas la dirección de envío, la dirección de correo y el número de teléfono a través del argumento PaymentRequest options del navegador, y no de la API de Google Pay, para que los métodos de pago sean coherentes. Usa la API Google Pay para recibir solo las credenciales de pago y la dirección de facturación opcional.

const googlePaymentDataRequest = {
  environment: 'TEST',
  apiVersion: 2,
  apiVersionMinor: 0,
  merchantInfo: {
    // A merchant ID is available after approval by Google.
    // @see {@link https://developers.google.com/pay/api/web/guides/test-and-deploy/integration-checklist}
    // merchantId: '12345678901234567890',
    merchantName: 'Example Merchant'
  },
  allowedPaymentMethods: [{
    type: 'CARD',
    parameters: {
      allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"],
      allowedCardNetworks: ["AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA"]
    },
    tokenizationSpecification: {
      type: 'PAYMENT_GATEWAY',
      // Check with your payment gateway on the parameters to pass.
      // @see {@link https://developers.google.com/pay/api/web/reference/request-objects#gateway}
      parameters: {
        'gateway': 'example',
        'gatewayMerchantId': 'exampleGatewayMerchantId'
      }
    }
  }]
};

Paso 2: Declara la compatibilidad con la API de Google Pay

Añade el identificador del método de pago de la API Google Pay y su configuración al parámetro methodData que se pasa a PaymentRequest.

const methodData = [
  {supportedMethods: 'https://google.com/pay', data: googlePaymentDataRequest}
];

Combinando todos los elementos

En el siguiente ejemplo se muestra una implementación de la API Google Pay con otros métodos de pago admitidos en PaymentRequest:

<div id="checkout">
  <button id="buyButton">Checkout</button>
</div>

<script>
const allowedCardNetworks = ["AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA"];
const allowedCardAuthMethods = ["PAN_ONLY", "CRYPTOGRAM_3DS"];
if (window.PaymentRequest) {
  const request = createPaymentRequest();

  request.canMakePayment()
      .then(function(result) {
        if (result) {
          // Display PaymentRequest dialog on interaction with the existing checkout button
          document.getElementById('buyButton')
              .addEventListener('click', onBuyClicked);
        }
      })
      .catch(function(err) {
        showErrorForDebugging(
            'canMakePayment() error! ' + err.name + ' error: ' + err.message);
      });
} else {
  showErrorForDebugging('PaymentRequest API not available.');
}

/**
 * Show a PaymentRequest dialog after a user clicks the checkout button
 */
function onBuyClicked() {
  createPaymentRequest()
      .show()
      .then(function(response) {
        // Dismiss payment dialog.
        response.complete('success');
        handlePaymentResponse(response);
      })
      .catch(function(err) {
        showErrorForDebugging(
            'show() error! ' + err.name + ' error: ' + err.message);
      });
}

/**
 * Define your unique Google Pay API configuration
 *
 * @returns {object} data attribute suitable for PaymentMethodData
 */
function getGooglePaymentsConfiguration() {
  return {
    environment: 'TEST',
    apiVersion: 2,
    apiVersionMinor: 0,
    merchantInfo: {
      // A merchant ID is available after approval by Google.
      // 'merchantId':'12345678901234567890',
      merchantName: 'Example Merchant'
    },
    allowedPaymentMethods: [{
      type: 'CARD',
      parameters: {
        allowedAuthMethods: allowedCardAuthMethods,
        allowedCardNetworks: allowedCardNetworks
      },
      tokenizationSpecification: {
        type: 'PAYMENT_GATEWAY',
        // Check with your payment gateway on the parameters to pass.
        // @see {@link https://developers.google.com/pay/api/web/reference/request-objects#gateway}
        parameters: {
          'gateway': 'example',
          'gatewayMerchantId': 'exampleGatewayMerchantId'
        }
      }
    }]
  };
}

/**
 * Create a PaymentRequest
 *
 * @returns {PaymentRequest}
 */
function createPaymentRequest() {
  // Add support for the Google Pay API.
  const methodData = [{
    supportedMethods: 'https://google.com/pay',
    data: getGooglePaymentsConfiguration()
  }];

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

  const options = {
    requestPayerEmail: true,
    requestPayerName: true
  };

  return new PaymentRequest(methodData, details, options);
}

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

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

Lista de parámetros de método de pago

La configuración de la API de Google Pay que se pasa en PaymentRequest es similar al objeto PaymentDataRequest que usa la biblioteca de cliente de JavaScript de la API de Google Pay, con algunas excepciones:

  • Se debe definir una propiedad environment en el objeto que coincida con un valor de cadena descrito en PaymentOptions.
  • La propiedad transactionInfo debe omitirse. El precio total y la moneda deben especificarse en el argumento details que se pasa a PaymentRequest.

Propiedades de objeto adicionales especificadas para el método de pago de la API Google Pay en una propiedad de datos del método de pago PaymentRequest:

Propiedad Tipo Necesidad Descripción
environment string opcional
  • PRODUCTION: devuelve los métodos de pago con cargo cuando se especifica un ID de comerciante de Google válido y se configura para el dominio.
  • TEST: se devuelven métodos de pago ficticios adecuados para pruebas (predeterminado)