LoginSignup
4
3

More than 5 years have passed since last update.

【W3C】Payment Request APIの概要部分【日本語訳】

Last updated at Posted at 2018-09-28

はじめに

以下APIドキュメントのガバガバ翻訳(一部意訳)です。(2018/09/27時点)
https://www.w3.org/TR/payment-request/
※翻訳に疲れた部分は、意味が通じる程度に省略してたりします・・・

サマリ

このAPIは、あくまでブラウザが「配送先住所」「決済手段」を「オートフィルしやすくする」ための規格。
「オートフィル」を実現するには「入力フォーマットを規格化」が必要という流れで、今回のAPIが生まれた。

なので、基本インターフェースのフォーマット定義がほとんど。

なお、この規格は、『ブラウザの挙動を定義する規格1』ではない。あくまで『ブラウザがオートフィルしやすくするための、ECサイト向けの規格』でしかない。
そのため、ブラウザがどのようにデータを保持しているかとか、ブラウザがそれを受け取ってどう処理するかはブラウザによって変わるっぽい。

なんとなくのブラウザ間の違い

  • chrome:ブラウザに保存してたっぽい。(googleアカウントには紐付いてないっぽい。chromeの設定の中から配送先情報とか修正できる。)
  • Edge:Microsoftアカウントに紐づけているっぽい。ログインしないと決済に辿り着けない。
  • samsung:samsung payに紐付いているらしい?触ってないから分からん。
  • ios safari:Apple Payに紐付いている?触ってないから分からん。
  • chrome for android:Android pay に紐付いてるんじゃないかなー?触ってないから分からん。

サンプル実装を見ると、最終的な決済処理は、1行2ってのは凄い。(裏の処理はブラウザ側に実装されている様子)

サンプル実装
function onBuyClicked() {
  if (!window.PaymentRequest) {
    // PaymentRequest API is not available. Forwarding to
    // legacy form based experience.
    location.href = '/checkout';
    return;
  }

  // Supported payment methods
  var supportedInstruments = [{
      supportedMethods: ['basic-card']
      data: {
        supportedNetworks: [
          'visa', 'mastercard', 'amex', 'discover',
          'diners', 'jcb', 'unionpay'
        ]
      }
  }];

  // Checkout details
  var details = {
    displayItems: [{
      label: 'Original donation amount',
      amount: { currency: 'USD', value: '65.00' }
    }, {
      label: 'Friends and family discount',
      amount: { currency: 'USD', value: '-10.00' }
    }],
    total: {
      label: 'Total due',
      amount: { currency: 'USD', value : '55.00' }
    }
  };

  // 1. Create a `PaymentRequest` instance
  // 1. `PaymentRequest` インスタンスを生成する
  var request = new PaymentRequest(supportedInstruments, details);

  // 2. Show the native UI with `.show()`
  // 2. `.show()` を呼び出して、ネイティブ UI を表示する



  request.show()  //←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←← 決済処理がたったこれだけ!



  // 3. Process the payment
  // 3. 決済処理をおこなう
  .then(result => {
    // POST the payment information to the server
    return fetch('/pay', {
      method: 'POST',
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(result.toJSON())
    }).then(response => {
      // 4. Display payment results
      // 4. 決済結果を表示する
      if (response.status === 200) {
        // Payment successful
        return result.complete('success');
      } else {
        // Payment failure
        return result.complete('fail');
      }
    }).catch(() => {
      return result.complete('fail');
    });
  });
}

document.querySelector('#start').addEventListener('click', onBuyClicked);

補足
いきなり仕様を読むよりは、こっちあたりを読んでからのが良いと思う。
このサマリも以下の内容をだいぶ参考にしています。

前説

W3Cドキュメントとしての前提が書かれているだけなので、飛ばしても構わない。
『あくまで、現時点では「勧告候補」という立ち位置でしか無い』という点だけ理解していれば十分。
ということで 本文はこちら

補足:W3C勧告プロセス・・・W3Cの規格を扱うワーキンググループにおける批准プロセス。以下プロセスを踏む。

  1. 「草案(Working Draft)」:実装前検討
  2. 「勧告候補(Candidate Recommendation)」:試行実装
  3. 「勧告案(Proposed Recommendation)」:最終レビュー
  4. 「W3C勧告(Recommendation)」:正式な規格(最終段階)

補足:W3C 仕様の共通部分の日本語訳・・・前説部分の日本語訳。

Abstract

概要

原文This specification standardizes an API to allow merchants (i.e. web sites selling physical or digital goods) to utilize one or more payment methods with minimal integration.
User agents (e.g., browsers) facilitate the payment flow between merchant and user.

これは「簡単なプログラミングで、複数の支払い方法の提供を可能にするAPI」に関する詳細な規格です。
ユーザーエージェント(ブラウザなど)が、支払い手続きを補助します。

Status of This Document

このドキュメントの状態

原文This section describes the status of this document at the time of its publication.
Other documents may supersede this document.
A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at https://www.w3.org/TR/.

本セクションは、公開時のこのドキュメントの状態について説明するものです。
他のドキュメントがこのドキュメントに取って代わるかもしれません。
現在のW3C出版物のリストと、この技術文書の最新バージョンは、 W3C技術文書インデックスで確認できます。

リンク:W3C技術文書インデックス

原文The working group maintains a list of all bug reports that the group has not yet addressed.
Pull requests with proposed specification text for outstanding issues are strongly encouraged.

ワーキンググループは、まだ対処していない全てのバグレポートのリストをメンテナンスします。
未解決課題の詳細テキスト提供は、とてもありがたいです。

リンク:未解決バグレポートリスト

