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: '01234567890123456789',
    merchantName: 'Example Merchant'
  },
  allowedPaymentMethods: [{
    type: 'CARD',
    parameters: {
      allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"],
      allowedCardNetworks: ["AMEX", "DISCOVER", "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/object#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", "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
 *
 * @return {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':'01234567890123456789',
      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/object#Gateway}
        parameters: {
          'gateway': 'example',
          'gatewayMerchantId': 'exampleGatewayMerchantId'
        }
      }
    }]
  };
}

/**
 * Create a PaymentRequest
 *
 * @return {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 string 選擇性
  • PRODUCTION:當指定有效的 Google 商家 ID 時,傳回可扣款的付款方式
  • TEST:傳回的虛擬付款方式,適用於測試作業 (預設)