Digital Goods API と Payment Request API を使用して Google Play 請求サービス経由で支払いを受け取る

Google Play で配信されているアプリをデジタル商品や特典として販売する場合 Google Play 請求サービスを使用する必要があります。Google Play 請求サービスには、 カタログ、価格、定期購入、便利なレポート、購入手続きフローを Google Play が提供します。 ユーザーが使い慣れているストアをオープンできます。

Trusted Web Activity を使用して作成され、Google Play ストアを通じて配信されるアプリの場合: Payment Request APIDigital Goods API を使用して Google Play 請求サービスAndroid と ChromeOS の Chrome 101 以降で利用できます。

このガイドでは、Google Play 請求サービスのサポートを PWA に追加し、 Google Play ストアで ChromeOS と Play ストアの両方で配布できます。

Play 請求サービスのサポートを PWA に追加するには、2 つのウェブ プラットフォーム API を使用します。「 Digital Goods API を使用して SKU 情報を収集し、購入と利用資格を確認します。 ダウンロードしてください。Payment Request API は、Google Play ストアを 購入フローを完了します。

Google Play ストアでアプリを収益化する方法

Google Play ストアのアプリを Google Play 請求サービスを使用して収益化するには、次の 2 つの方法があります。

  • アプリ内購入では、耐久消費財と消費型仮想アイテムの両方を販売できます。 広告の削除などを行います
  • 定期購入: 定期的に料金を支払うユーザーにコンテンツやサービスへの継続的なアクセス権を提供します。 定期購読や寄付など
で確認できます。

要件

Google Play 請求サービスを設定するには、以下が必要です。

Bubblewrap プロジェクトを更新する

Bubblewrap をまだインストールしていない場合は、インストールする必要があります。詳しくは、 使用方法について詳しくは、クイック スタートガイドをご覧ください。すでにバブルラップがある場合は、 必ずバージョン 1.8.2 以降にアップデートしてください。

バブルラップには旗の後ろの機能もあります。イン 有効にするには、twa-manifest.json でプロジェクト構成を変更する必要があります。 (プロジェクトのルートにあり、alphaDependenciesplayBilling の両方を有効にする) feature:

  ...,
  "enableNotifications": true,
  "features": {
    "playBilling": {
      "enabled": true
    }
  },
  "alphaDependencies": {
    "enabled": true
  },
  ...

構成ファイルを更新したら、bubblewrap update を実行して構成を適用します。 bubblewrap build を指定して、新しい Android パッケージを生成し、 パッケージを Google Play ストアに送信できます。

Digital Goods API と Google Play 請求サービスの対応状況を検出する機能

現在のところ、Digital Goods API が Chrome でサポートされるのは、PWA が 信頼できるウェブ アクティビティです。利用可能かどうかは、 window オブジェクトに対する getDigitalGoodsService:

if ('getDigitalGoodsService' in window) {
 // Digital Goods API is supported!
}

Digital Goods API はどのブラウザでも使用でき、さまざまなストアをサポートしています。目的 特定の店舗のバックエンドがサポートされているかどうかを確認するには、 店舗 ID をパラメータとして渡す getDigitalGoodsService()。Google Play ストアが特定されている 文字列 https://play.google.com/billing に置き換えます。

if ('getDigitalGoodsService' in window) {
  // Digital Goods API is supported!
  try {
    const service =
        await window.getDigitalGoodsService('https://play.google.com/billing');
    // Google Play Billing is supported!

  } catch (error) {
    // Google Play Billing is not available. Use another payment flow.
    return;
  }
}

SKU の詳細を取得する

Digital Goods API が提供する getDetails() を使用すると、 商品のタイトル、説明、そして最も重要なのは価格です。

この情報は、次のようにユーザー インターフェースで使用し、さらに詳しい情報をユーザーに提供できます。

const skuDetails = await service.getDetails(['shiny_sword', 'gem']);
for (item of skuDetails) {
  // Format the price according to the user locale.
  const localizedPrice = new Intl.NumberFormat(
      navigator.language,
      {style: 'currency', currency: item.price.currency}
    ).format(item.price.value);

  // Render the price to the UI.
  renderProductDetails(
        item.itemId, item.title, localizedPrice, item.description);
}

購入フローを構築する

PaymentRequest のコンストラクタは、お支払い方法のリストと、 お支払いの詳細が表示されます。

信頼できるウェブ アクティビティ内では、Google Play 請求サービスのお支払い方法を、 https://play.google.com/billing を ID として設定し、商品の SKU を データメンバー:

async function makePurchase(service, sku) {
   // Define the preferred payment method and item ID
   const paymentMethods = [{
       supportedMethods: "https://play.google.com/billing",
       data: {
           sku: sku,
       }
   }];

   ...
}

支払いの詳細は必須ですが、Play 請求サービスではこれらの値が無視され、 の値を使用して、虚偽の値を入力できます。

const paymentDetails = {
    total: {
        label: `Total`,
        amount: {currency: `USD`, value: `0`}
    }
};

const request = new PaymentRequest(paymentMethods, paymentDetails);

支払いリクエスト オブジェクトで show() を呼び出して、支払いフローを開始します。Promise が成功した場合 支払いが成功した可能性があります。失敗した場合、お客様は支払いを中止した可能性があります。