原文NOTE: Sending comments on this document
If you wish to make comments regarding this document, please raise them as GitHub issues.
Only send comments by email if you are unable to raise issues on GitHub (see links below).
All comments are welcome.

注意:このドキュメントへのコメントについて
 このドキュメントにコメントがしたい場合、Githubのissueにあげてください。
 Githubのissueに上げられない場合に限り、emailでコメントしてください。
 どんなコメントでも大歓迎です。

リンク:Github issues

原文The working group will demonstrate implementation experience by producing an implementation report.
The report will show two or more independent implementations passing each mandatory test in the test suite (i.e., each test corresponds to a MUST requirement of the specification).

ワーキンググループは、実装レポートを提供することで、実装体験をデモンストレーションします。
そのレポートは、テストをクリアする、2つ以上の独立した実装を提示しています。

リンク:テスト内容

原文There has been no change in dependencies on other workings groups during the development of this specification.

この仕様の開発を通して、他のワーキンググループに何かしらの変更が加わることはありません。

原文This document was published by the Web Payments Working Group as a Candidate Recommendation.
This document is intended to become a W3C Recommendation.

このドキュメントは、「Web Paymentsワーキンググループ」によって、「勧告候補」として発行されました。
このドキュメントは「W3C勧告」に成ることを目的としています。

リンク:Web Paymentsワーキンググループ
補足:W3C勧告プロセス・・・W3Cの規格を扱うワーキンググループにおける批准プロセス。以下プロセスを踏む。

  1. 「草案(Working Draft)」:実装前検討
  2. 「勧告候補(Candidate Recommendation)」:試行実装
  3. 「勧告案(Proposed Recommendation)」:最終レビュー
  4. 「W3C勧告(Recommendation)」:正式な規格(最終段階)

原文GitHub Issues are preferred for discussion of this specification.

Github Issuesではこの仕様について議論することが望ましいです。

リンク:Github issues

原文W3C publishes a Candidate Recommendation to indicate that the document is believed to be stable and to encourage implementation by the developer community.
This Candidate Recommendation is expected to advance to Proposed Recommendation no earlier than 31 October 2018.

W3Cは、このドキュメントが開発者コミュニティーによって実装することができると知らせるために、「勧告候補」として公表します。
なお、この「勧告候補」が、2018/8/31より前に「勧告案」になることはない想定です。

原文Please see the Working Group's implementation report.

ワーキンググループの実装レポートを見てください。

リンク:実装レポート・・・テストのクリア状況が見れます

原文Publication as a Candidate Recommendation does not imply endorsement by the W3C Membership.
This is a draft document and may be updated, replaced or obsoleted by other documents at any time.
It is inappropriate to cite this document as other than work in progress.

「勧告候補」として発行されたからといって、W3Cメンバーシップによって保証されている訳ではありません。
これはドラフト版ですので、更新されるのが前提ですし、もしかしたらいつか他のドキュメントによって置き換えられるかもしれません。
そのため、最終版のドキュメントとして、このドキュメントを引用するのは不適切です。

原文This document was produced by a group operating under the W3C Patent Policy.
W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent.
An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

このドキュメントは、W3C特許方針の元で作成されました。
W3Cは「public list of any patent disclosures」を保守しています。そのページには特許開示の手引きも含まれます。
特許に関する実際的知識を持ち、そこに Essential Claim(s) が含まれていると主張する者は W3C Patent Policy 第 6 節 に従って情報を開示しなければなりません。

リンク:W3C特許方針-原文
リンク:W3C特許方針-日本語訳
リンク:public list of any patent disclosures
リンク:Essential Claimsの定義
リンク:W3C Patent Policy 第 6 節

原文This document is governed by the 1 February 2018 W3C Process Document.

このドキュメントは W3C Process Document(2018/2/1版) の元で管理されています。
リンク:W3C Process Document

Features at risk

リスクのある機能

原文As this specification enters the Candidate Recommendation phase of the W3C standardization process, the working group has identified the following feature(s) as being "at risk" of being removed from the specification.
The working group seeks input from implementers, developers, and the general public on whether these features should remain in the specification.
If no compelling use cases are received, or if there is limited interest from implementers, these features will be removed from the specification before proceeding along the W3C Recommendation track.

この仕様が「勧告候補」フェーズに入った時、ワーキンググループは、「仕様から除外される可能性のあるいくつかの機能」を定義しました。
ワーキンググループは、それらの機能をこの仕様に残すべきかどうかについて、実装者・開発者・世間からの意見を求めています。

  • 原文PaymentItem's type member and the PaymentItemType enum (see issue 163).
    • PaymentItemのtypeと、PaymentItemType。
    • 詳細はIssue163を見てください。
  • 原文As the optional detailsPromise argument of the show() method was added late in the Candidate Recommendation phase, the working group is treating it "at risk" and considering moving it to a future version of the specification. This is to avoid this version of the specification from being delayed from progressing along the Recommendation Track, in case we can't get two interoperable implementations in a timely manner. However, if it gets interoperably implemented relatively quickly, the feature will remain in this version of the specification.
    • 「show()」のオプション引数である「detailsPromise」が「候補勧告」フェーズの終盤に追加された時、ワーキンググループはこれを「リスクがある機能」とみなし、将来バージョンにおいて取り除くことを考えています。これを取り除くことで、現バージョンが「W3C勧告プロセス」の通過を早くすることが目的です。しかし、比較的早く相互運用可能な実装が実現できるなら、この機能は現バージョンの仕様に残したいとも考えています。
  • 原文Due to PaymentAddress's languageCode attribute only being implemented in one browser (Chrome), the attribute, and all its associated spec text, is at risk.
    • PaymentAddressのlanguageCodeはたった1つのブラウザ(chrome)でしか実装されていないため、「リスクがある機能」とみなしています。

