Google Pay API PaymentRequest 教程

Google Pay API 可与 PaymentRequest 中支持的其他付款方式结合使用。

第 1 步:创建 PaymentDataRequest 对象

配置 PaymentDataRequest 对象,以指定您的支付网关和可接受的付款方式。我们建议您通过浏览器的 PaymentRequest options 参数(而非 Google Pay API)获取送货地址、电子邮件地址和电话号码,这样无论选择何种付款方式,都能提供一致的体验。使用 Google Pay API 仅接收付款凭据和可选的帐单邮寄地址。

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'
      }
    }
  }]
};

第 2 步:声明 Google Pay API 支持

将 Google Pay API 付款方式标识符及其配置添加到传递给 PaymentRequestmethodData 参数中。

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

总结

以下示例展示了 Google Pay API 如何实现与 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()
  }];
  // Add other supported payment methods.
  methodData.push({
    supportedMethods: 'basic-card',
    data: {
      supportedNetworks:
          Array.from(allowedCardNetworks, (network) => network.toLowerCase())
    }
  });

  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>

付款方式参数列表

PaymentRequest 中传递的 Google Pay API 配置类似于 Google Pay API JavaScript 客户端库使用的 PaymentDataRequest 对象,但有一些例外:

  • PaymentOptions 中说明的字符串值匹配的对象应该设置 environment 属性
  • transactionInfo 属性应该省略。相反,应在传递给 PaymentRequestdetails 参数中指定总价和币种

PaymentRequest 付款方式数据属性中为 Google Pay API 付款方式指定的其他对象属性如下:

属性 类型 必要性 说明
environment 字符串 可选
  • PRODUCTION:当为网域指定和配置了有效的 Google 商家 ID 时,返回可用付款方式。
  • TEST:返回的虚拟付款方式,适用于测试(默认)