プロミスが成功したら、購入の確認と承認が必要になります。 不正行為から保護するために、このステップはバックエンドを使用して実装する必要があります。詳しくは、 バックエンドで検証を実装する方法について詳しくは、Play 請求サービスのドキュメントをご覧ください。 購入を承認しない場合、 3 日経過すると、お客様への払い戻しが行われ、Google Play が購入を取り消します

...
const request = new PaymentRequest(paymentMethods, paymentDetails);
try {
    const paymentResponse = await request.show();
    const {purchaseToken} = paymentResponse.details;

    // Call backend to validate and acknowledge the purchase.
    if (await acknowledgePurchaseOnBackend(purchaseToken, sku)) {
        // Optional: tell the PaymentRequest API the validation was
        // successful. The user-agent may show a "payment successful"
        // message to the user.
        const paymentComplete = await paymentResponse.complete('success');
    } else {
        // Optional: tell the PaymentRequest API the validation failed. The
        // user agent may show a message to the user.
        const paymentComplete = await paymentResponse.complete('fail');
    }
} catch(e) {
    // The purchase failed, and we can handle the failure here. AbortError
    // usually means a user cancellation
}
...

必要に応じて、purchaseToken に対して consume() を呼び出して、購入を使い切ったとマークできます。 再度購入できるようにします。

すべてをまとめると、購入方法は以下のようになります。

async function makePurchase(service, sku) {
    // Define the preferred payment method and item ID
    const paymentMethods = [{
        supportedMethods: "https://play.google.com/billing",
        data: {
            sku: sku,
        }
    }];

    // The "total" member of the paymentDetails is required by the Payment
    // Request API, but is not used when using Google Play Billing. We can
    // set it up with bogus details.
    const paymentDetails = {
        total: {
            label: `Total`,
            amount: {currency: `USD`, value: `0`}
        }
    };

    const request = new PaymentRequest(paymentMethods, paymentDetails);
    try {
        const paymentResponse = await request.show();
        const {purchaseToken} = paymentResponse.details;

        // Call backend to validate and acknowledge the purchase.
        if (await acknowledgePurchaseOnBackend(purchaseToken, sku)) {
            // Optional: consume the purchase, allowing the user to purchase
            // the same item again.
            service.consume(purchaseToken);

            // Optional: tell the PaymentRequest API the validation was
            // successful. The user-agent may show a "payment successful"
            // message to the user.
            const paymentComplete =
                    await paymentResponse.complete('success');
        } else {
            // Optional: tell the PaymentRequest API the validation failed.
            // The user agent may show a message to the user.
            const paymentComplete = await paymentResponse.complete('fail');
        }
    } catch(e) {
        // The purchase failed, and we can handle the failure here.
        // AbortError usually means a user cancellation
    }
}

既存の購入のステータスを確認する

Digital Goods API を使用すると、ユーザーに既存の利用資格があるかどうかを確認できます(アプリ内で (まだ利用していない購入や継続中の定期購入など)のうち、以前の購入からの購入 すでに作成されているもの(別のデバイス、以前のインストール、プロモーション コードでの利用など) 最後にアプリを開いたときだけです


const service =
     await window.getDigitalGoodsService('https://play.google.com/billing');
...
const existingPurchases = await service.listPurchases();
for (const p of existingPurchases) {
    // Update the UI with items the user is already entitled to.
    console.log(`Users has entitlement for ${p.itemId}`);
}

また、この段階で、承認されずに行われた購入を確認するのに適しています。 ユーザーが確実に購入できるようにするため、できるだけ早く購入を承認することをおすすめします。利用資格 アプリに適切に反映されているかを確認します

const service =
     await window.getDigitalGoodsService("https://play.google.com/billing");
...
const existingPurchases = await service.listPurchases();
for (const p of existingPurchases) {
    await verifyOrAcknowledgePurchaseOnBackend(p.purchaseToken, p.itemId);

    // Update the UI with items the user is already entitled to.
    console.log(`Users has entitlement for ${p.itemId}`);
}

統合をテストする

開発用 Android デバイスの場合

開発用の Android デバイスで、テストのために Digital Goods API を有効にできます。

  • Android 9 以降でデベロッパー モードが有効になっていることを確認します。
  • Chrome 101 以降をインストールします。
  • Chrome で次のフラグを有効にするには、chrome://flags に移動して「 フラグを名前で指定: <ph type="x-smartling-placeholder">
      </ph>
    • #enable-debug-for-store-billing
  • サイトが HTTPS プロトコルを使用してホストされていることを確認します。http を使用すると、API が undefined になります。
で確認できます。

ChromeOS デバイスの場合

Digital Goods API は、ChromeOS Stable 版バージョン 89 以降でご利用いただけます。 それまでの間、Digital Goods API をテストできます。

  • Google Play ストアからデバイスにアプリをインストールします。
  • サイトが HTTPS プロトコルを使用してホストされていることを確認します。http を使用すると、API が undefined になります。

テストユーザーと QA チーム

Google Play ストアには、ユーザーテスト アカウントやテスト SKU など、テスト用のアフォーダンスが用意されています。 詳しくは、Google Play 請求サービスのテストに関するドキュメントをご覧ください。

次のステップ

このドキュメントで説明するように、Play Billing API には、管理されるクライアントサイドのコンポーネントがあります。 サーバーサイドコンポーネントで テストを行います