本文

1. Introduction

導入

原文This section is non-normative.

本セクションは、規格の内容を定義するものではなく、参考情報(non-normative)です。

原文This specification describes an API that allows user agents (e.g., browsers) to act as an intermediary between three parties in a transaction:

このAPIは、ユーザーエージェント(ブラウザなど)が、トランザクションの中で、3者間の仲介を担います。

  • 原文the payee: the merchant that runs an online store, or other party that requests to be paid.
    • 被決済者(お店の人):オンラインストアを経営する人。もしくは「支払ってください」と要求する人。
  • 原文the payer: the party that makes a purchase at that online store, and who authenticates and authorizes payment as required.
    • 決済者(お客さん):オンラインストアで購入する人。(要求に応じて決済を認証・認可する。)
  • 原文the payment method provider: the party that provides the means (e.g., credit card) that the payer uses to pay, and that is accepted by the payee.
    • 決済手段提供者(決済プロバイダー):クレジットカードなどの決済手段を提供する人。(被決済者:お店の人に決済手段の提供を許可する人)

原文The details of how to fulfill a payment request for a given payment method is an implementation detail of a payment handler. Concretely, each payment handler defines:

提供された決済手段に対しての決済要求を満たす方法は、payment handlerに細かく定義されています。
具体的にはそれぞれのpayment handlerは以下の通りに定義されています。

  • Steps to check if a payment can be made: ---決済可能かどうか確認するステップ

    原文How a payment handler determines whether it, or the user, can potentially "make a payment" is also an implementation detail of a payment handler. For an example, see the can make payment algorithm of [payment-method-basic-card].

    「ユーザーが"決済"可能かどうか」をpayment handlerがチェックする方法については、payment handlerに定義されています。具体的なアルゴリズムが見たい場合は、「payment-method-basic-card」を参照してください。

  • Steps to respond to a payment request: ---決済要求にレスポンスするステップ

    原文Steps that return an object or dictionary that a merchant uses to process or validate the transaction.
    The structure of this object is specific to each payment method.
    For an example of such an object, see the BasicCardResponse dictionary of [payment-method-basic-card].

    店側が取引を行ったり精査(妥当性確認)したりする時に使う、オブジェクトや連想配列を返却するステップ。
    オブジェクトの構造は、決済手段ごとに異なります。
    具体例については、「payment-method-basic-card」の「BasicCardResponse dictionary」を見てください。

  • Steps for when a user changes payment method (optional) ---決済手段をユーザーが変更する時のステップ(オプション)

    原文Steps that describe how to handle the user changing payment method or monetary instrument (e.g., from a debit card to a credit card) that results in a dictionary or object or null.

    ユーザーが決済手段を変更(デビットカードからクレジットカードに変更する場合など)する処理の仕方を説明するステップ。

原文This API also enables web sites to take advantage of more secure payment schemes (e.g., tokenization and system-level authentication) that are not possible with standard JavaScript libraries.
This has the potential to reduce liability for the merchant and helps protect sensitive user information.

このAPIは、一般的なJavaScriptのライブラリでは実現できないような、よりセキュアな決済スキーム(トークンやシステムレベルの認証など)を、WEBサイトにもたらすことができる。
このAPIによって、店側は、ライブラリを減らしたり、取扱に注意が必要な顧客情報を保護することができる可能性がある。

1.1 Goals

目的

  • 原文Allow the user agent to act as intermediary between merchants, users, and payment method providers.
    • ユーザーエージェント(ブラウザなど)が、店・ユーザー・決済手段提供者の仲介をできるようになること。
  • 原文Enable user agents to streamline the user's payment experience by taking into account user preferences, merchant information, security considerations, and other factors.
    • ユーザーエージェント(ブラウザなど)が、「ユーザーの好み」「お店の情報」「セキュリティ情報」などを考慮に入れた決済体験を提供できるようになること。
  • 原文Standardize (to the extent that it makes sense) the communication flow between a merchant, user agent, and payment method provider.
    • 「お店」「ユーザーエージェント」「決済手段提供者」の間のコミュニケーションフローを規格化すること。
  • 原文Enable payment method providers to bring more secure payment transactions to the web.
    • 決済手段提供者に、よりセキュアなWEB上での決済取引の提供を可能にすること。

1.1.1 Out of scope

スコープ対象外

  • 原文Create a new payment method
    • 新しい決済手段を作ること
  • 原文Integrate directly with payment processors
    • 決済プロセスを直接統合すること(あくまで仲介に留める)

2. Examples of usage

サンプル

原文This section is non-normative.

本セクションは、規格の内容を定義するものではなく、参考情報(non-normative)です。

原文In order to use the API, the developer needs to provide and keep track of a number of key pieces of information.
These bits of information are passed to the PaymentRequest constructor as arguments, and subsequently used to update the payment request being displayed to the user.
Namely, these bits of information are:

