Payment Request API 的運作方式

概略瞭解 Payment Request API 的運作方式。

Payment Request API

客戶嘗試在您的網站上購買商品時,網站必須請客戶提供付款資訊,以及運送偏好設定等其他資訊。您可以使用 Payment Request 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' }
  }
};

確認付款方式是否可用

叫用付款程序前,商家可以檢查使用者和環境是否已準備好付款。

呼叫 canMakePayment() 會檢查瀏覽器是否支援物件中指定的付款方式 (至少一種)。

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 來關閉付款要求 UI。

下一步

進一步瞭解網路付款