Payment Request API 總覽

當顧客嘗試在你的網站上購物時,網站必須要求顧客提供付款資訊,以及其他資訊 (例如運送偏好設定)。您可以使用付款要求 API (PR API) 快速達成這個目標。

基本付款結構

建構 PaymentRequest 物件需要兩個參數:付款方式付款詳細資料。此外,第三個「付款方式」參數為選用參數。您可以按照下列方式建立基本要求:

const request = new PaymentRequest(paymentMethods, paymentDetails);

請參閱每個參數的建構和使用方式。

付款方式

第一個參數 paymentMethods 是陣列變數中支援的付款方式清單。陣列中的每個元素都包含兩個元件:supportedMethods 和 (選用) data

對於 supportedMethods,商家需要指定付款方式 ID,例如 https://bobbucks.dev/paydata 的存在與內容取決於 supportedMethods 的內容和付款應用程式供應商的設計。

這兩項資訊都應由付款應用程式供應商提供。

// Supported payment methods
const paymentMethods = [{
  supportedMethods: 'https://bobbucks.dev/pay',
  data: {
    ... // Optional parameters defined by the payment app provider.
  }
}];

付款詳情

第二個參數 paymentDetails 會以物件形式傳遞,並指定交易的付款詳細資料。其中包含必要值 total,指定顧客應付總金額。這個參數也可以選擇列出購買的項目。

在下列範例中,系統會顯示選購項目清單 (本例中只有一個項目),以及應付總金額 (必填)。在這兩種情況下,每個金額都會指定幣別單位。

const paymentDetails = {
  displayItems: [{
    label: 'Anvil L/S Crew Neck - Grey M x1',
    amount: { currency: 'USD', value: '22.15' }
  }],
  total: {
    label: 'Total due',
    amount: { currency: 'USD', value : '22.15' }
  }
};

確認付款方式是否適用

Chrome 會在建構 PaymentRequest 物件期間,檢查使用者和環境是否已準備好付款。

如要檢查使用者和環境是否已準備好付款,請在叫用付款程序前呼叫 canMakePayment()。如果瀏覽器支援物件中指定的至少一種付款方式,呼叫 canMakePayment() 會傳回 true

request.canMakePayment().then(result => {
  if (result) {
    // This browser supports the specified payment method.
  } else {
    // This browser does NOT support the specified payment method.
  }
}).catch(e => {
  // An exception
});

在 MDN 上進一步瞭解 PaymentRequest.canMakePayment()

show() 方法

設定這兩個參數並建立 request 物件後,即可呼叫 show() 方法,顯示付款應用程式使用者介面。

request.show().then(response => {
  // [process payment]
  // send to a PSP etc.
  response.complete('success');
});

付款應用程式的使用者介面外觀完全由付款應用程式供應商決定。消費者同意付款後,系統會將 JSON 物件傳送給商家,其中包含轉帳所需的所有資訊。商家接著可將這項資訊傳送給 PSP,以處理付款事宜。

最後,視 PSP 傳回的結果而定,您可以使用 response.complete('success')response.complete('fail') 完成程序,關閉付款要求 UI。

下一步

進一步瞭解 Web Payments