API使用するには、開発者は多数の重要な情報を提供し、追跡する必要があります。
これらの情報は、PaymentRequestコンストラクタに引数として渡され、ユーザーに表示された決済リクエストの更新に使われます。
通常、これらの情報は以下である。

  • 原文The methodData: A sequence of PaymentMethodDatas that represents the payment methods that the site supports (e.g., "we support card-based payments, but only Visa and MasterCard credit cards.").
    • methodData: サポートされている決済手段を示すPaymentMethodDataのシーケンス。
  • 原文The details: The details of the transaction, as a PaymentDetailsInit dictionary. This includes total cost, and optionally a list of goods or services being purchased, for physical goods, and shipping options. Additionally, it can optionally include "modifiers" to how payments are made. For example, "if you pay with a credit card of type X, it incurs a US$3.00 processing fee".
    • details: PaymentDetailsInitという連想配列で表現される 取引詳細のこと。
      • トータル金額、購入した商品やサービスの一覧、配送オプションなどが含まれます。
      • 加えて、決済手段に関する「変更」を含めることもできます。
        • 例:「もしXという種別のクレジットカードで支払うなら、追加で300円が必要です。」など
  • 原文The options: Optionally, a list of things as PaymentOptions that the site needs to deliver the good or service (e.g., for physical goods, the merchant will typically need an physical address to ship to. For digital goods, an email will usually suffice).
    • options:オプションとして、PaymentOptionsのリストを用いて、商品やサービスの提供に必要な情報を付与できます。
      • 例1:物理的なグッズを配送する場合、通常、お店側は配送先の住所が必要になります。
      • 例2:デジタルデータなら、メールアドレスが必要です。

訳者注:クレジットカードを使った場合と、使わなかった場合で料金が変わるのは、加盟店規約に違反するんじゃないっけ?

原文Once a PaymentRequest is constructed, it's presented to the end user via the show() method.
The show() returns a promise that, once the user confirms request for payment, results in a PaymentResponse.

PaymentRequestがインスタンス生成されたら、「show()」メソッドによって、エンドユーザーに提供されます。
「show()」メソッドは、ユーザーが決済リクエストを確認した時に、PaymentResponseを必ず返却します。

2.1 The methodData argument

引数:methodData

原文The methodData sequence contains PaymentMethodData dictionaries containing the payment method identifiers for the payment methods that the web site accepts and any associated payment method specific data.

methodDataのシーケンスは、PaymentMethodDataという連想配列を含んでいる。
PaymentMethodDataには、ウェブサイトが許可する決済手段および、各決済手段特有の情報を保有します。
また、PaymentMethodDataには、決済手段を一意に識別する「payment method identifier」というIDが含まれています。

補足:payment method identifier・・・payment-method-idに定義されている用語。決済手段を一意に識別するID。

EXAMPLE_1-The_`methodData`_argument
const methodData = [
  {
    supportedMethods: "basic-card",
    data: {
      supportedNetworks: ["visa", "mastercard"],
      supportedTypes: ["debit", "credit"],
    },
  },
  {
    supportedMethods: "https://example.com/bobpay",
    data: {
      merchantIdentifier: "XXXX",
      bobPaySpecificField: true,
    },
  },
];

2.2 The details argument

引数:details

原文The details contains information about the transaction that the user is being asked to complete, such as the line items in an order.

details は、レシートのような、取引の完了時にユーザーに渡される情報です。

EXAMPLE_2-The_`details`_argument
const details = {
  id: "super-store-order-123-12312",
  displayItems: [
    {
      label: "Sub-total",
      amount: { currency: "USD", value: "55.00" },
    },
    {
      label: "Sales Tax",
      amount: { currency: "USD", value: "5.00" },
      type: "tax"
    },
  ],
  total: {
    label: "Total due",
    // The total is USD$65.00 here because we need to
    // add shipping (below). The selected shipping
    // costs USD$5.00.
    amount: { currency: "USD", value: "65.00" },
  },
};
2.2.1 Shipping options

配送オプション

原文Here we see an example of how to add two shipping options to the details.

detailsに2つの配送オプションを追加する例です。

EXAMPLE_3-Adding_shipping_options
const shippingOptions = [
  {
    id: "standard",
    label: "🚛 Ground Shipping (2 days)",
    amount: { currency: "USD", value: "5.00" },
    selected: true,
  },
  {
    id: "drone",
    label: "🚀 Drone Express (2 hours)",
    amount: { currency: "USD", value: "25.00" }
  },
];
Object.assign(details, { shippingOptions });
2.2.2 Conditional modifications to payment request

決済リクエストに対する条件付き変更

原文Here we see how to add a processing fee for using a credit card.
Notice that it requires recalculating the total.

以下は、クレジットカードを使う場合に、手数料を付与する方法です。
注意して欲しいのは、トータル金額に対して再計算が必要な点です。

EXAMPLE_4-Modifying_payment_request_based_on_card_type
// Credit card incurs a $3.00 processing fee.
const creditCardFee = {
  label: "Credit card processing fee",
  amount: { currency: "USD", value: "3.00" },
};

// Modifiers apply when the user chooses to pay with
// a credit card.
const modifiers = [
  {
    additionalDisplayItems: [creditCardFee],
    supportedMethods: "basic-card",
    total: {
      label: "Total due",
      amount: { currency: "USD", value: "68.00" },
    },
    data: {
      supportedTypes: "credit",
    },
  },
];
Object.assign(details, { modifiers });

2.3 The options argument

引数:options

