PaymentResponse: shippingAddress 屬性

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

安全上下文: 此功能僅在安全上下文(HTTPS)中可用,且支援此功能的瀏覽器數量有限。

PaymentRequest 介面的只讀屬性 shippingAddress 返回一個 PaymentAddress 物件,其中包含使用者提供的送貨地址。

一個 PaymentAddress 物件,提供包含使用者提供的送貨地址的詳細資訊。

示例

通常,使用者代理會為您填充 shippingAddress 屬性。您可以透過在呼叫 PaymentRequest 建構函式時將 options.requestShipping 設定為 true 來觸發此操作。

在下面的示例中,運費因地區而異。當觸發並捕獲 shippingaddresschange 事件時,會呼叫 updateDetails() 來更新 PaymentRequest 的詳細資訊,使用 shippingAddress 來設定正確的運費。

js
// Initialization of PaymentRequest arguments are excerpted for brevity.

const payment = new PaymentRequest(supportedInstruments, details, options);

request.addEventListener("shippingaddresschange", (evt) => {
  evt.updateWith(
    new Promise((resolve) => {
      updateDetails(details, request.shippingAddress, resolve);
    }),
  );
});

payment
  .show()
  .then((paymentResponse) => {
    // Processing of paymentResponse excerpted for the same of brevity.
  })
  .catch((err) => {
    console.error("Uh oh, something bad happened", err.message);
  });

function updateDetails(details, shippingAddress, resolve) {
  if (shippingAddress.country === "US") {
    const shippingOption = {
      id: "",
      label: "",
      amount: { currency: "USD", value: "0.00" },
      selected: true,
    };
    if (shippingAddress.region === "MO") {
      shippingOption.id = "mo";
      shippingOption.label = "Free shipping in Missouri";
      details.total.amount.value = "55.00";
    } else {
      shippingOption.id = "us";
      shippingOption.label = "Standard shipping in US";
      shippingOption.amount.value = "5.00";
      details.total.amount.value = "60.00";
    }
    details.displayItems.splice(2, 1, shippingOption);
    details.shippingOptions = [shippingOption];
  } else {
    delete details.shippingOptions;
  }
  resolve(details);
}

規範

規範
Payment Request API
# shippingaddress-attribute

瀏覽器相容性