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", "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 付款方式 ID 及其設定,新增至傳送給 PaymentRequestmethodData 參數。

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

總整理

下列範例顯示 PaymentRequest 中 Google Pay API 與其他支援付款方式搭配使用的實作:

    <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':'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/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:傳回的虛擬付款方式,適用於測試作業 (預設)