原文The options dictionary contains information the developer needs from the user to perform the payment (e.g., the payer's name and shipping address).

連想配列である「options」は、ユーザーに決済させるために、開発者が求めている情報を含んでいます。

EXAMPLE_5-The_`options`_argument
const options = {
  requestPayerEmail: false,
  requestPayerName: true,
  requestPayerPhone: false,
  requestShipping: true,
}

2.4 Constructing a PaymentRequest

PaymentRequestのインスタンス生成

原文Having gathered all the prerequisite bits of information, we can now construct a PaymentRequest and request that the browser present it to the user:

予め必要な情報の全てを集めることで、私達はPaymentRequestのインスタンス生成ができ、ブラウザを介して、ユーザーにPaymentRequestを提供することができます。

EXAMPLE_6-Constructing_a_`PaymentRequest`
async function doPaymentRequest() {
  try {
    const request = new PaymentRequest(methodData, details, options);
    // See below for a detailed example of handling these events
    request.onshippingaddresschange = ev => ev.updateWith(details);
    request.onshippingoptionchange = ev => ev.updateWith(details);
    const response = await request.show();
    await validateResponse(response);
  } catch (err) {
    // AbortError, SecurityError
    console.error(err);
  }
}
async function validateResponse(response) {
  try {
    if (await checkAllValuesAreGood(response)) {
      await response.complete("success");
    } else {
      await response.complete("fail");
    }
  } catch (err) {
    // Something went wrong...
    await response.complete("fail");
  }
}
doPaymentRequest();

2.5 Handling events and updating the payment request

イベントの制御・決済リクエストの更新

原文Prior to the user accepting to make payment, the site is given an opportunity to update the payment request in response to user input.
This can include, for example, providing additional shipping options (or modifying their cost), removing items that cannot ship to a particular address, etc.

ユーザーが決済するためには、WEBサイトは決済リクエストを更新する機会を提供しましょう。
例えば、追加の配送オプションの提供、配送対象外地域が配送対象に指定されている商品の除外、などをできるようにしましょう。

EXAMPLE_7-Registering_event_handlers
const request = new PaymentRequest(methodData, details, options);
// Async update to details
request.onshippingaddresschange = ev => {
  ev.updateWith(checkShipping(request));
};
// Sync update to the total
request.onshippingoptionchange = ev => {
  // selected shipping option
  const { shippingOption } = request;
  const newTotal = {
    currency: "USD",
    label: "Total due",
    value: calculateNewTotal(shippingOption),
  };
  ev.updateWith({ total: newTotal });
};
async function checkShipping(request) {
  try {
    const json = request.shippingAddress.toJSON();

    await ensureCanShipTo(json);
    const { shippingOptions, total } = await calculateShipping(json);

    return { shippingOptions, total };
  } catch (err) {
    return { error: `Sorry! we can't ship to your address.` };
  }
}

2.6 Fine-grained error reporting

丁寧なエラーレポート

原文A developer can use the shippingAddressErrors member of the PaymentDetailsUpdate dictionary to indicate that there are validation errors with specific attributes of a PaymentAddress.
The shippingAddressErrors member is a AddressErrors dictionary, whose members specifically demarcate the fields of a physical address that are erroneous while also providing helpful error messages to be displayed to the end user.

開発者は、PaymentAddressにおける特定属性に対しての精査(妥当性確認)エラーを示すために、連想配列「PaymentDetailsUpdate」のshippingAddressErrorsを利用できます。
shippingAddressErrorsは、連想配列「AddressErrors」です。
「AddressErrors」は、誤った住所フィールドを明確にし、同時に、エンドユーザーにエラーメッセージを提供する時に役に立ちます。

EXAMPLE_8
request.onshippingaddresschange = ev => {
  ev.updateWith(validateAddress(request.shippingAddress));
};
function validateAddress(shippingAddress) {
  const error = "Can't ship to this address.";
  const shippingAddressErrors = {
    city: "FarmVille is not a real place.",
    postalCode: "Unknown postal code for your country.",
  };
  // Empty shippingOptions implies that we can't ship
  // to this address.
  const shippingOptions = [];
  return { error, shippingAddressErrors, shippingOptions };
}

2.7 POSTing payment response back to a server

決済レスポンスをサーバーから返却する

原文It's expected that data in a PaymentResponse will be POSTed back to a server for processing.
To make this as easy as possible, PaymentResponse provides a toJSON() method that serializes the object directly into JSON.
This makes it trivial to POST the resulting JSON back to a server using the Fetch API:

PaymentResponseの中にあるデータは、サーバーから返却されることが期待されます。
これの実装は簡単で、PaymentResponseは、オブジェクトを直接JSONに変換する「toJSON()」メソッドを提供しています。

EXAMPLE_9-POSTing_with_`fetch()`
async function doPaymentRequest() {
  const payRequest = new PaymentRequest(methodData, details, options);
  const payResponse = await payRequest.show();
  let result = "";
  try {
    const httpResponse = await fetch("/process-payment", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: payResponse.toJSON(),
    });
    result = httpResponse.ok ? "success" : "fail";
  } catch (err) {
    console.error(err);
    result = "fail";
  }
  await payResponse.complete(result);
}
doPaymentRequest();

3. PaymentRequest interface

訳者注:このセクションは結構省略してます。

WebIDL
[Constructor(sequence<PaymentMethodData> methodData, PaymentDetailsInit details, optional PaymentOptions options),
SecureContext, Exposed=Window]
interface PaymentRequest : EventTarget {
  [NewObject]
  Promise<PaymentResponse> show(optional Promise<PaymentDetailsUpdate> detailsPromise);
  [NewObject]
  Promise<void> abort();
  [NewObject]
  Promise<boolean> canMakePayment();

  readonly attribute DOMString id;
  readonly attribute PaymentAddress? shippingAddress;
  readonly attribute DOMString? shippingOption;
  readonly attribute PaymentShippingType? shippingType;

  attribute EventHandler onshippingaddresschange;
  attribute EventHandler onshippingoptionchange;
  attribute EventHandler onpaymentmethodchange;
};

原文Because the simultaneous display of multiple PaymentRequest user interfaces might confuse the user, this specification limits the user agent to displaying one at a time via the show() method.
This is ensured by a payment request is showing boolean.

複数のPaymentRequestユーザーインターフェースが同時表示された場合、ユーザーは混乱するだろう。
この仕様は、ユーザーエージェントにshow()メソッドで一度に表示する対象を制限するものです。
"payment request is showing"真偽値によって、実現します。

4. PaymentMethodData dictionary

訳者注:このセクションは結構省略してます。

WebIDL
dictionary PaymentMethodData {
  required DOMString supportedMethods;
  object data;
};

原文A PaymentMethodData dictionary is used to indicate a set of supported payment methods and any associated payment method specific data for those methods.

連想配列PaymentMethodDataは、「サポートされている決済手段」と「決済手段に付随するデータ」のセットを指定する時に使われます

5. PaymentCurrencyAmount dictionary

訳者注:このセクションは結構省略してます。

原文A PaymentCurrencyAmount dictionary is used to supply monetary amounts.

連想配列PaymentCurrencyAmountは、合計金額を表示する時に使います。

6. Payment details dictionaries

訳者注:このセクションは結構省略してます。

6.1 PaymentDetailsBase dictionary

WebIDL
dictionary PaymentDetailsBase {
  sequence<PaymentItem> displayItems;
  sequence<PaymentShippingOption> shippingOptions;
  sequence<PaymentDetailsModifier> modifiers;
};

6.2 PaymentDetailsInit dictionary

WebIDL
dictionary PaymentDetailsInit : PaymentDetailsBase {
  DOMString id;
  required PaymentItem total;
};

原文The PaymentDetailsInit dictionary is used in the construction of the payment request.

連想配列PaymentDetailsInitは、決済要求の構築時に使われます。

6.3 PaymentDetailsUpdate dictionary

WebIDL
dictionary PaymentDetailsUpdate : PaymentDetailsBase {
  DOMString error;
  PaymentItem total;
  AddressErrors shippingAddressErrors;
};

原文The PaymentDetailsUpdate dictionary is used to update the payment request using updateWith().

連想配列PaymentDetailsUpdateは、決済要求を更新する時に使います。

7. PaymentDetailsModifier dictionary

訳者注:このセクションは結構省略してます。

原文The PaymentDetailsModifier dictionary provides details that modify the PaymentDetailsBase based on a payment method identifier.
It contains the following members:

連想配列PaymentDetailsModifierは、「payment method identifier」をベースにした「PaymentDetailsBase」を修正する詳細を提供します。

補足:payment method identifier・・・payment-method-idに定義されている用語。決済手段を一意に識別するID。

8. PaymentShippingType enum

訳者注:このセクションは結構省略してます。

WebIDL
enum PaymentShippingType {
  "shipping",
  "delivery",
  "pickup"
};

9. PaymentOptions dictionary

訳者注:このセクションは結構省略してます。

WebIDL
dictionary PaymentOptions {
  boolean requestPayerName = false;
  boolean requestPayerEmail = false;
  boolean requestPayerPhone = false;
  boolean requestShipping = false;
  PaymentShippingType shippingType = "shipping";
};

原文The PaymentOptions dictionary is passed to the PaymentRequest constructor and provides information about the options desired for the payment request.

連想配列PaymentOptionsは、PaymentRequestのコンストラクタで利用します。また、決済要求に対する追加要求についての情報を提供します。

10. PaymentItem dictionary

訳者注:このセクションは結構省略してます。

WebIDL
dictionary PaymentItem {
  required DOMString label;
  required PaymentCurrencyAmount amount;
  boolean pending = false;
  // Note: type member is "at risk" of being removed!
  PaymentItemType type;
};

原文A sequence of one or more PaymentItem dictionaries is included in the PaymentDetailsBase dictionary to indicate what the payment request is for and the value asked for.

1つ以上の連想配列PaymentItemは、連想配列PaymentDetailsBaseを含んでいます。
連想配列PaymentDetailsBaseは、決済要求が何のために有るのか、また価値が何を求めているのかを示します。

11. Physical addresses

訳者注:このセクションは結構省略してます。

11.1 PaymentAddress interface

WebIDL
[SecureContext, Exposed=(Window)]
interface PaymentAddress {
  [Default] object toJSON();
  readonly attribute DOMString city;
  readonly attribute DOMString country;
  readonly attribute DOMString dependentLocality;
  // "languageCode" is a feature at risk
  readonly attribute DOMString languageCode;
  readonly attribute DOMString organization;
  readonly attribute DOMString phone;
  readonly attribute DOMString postalCode;
  readonly attribute DOMString recipient;
  readonly attribute DOMString region;
  readonly attribute DOMString regionCode;
  readonly attribute DOMString sortingCode;
  readonly attribute FrozenArray<DOMString> addressLine;
};

原文The PaymentAddress interface represents a physical address.

インターフェースPaymentAddressは、物理的な住所を示します。

11.2 AddressInit dictionary

WebIDL
dictionary AddressInit {
  DOMString country;
  sequence<DOMString> addressLine;
  DOMString region;
  DOMString regionCode;
  DOMString city;
  DOMString dependentLocality;
  DOMString postalCode;
  DOMString sortingCode;
  DOMString languageCode;
  DOMString organization;
  DOMString recipient;
  DOMString phone;
};

原文A AddressInit is passed when constructing a PaymentAddress. Its members are as follows.

AddressInitはPaymentAddressのインスタンス化に必要です。

11.3 AddressErrors dictionary

WebIDL
dictionary AddressErrors {
  DOMString addressLine;
  DOMString city;
  DOMString country;
  DOMString dependentLocality;
  DOMString languageCode;
  DOMString organization;
  DOMString phone;
  DOMString postalCode;
  DOMString recipient;
  DOMString region;
  DOMString regionCode;
  DOMString sortingCode;
};

原文The members of the AddressErrors dictionary represent validation errors with specific parts of a physical address.
Each dictionary member has a dual function:
firstly, its presence denotes that a particular part of an address is suffering from a validation error.
Secondly, the string value allows the developer to describe the validation error (and possibly how the end user can fix the error).

連想配列AddressErrorsのメンバーは、住所に関する精査エラーを提供します。
いずれのエラーも大きく2つの機能を保持しています。
1つは、エラーの発生したのが住所のどの部分なのか明示すること。
もうひとつが、開発者に対して、エラーの内容を説明することです。

11.4 Creating a PaymentAddress from user-provided input

原文The steps to create a PaymentAddress from user-provided input are given by the following algorithm. The algorithm takes a list redactList, for which user input will not be gathered.

PaymentAddressをユーザー入力情報から作成するためには、以下のようなアルゴリズムが提供するステップが必要です。

※アルゴリズムは省略

12. PaymentShippingOption dictionary

訳者注:このセクションは結構省略してます。

WebIDL
dictionary PaymentShippingOption {
  required DOMString id;
  required DOMString label;
  required PaymentCurrencyAmount amount;
  boolean selected = false;
};

原文The PaymentShippingOption dictionary has members describing a shipping option. Developers can provide the user with one or more shipping options by calling the updateWith() method in response to a change event.

連想配列PaymentShippingOptionは、配送オプションを定義しています。
開発者はユーザーに1つ以上の配送オプションを提供できます。(変更イベントに対するレスポンスの中で、updateWith()メソッドを呼び出すことによって)

13. PaymentComplete enum

訳者注:このセクションは結構省略してます。

WebIDL
enum PaymentComplete {
  "fail",
  "success",
  "unknown"
};

14. PaymentResponse interface

訳者注:このセクションは結構省略してます。

WebIDL
[SecureContext, Exposed=Window]
interface PaymentResponse : EventTarget {
  [Default] object toJSON();

  readonly attribute DOMString requestId;
  readonly attribute DOMString methodName;
  readonly attribute object details;
  readonly attribute PaymentAddress? shippingAddress;
  readonly attribute DOMString? shippingOption;
  readonly attribute DOMString? payerName;
  readonly attribute DOMString? payerEmail;
  readonly attribute DOMString? payerPhone;

  [NewObject]
  Promise<void> complete(optional PaymentComplete result = "unknown");
  [NewObject]
  Promise<void> retry(PaymentValidationErrors errorFields);

  attribute EventHandler onpayerdetailchange;
};

原文A PaymentResponse is returned when a user has selected a payment method and approved a payment request.

PaymentResponseは、決済手段を選択して、決済要求を承認した時に返却されます。

15. PaymentRequest and iframe elements

訳者注:このセクションは結構省略してます。

原文This section is non-normative.

本セクションは、規格の内容を定義するものではなく、参考情報(non-normative)です。

原文To indicate that a cross-origin iframe is allowed to invoke the payment request API, the allowpaymentrequest attribute can be specified on the iframe element.

allowpaymentrequest属性がiframe要素上で宣言することで、クロスオリジンiframeでPaymentRequestAPIを呼び出すことが可能になります。

16. Events

訳者注:このセクションは結構省略してます。

原文This section is non-normative.

本セクションは、規格の内容を定義するものではなく、参考情報(non-normative)です。

Event name Interface Dispatched when… Target
shippingaddresschange PaymentRequestUpdateEvent ユーザーが新しい配送先を登録する時 PaymentRequest
shippingoptionchange PaymentRequestUpdateEvent ユーザーが新しい配送オプションを選択する時 PaymentRequest
payerdetailchange PaymentRequestUpdateEvent The user changes the payer name, the payer email, or the payer phone .ユーザーが、決済者の、名前/メールアドレス/電話番号を変更する時 PaymentResponse
paymentmethodchange PaymentMethodChangeEvent ユーザーが、payment handlerの中で、異なる決済手段を選んだ時 PaymentRequest

17. Algorithms

訳者注:このセクションは結構省略してます。

原文When the internal slot [[state]] of a PaymentRequest object is set to "interactive", the user agent will trigger the following algorithms based on user interaction.

PaymentRequestオブジェクトの内部スロットであるstateに"interactive"がセットされた時、ユーザーエージェントは、ユーザーインタラクションを基準にした以下のアルゴリズムをキックする。

※アルゴリズムは省略。

18. Privacy and Security Considerations

プライバシーとセキュリティに関する考慮事項

原文This section is non-normative.

本セクションは、規格の内容を定義するものではなく、参考情報(non-normative)です。

18.1 User Protections with show() method

show()メソッドにおけるユーザー保護

原文This section is non-normative.

本セクションは、規格の内容を定義するものではなく、参考情報(non-normative)です。

原文To help ensure that users do not inadvertently share sensitive credentials with an origin, this API requires that PaymentRequest's show() method be triggered by user activation (e.g., via a click or press).

ユーザーが誤って機密情報を共有しないようにするため、
このAPIはPaymentRequestのshow()メソッドが、クリックやボタン押下などのユーザーアクションによって実行されることが必要です。

原文To avoid a confusing user experience, this specification limits the user agent to displaying one at a time via the show() method.
In addition, the user agent can limit the rate at which a page can call show().

ユーザーの混乱を避けるために、この仕様は、ユーザーエージェントに、show()メソッドを用いて一度に表示する範囲を制限します。
加えて、ユーザーエージェントは、show()メソッドによってページが呼ばれる割合を制限できます。

18.2 Secure contexts

「Secure contexts」

補足:Secure contexts・・・セキュアな情報のやり取りに関する規格

原文This section is non-normative.

本セクションは、規格の内容を定義するものではなく、参考情報(non-normative)です。

原文The API defined in this specification is only exposed in secure contexts.
In practice, this means that this API is only available over HTTPS.
This is to limit the possibly of payment method data (e.g., credit card numbers) being sent in the clear.

この仕様で定義されたAPIは、「Secure contexts」でのみ公開されます。(このAPIはHTTPSでしか使えないという意味でもあります。)
これは、決済手段データ(クレジットカード番号など)が丸見えな状態で送信される可能性を制限するために存在します。

18.3 Cross-origin payment requests

クロスオリジン決済要求

原文This section is non-normative.

本セクションは、規格の内容を定義するものではなく、参考情報(non-normative)です。

原文It is common for merchants and other payees to delegate checkout and other e-commerce activities to payment service providers through an iframe.
This API supports payee-authorized cross-origin iframes through [HTML]'s allowpaymentrequest attribute.

お店や決済者にとって、精算やそれにまつわるEC周りの処理を、iframeを通して決済サービスプロバイダーに委託することは、一般的です。
このAPIは、HTMLのallowpaymentrequest属性を通して、決済者として認証されたクロスオリジンiframeをサポートします。

原文Payment handlers have access to both the origin that hosts the iframe and the origin of the iframe content (where the PaymentRequest initiates).

Payment handlerは、iframeをホストする生成したオリジンと、iframeコンテンツになっているオリジンの、両方にアクセスします。

18.4 Encryption of data fields

暗号化

原文This section is non-normative.

本セクションは、規格の内容を定義するものではなく、参考情報(non-normative)です。

原文he PaymentRequest API does not directly support encryption of data fields.
Individual payment methods may choose to include support for encrypted data but it is not mandatory that all payment methods support this.

PaymentRequestAPIは、データの暗号化を直接はサポートしません。
私的な決済手段は、暗号化されたデータのサポートを含むことを期待するでしょう。
しかし、「全ての決済手段がこれをサポートすること」を強制することはできません。

18.5 How user agents match payment handlers

payment handlersとユーザーエージェントをどうマッチさせるか

原文This section is non-normative.

本セクションは、規格の内容を定義するものではなく、参考情報(non-normative)です。

原文As part of show(), the user agent typically displays a list of matching payment handlers that satisfy the payment methods accepted by the merchant and other conditions.
Matching can take into account payment method information provided as input to the API, information provided by the payment method owner, the payment handlers registered by the user, user preferences, and other considerations.

show()メソッドにおいて、
ユーザーエージェントは、お店側などによって許可された決済手段を満たすpayment handlerのリストを表示する。
マッチングは、以下の情報を考慮にいれることができます。
「APIへのインプットとして提供される決済手段情報」「決済手段提供元によって提供される情報」「ユーザーによって登録されたpayment handler」「ユーザー設定」など

原文For security reasons, a user agent can limit matching (in show() and canMakePayment()) to payment handlers from the same origin as a URL payment method identifier.

セキュリティが理由で、URL(payment method identifier)という同じオリジンから、payment handlerへのマッチングを、ユーザーエージェントは制限します。

補足:payment method identifier・・・payment-method-idに定義されている用語。決済手段を一意に識別するID。

19. Privacy Considerations

プライバシーに関する考慮

19.1 Exposing user information

ユーザー情報の公開

原文The user agent MUST NOT share information about the user with a developer (e.g., the shipping address) without user consent.

ユーザーエージェントは、ユーザーの同意無しに、ユーザーに関する情報を開発者に共有しては絶対にいけません。

原文One way that the API supports limited information sharing is through the "redactList" associated with the creation of physical addresses throughout the API.
This feature enables user agents to provide the payee with enough information to compute shipping costs or tax information, while limiting the payee's ability to identify the payer via the address.

APIが制限された情報のシェアをサポートする方法は、APIを通して、住所の作成に紐付けられた"redactList"を通すことです。
この機能は、配送料や税を計算するために、決済者に十分な情報を、ユーザーエージェントが提供することを可能にする。
(お店側が「住所から決済者を特定」できないようにしている間に)

原文The user agent MUST NOT share the values of the displayItems member or additionalDisplayItems member with a third-party payment handler without user consent.

ユーザーエージェントは、ユーザーの許可なしに、第三者のpayment handlerにdisplayItemsもしくはadditionalDisplayItemsの値を、絶対にシェアしてはいけない。

19.2 canMakePayment() protections

「canMakePayment()」による保護

原文The canMakePayment() method enables the payee to call show() if the user is ready to take advantage of the API, or to fall back to a legacy checkout experience if not.
Because this method shares some information with the payee, user agents are expected to protect the user from abuse of the method, for example, by restricting the number or frequency of calls.

canMakePayment()メソッドは、「ユーザーがAPIの利点を得る準備ができた時に決済者がshow()メソッドを呼び出すこと」を可能にする。
もし、「ユーザーがAPIの利点を得る準備ができていないなら」、レガシーな決済体験に戻すしか無い。
このメソッドは、被決済者といくつかの情報をシェアするため、ユーザーエージェントは、メソッドの乱用からユーザーを守ることが期待される。
例えば、メソッド呼び出しの頻度もしくは回数を制限することになどによって。

20. Dependencies

依存技術

原文This section is non-normative.

本セクションは、規格の内容を定義するものではなく、参考情報(non-normative)です。

訳者注:詳細は原文見てください。ここでは列挙するにとどめます。

  • DOM
  • ECMAScript
  • HTML
  • Infra
  • ISO 3366-2
  • Payment Method Identifiers
  • Web IDL
  • Writing Promise-Using Specifications

21. Conformance

守るべきこと

訳者注:共通部分のため割愛。
以下の「適合性の要件」参照。

補足:W3C 仕様の共通部分の日本語訳・・・前説部分の日本語訳。

以上


  1. 「ブラウザが安全に情報を保持するためのルール」とか「ブラウザが受け取ったデータをどう処理するか」とか 

  2. request.show() だけやでぇ・・・(細かいとこすっ飛ばせば) 

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3