2013年5月29日水曜日

Google Play In-app Billingを訳してみる「In-app Billing Reference (IAB Version 3)」


In-app Billing レファレンス(IABバージョン3)

この文書はIn-app Billingバージョン3APIを使うための技術的レファレンス情報を提供するものである。

サーバーレスポンスコード

後述のテーブルはすべてのサーバーレスポンスコードを列記している。このレスポンスコードはGoogle Playからあなたのアプリへ送られるものである。Google Playはレスポンスコードを同期的に送る。レスポンスバンドル内でRESPONSE_CODEキーへマッピングされた整数値として。

レスポンスコード 値 詳細
BILLING_RESPONSE_RESULT_OK 0 成功
BILLING_RESPONSE_RESULT_USER_CANCELED 1 ユーザーが戻るボタンを押したかキャンセルダイアログを押した
BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE 3 Billing APIバージョンがこのタイプのリクエストをサポートしていない
BILLING_RESPONSE_RESULT_ITEM_unAVAILABLE 4 リクエストされた商品が決済で使えない
BILLING_RESPONSE_RESULT_DEVELOPER_ERROR 5 APIに不当な引数が与えられた。このエラーはアプリが正しく署名されていない、Google Play内のIn-app Billingに対して適切に設定されていない、マニュフェストに必要なパーミッションがないことも示している。
BILLING_RESPONSE_RESULT_ERROR 6 API挙動内での致命的エラー
BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED 7 アイテムが既に所持されていることによる決済エラー
BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED 8 アイテムが所持されていないことによる消費エラー


APIレファレンス

In-app Billingバージョン3APIはIInAppBillingService.aidlファイル内で定義されている。このファイルはバージョン3のサンプルアプリを含んでいる。

getSkuDetails()メソッド

このメソッドはプロダクトID一覧に対する商品詳細を返す。Google Playによって送られるレスポンスバンドル内で、クエリ結果はDETAILS_LISTキーにマッピングされたArrayList文字列内で保存される。詳細一覧内の各々の文字列はJSON形式の単体商品に対する商品詳細を含んでいる。商品詳細に伴うJSON文字列内のフィールドはtable2でまとめられている。

Table2。商品アイテム詳細に伴うJSONフィールドの詳細はgetSkudetailsリクエストから返される
キー 詳細
productId:商品に対するプロダクトID
type:値はin-app商品に対する"inapp"か定期購入に対する"subs"でなければならない
price:通貨単位を含む商品の定型化された価格。この価格は税を含まない
title:商品タイトル
description:商品の詳細


getBuyIntent()メソッド

このメソッドはRESPONSE_CODEキーでマッピングされたレスポンスコードの整数値を返す。またBUY_INTENTキーでマッピングされたin-appアイテムに対する決済フローを開始するためのPendingIntentを返す。PendingIntentを受け取ったとき、Google Playは決済注文に対するデータと共にレスポンスIntentを送る。レスポンスIntent内で返されたこのデータはtable 3でまとめられている。

Table 3.In-app Billinバージョン3決済リクエストからのレスポンスデータ

キー 詳細
RESPONSE_CODE もし決済が成功した場合は0、エラーはそれ以外
INAPP_PURCHASE_DATA JSON形式の文字列。JSONには決済注文に関する詳細を含んでいる。JSONフィールドの詳細に関してはtable4を参照。
INAPP_DATA_SIGNATURE 決済シグネチャーを含む文字列。この決済データはデベロッパーのプライベートキーで署名されている。データ署名はRSASSA-PKCS1-v1_5スキームを用いている

Table4は決済注文に対するレスポンスデータ内で返されるJSONフィールドについて述べている

Table4 INAPP_PURCHASE_DATAに対するJSONフィールドの詳細

フィールド 詳細
orderId:トランザクションに対するユニークなオーダー識別子。これはグーグルウォレットのOrderIDと一致する
packageName:決済が由来するアプリのパッケージ
productId:アイテム商品識別子。すべてのアイテムは商品IDを持っている。このIDはGoogle Playデベロッパーコンソール上でアプリ商品一覧内で定義しなければならない
purchaseTime:商品が決済された時間エポック(1970/1/1)からのミリセコンドで表記。
purchaseState:注文の決済状態。取りうる値は0(purchased),1(canceled),2(refunded)
developerPayload:デベロッパーが定義した文字列。この文字列は注文に関する追加情報を含んでいる。あなたはgetBuyIntentリクエストを生成した際にこのフィールドに対する値を規定することができる。
purchaseToken:付与されたアイテムとユーザーのペアに対する決済を一意に識別するトークン


getPurchases()メソッド

このメソッドはユーザーが所持している現在未消費の商品を返す。Table 5はバンドル内で返されたレスポンスデータを列挙している。

Table 5 getPurchaseリクエストからのレスポンスデータ

キー 詳細
RESPONSE_CODE:リクエストが成功なら0、エラーならそれ以外
INAPP_PURCHASE_ITEM_LIST:このアプリからの決済の商品ID一覧を含むStringArrayList
INAPP_PURCHASE_DATA_LIST:このアプリからの決済詳細を含むStringArrayList。一覧の各々のINAPP_PURCHASE_DATAアイテム内で保存された詳細情報の一覧を参照。
INAPP_DATA_SIGNATURE_LIST:このアプリの決済シグネチャーを含むStringArrayList
INAPP_CONTINUATION_TOKEN:ユーザーが所持しているin-app商品の次のセットを取り出すための連続トークンを含む文字列。ユーザーが所持している商品数がとても多い場合にこれはGoogle Playサービスによってのみセットされる。レスポンス内に連続トークンが存在する場合、あなたはgetPurchasesに対して別のコールを生成しなければならない。そしてあなたが取り出した連続トークンを通さなければならない。次のgetPurchasesコールはより多くの決済を返し、さらなる連続トークンを返すこともありうる。



In-app Billing Reference (IAB Version 3)

This documentation provides technical reference information for using the In-app Billing Version 3 API.

Server Response Codes


The following table lists all of the server response codes that are sent from Google Play to your application. Google Play sends the response code synchronously as an integer mapped to the RESPONSE_CODE key in the response Bundle. Your application must handle all of these response codes.
Table 1. Summary of response codes for In-app Billing Version 3 API calls.
Response Code Value Description
BILLING_RESPONSE_RESULT_OK 0 Success
BILLING_RESPONSE_RESULT_USER_CANCELED 1 User pressed back or canceled a dialog
BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE 3 Billing API version is not supported for the type requested
BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE 4 Requested product is not available for purchase
BILLING_RESPONSE_RESULT_DEVELOPER_ERROR 5 Invalid arguments provided to the API. This error can also indicate that the application was not correctly signed or properly set up for In-app Billing in Google Play, or does not have the necessary permissions in its manifest
BILLING_RESPONSE_RESULT_ERROR 6 Fatal error during the API action
BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED 7 Failure to purchase since item is already owned
BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED 8 Failure to consume since item is not owned

API Reference


The In-app Billing Version 3 API is defined in the IInAppBillingService.aidl file, which is included with the Version 3 sample application.

The getSkuDetails() method

This method returns product details for a list of product IDs. In the response Bundle sent by Google Play, the query results are stored in a String ArrayList mapped to the DETAILS_LIST key. Each String in the details list contains product details for a single product in JSON format. The fields in the JSON string with the product details are summarized in table 2.
Table 2. Description of JSON fields with product item details returned from a getSkuDetails request.
Key Description
productId The product ID for the product.
type Value must be “inapp” for an in-app product or "subs" for subscriptions.
price Formatted price of the item, including its currency sign. The price does not include tax.
title Title of the product.
description Description of the product.

The getBuyIntent() method

This method returns a response code integer mapped to the RESPONSE_CODE key, and a PendingIntent to launch the puchase flow for the in-app item mapped to the BUY_INTENT key. When it receives the PendingIntent, Google Play sends a response Intent with the data for that purchase order. The data that is returned in the response Intent is summarized in table 3.
Table 3. Response data from an In-app Billing Version 3 purchase request.
Key Description
RESPONSE_CODE 0 if the purchase was success, error otherwise.
INAPP_PURCHASE_DATA A String in JSON format that contains details about the purchase order. See table 4 for a description of the JSON fields.
INAPP_DATA_SIGNATURE String containing the signature of the purchase data that was signed with the private key of the developer. The data signature uses the RSASSA-PKCS1-v1_5 scheme.

Table 4 describes the JSON fields that are returned in the response data for a purchase order.
Table 4. Descriptions of the JSON fields for INAPP_PURCHASE_DATA.
Field Description
orderId A unique order identifier for the transaction. This corresponds to the Google Wallet Order ID.
packageName The application package from which the purchase originated.
productId The item's product identifier. Every item has a product ID, which you must specify in the application's product list on the Google Play Developer Console.
purchaseTime The time the product was purchased, in milliseconds since the epoch (Jan 1, 1970).
purchaseState The purchase state of the order. Possible values are 0 (purchased), 1 (canceled), or 2 (refunded).
developerPayload A developer-specified string that contains supplemental information about an order. You can specify a value for this field when you make a getBuyIntent request.
purchaseToken A token that uniquely identifies a purchase for a given item and user pair.

The getPurchases() method

This method returns the current un-consumed products owned by the user. Table 5 lists the response data that is returned in the Bundle.
Table 5. Response data from a getPurchases request.
Key Description
RESPONSE_CODE 0 if the request was successful, error otherwise.
INAPP_PURCHASE_ITEM_LIST StringArrayList containing the list of productIds of purchases from this app.
INAPP_PURCHASE_DATA_LIST StringArrayList containing the details for purchases from this app. See table 4 for the list of detail information stored in each INAPP_PURCHASE_DATA item in the list.
INAPP_DATA_SIGNATURE_LIST StringArrayList containing the signatures of purchases from this app.
INAPP_CONTINUATION_TOKEN String containing a continuation token to retrieve the next set of in-app products owned by the user. This is only set by the Google Play service if the number of products owned by the user is very large. When a continuation token is present in the response, you must make another call to getPurchases and pass in the continuation token that you received. The subsequent getPurchases call returns more purchases and possibly another continuation token.

Google Play In-app Billingを訳してみる「Implementing the API(Version 3 API)」

In-app Billingの実装(IABバージョン3)

Google PlayのIn-app Billingはわかりやすくシンプルなインターフェースを提供する。このインターフェースはIn-app Billingリクエストを起こったり、Google Playを使うIn-app Billingトランザクションを管理するのに使用される。下記の情報はどのようにしてあなたのアプリケーションからバージョン3APIを使ってin-app Billingサービスを呼び出すかに関する基本をカバーしている。

ノート:完璧な実装を見たり、どのようにあなたのアプリのテストするかを学んだりする場合はSelling In-app Productsトレーニングクラスを参照。このトレーニングクラスはIn-app Billing アプリケーションの完全なサンプルを提供している。サンプルには接続を行うのに関するキーとなるタスクを管理するクラスや、決済リクエストを送るクラス、Google Playからのレスポンスを管理するクラス、メイン操作からin-app Billingコールを生成できるよう、バックグラウンドのスレッドを管理するクラスなど、便利なクラスを含んでいる。

始める前に、必ずIn-app Billing Overviewを読んでおくこと。それをすることであなたはIn-app Billingを実装することを容易にするためのコンセプトに馴染みやすくすることができる。

In-app Billingをあなたのアプリに実装するために、あなたは以下のことをする必要がある。

1.あなたのプロジェクトにIn-app Billingライブラリを追加する
2.AndroidManifest.xmlファイルをアップデートする
3.ServiceConnectionを作り、IInAppBillingServiceをそこにバインドする
4.あなたのアプリからIInAppBillingServiceにIn-app Billingリクエストを送る
5.Google PlayからIn-app Billingレスポンスを管理する


AIDLファイルをあなたのプロジェクトに追加する

IInAppBillingService.aidlはアンドロイドインターフェース定義言語(AIDL)ファイルである。これはIn-app Billingバージョン3にインターフェースを定義するものである。あなたはIPCメソッドコールを呼び出すことによって決済リクエストを作るためのインターフェースを使うことができる。

AIDLファイルを取得するためには

1.Android SDK Managerを開く
2.SDKマネージャーでExtrasセクションを広げる
3.Google Play Billing Libraryを選択する
4.Install packagesをクリックし、ダウンロードを完了させる

これでIInAppBillingService.aidlファイルは<sdk>/extras/google/play_billing/にインストールされる。

AIDLをあなたのプロジェクトに追加するには

1.IInAppBillingService.aidlファイルをあなたのアンドロイドプロジェクトにコピーする
・あなたがEclipseを使っている場合は
a.あなたが既存のAndroidプロジェクトから始める場合は、プロジェクトをEclipseで開き。もしあなたが新しいAndroidプロジェクトを初めから作る場合は、File > New > Android Application Projectをクリックする。その後あなたのワークスペースに新しいプロジェクトを作るためのNew Android Applicationウィザードの指示に従う
b./srcディレクトリ内で、File > New > Packageをクリックする。そうするとcom.android.vending.billingという名前のパッケージが作られる。
c.<sdk>/extras/google/play_billing/からIInAppBillingService.aidlファイルをコピーし、あなたのワークスペース内のsrc/com.android.vending.billing/ フォルダに貼り付ける
・あなたが非Eclipse環境で開発をしている場合、/src/com/android/vending/billingディレクトリを作って、そこにIInAppBillingService.aidlをコピーする。AIDLファイルをあなたのプロジェクト内に置き、IInAppBillingService.javaファイルが作られるようにAntツールを使ってあなたのプロジェクトをビルドする
2.あなたのアプリケーションをビルドする。あなたはプロジェクトの/genディレクトリ内にIInAppBillingService.javaと名前の着いたファイルが生成されていることを確認する


あなたのアプリケーションManifestを更新する

In-app billingはGoogle Playアプリケーションに依存している。それはつまりあなたのアプリケーションとGoogle Playサーバー間のすべてのコミュニケーションはGoogle Playアプリケーションが管理している。Google Playアプリケーションを使うために、あなたのアプリケーションは適切なパーミッションをリクエストしなければならない。このリクエストはあなたのAndroidManifest.xmlファイルにcom.android.vending.BILLINGパーミッションを付加することで行うことができる。もしあなたのアプリがIn-app Billingパーミッションを宣言していないにもかかわらず決済リクエストを贈ろうとした場合、Google Playはそのリクエストを拒絶し、エラーのレスポンスを返す。

あなたのアプリに必要なパーミッションを与えるには、Android.xmlマニフェストファイルに以下の行を加える。
<uses-permission android:name="com.android.vending.BILLING" />


サービスコネクションを作る

あなたのアプリはアプリとGoogle Play間でメッセージのやり取りをするためのServiceConnectionを持たなくてはならない。最低限、あなたのアプリは下記のことを行わなければならない。

・IInAppBillingServiceをバインドする
・GooglePlayアプリに(IPCメソッドコールとしての)決済リクエストを送る
・各々の決済リクエストとともに返される同期レスポンスメッセージを管理する


IInAppBillingServiceをバインドする

Google Play上のIn-app Billingサービスと接続を確立するために、あなたのアクティビティとIInAppBillingServiceをつなぐServiceConnectionを実装する必要がある。接続が確立されたあとにIInAppBillingServiceインスタンスへのリファレンスを得るためのonServiceDisconnectedメソッドとonServiceConnectedメソッドをオーバーライドすること。

あなたのアクティビティのonCreateメソッドにおいて、bindServiceメソッドを呼ぶことでバインドを行う。メソッドにあなたが作成したServiceConnectionのインスタンスとIn-app Billingサービスを参照しているIntentを通す。

あなたはこれでGoogle Playサービスとコミュニケーションを取るmService参照を使うことができる。

重要:あなたがアクティビティを完了させたとき、In-app Billingサービスからバインドを外すことを覚えておくこと。もしバインドを外すことをしないと、オープンサービス接続があなたのデバイスのパフォーマンスを落とすことになる。この例は、アクティビティのonDestroyメソッドをオーバーライドすることによって、mServiceConnと呼ばれているIn-app Billingと接続しているサービス接続上でどうやってバインドを外すのかを示している。

IInAppBillingServiceにバインドするサービス接続の完全な実装に関しては、Selling In-app Productsトレーニングクラスと関連サンプルを参照。


In-app Billingリクエストを生成する

一度あなたのアプリをGoogle Playに接続させると、in-app商品に対する決済リクエストを初期化することができる。Google Playはユーザーが決済メソッドに入るための精算インターフェースを提供している。だから、あなたのアプリは決済トランザクションを直接操作する必要はない。アイテムが決済されたとき、Google Playはユーザーがアイテムの所有権を持つことを認識し、またそのアイテムが消費されるまで、同じプロダクトIDの他の商品を決済できないようにする。あなたはアプリ内でどうやってアイテムが消費されるかを管理することができ、またGoogle Playに再びそのアイテムの決済が可能であることを通知することができる。あなたはGoogle Playにユーザーによって行われた決済一覧を迅速に取り出す問い合わせをすることもできる。これは例えばユーザーがあなたのアプリを立ち上げた際にユーザー決済を復帰させたいときに便利だ。


決済に関する利用可能アイテムの問い合わせをする

あなたのアプリ内で、In-app Billingバージョン3APIを使うことでGoogle Playから商品詳細と問い合わせることができる。リクエストをIn-app Billingサービスに通すには、まず"ITEM_ID_LIST"キーとプロダクトIDの文字列配列を含むバンドルを作る。このリストの各々の文字列は決済可能アイテムに対するプロダクトIDである。

Google Playから情報を取り出すためにはgetSkuDetailsメソッドをIn-app Billingバージョン3PAI上で呼び、そのメソッドをIn-app BillingAPIバージョン3、あなたのコールしているアプリのパッケージネーム、決済タイプinapp、そしてあなたが作ったバンドルに通せばよい。

もしリクエストが成功した場合、返り値としてのバンドルはBILLING_RESPONSE_RESULT_OKのレスポンスコードを持っている。

警告:メインスレッドでgetSkuDetailsを呼んではいけない。このメソッドを呼ぶことはあなたのメインスレッドをブロックするネットワークリクエストのトリガーになる。その代わりとして、分離されたスレッドを生成し、そのスレッドの中からgetSkuDetailsメソッドを呼ぶ。

Google Playからすべての可能なレスポンスコードを見たい場合はIn-app Billing Referenceを参照。

問い合わせ結果はDETAILS_LISTキーとともに文字列配列の形で保存される。決済情報はJSON形式の文字列で保存される。帰ってくる商品詳細情報のタイプを見たい場合は、In-app Billing Referenceを参照。

この例では、あなたは前のコードの一部から返されるsku詳細バンドルからin-appアイテムに対する価格を取り出している。


アイテムの決済

あなたのアプリから決済リクエストを始めるためには、In-app Billingサービス上のgetBuyIntentメソッドを呼び出す。メソッドの中にIn-app Billing APIバージョン3、あなたの呼び出しアプリのパッケージネーム、決済アイテムのプロダクトID、決済タイプ(inappまたはsubs)、developerPayload文字列を通す。developerPayload文字列はGoogle Playに決済情報と一緒に返り値として送信してほしい追加の引数を規定したい場合に使われる。

リクエストが成功した場合、返り値としてのバンドルはBILLING_RESPONSE_RESULT_OK(0)のレスポンスコードと、決済フローを始めるために使用できるPendingIntentを持っている。Google Playから戻されうるレスポンスコードをすべて見たい場合は、In-app Billing Referenceを参照。次にBUY_INTENTキーと一緒にレスポンスバンドルからPendingIntentを抽出する。

PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");

決済トランザクションを完了させるためには、startIntentSenderForResultメソッドを呼び、生成したPendingIntentを使う。この例は、リクエストコードに対する1001の任意の値を使用している。

Google PlayはあなたのアプリのonActivityResultメソッドに対するPendingIntentに対するレスポンスを送る。onActivityResultメソッドはActivity.RESULT_OK(1)またはActivity.RESULT_CANCELED(0)の結果コードを持っている。Intentレスポンスで返される注文情報のタイプを見たい場合はIn-app Billing レファレンスを参照。

注文の決済データはIntentレスポンスの中でINAPP_PURCHASE_DATAキーにマッピングされたJSONフォーマットの文字列になっている。例が下記。

前の例から続ける場合は、あなたはレスポンスコード、決済データ、シグネチャーをIntentレスポンスから受け取る。

セキュリティ推奨:あなたが決済リクエストを送る際にはdeveloperPayloadの中でこのトークンを含み、また決済リクエストを一意に定義する文字列トークンを作る必要がある。あなたはトークンとして文字列をランダムに生成された文字列を使うことができる。Google Playからの決済レスポンスを受け取る際に、戻り値としてのデータシグネチャー、orderId、developerPayload文字列をチェックすること。さらにセキュリティを向上させるにはあなたはこのチェックをセキュアなサーバーで行うべきである。orderIdはあなたが前に処理していないユニークな値であること、そしてdeveloperPayload文字列は前に決済リクエストとともに送ったトークンとマッチすることを確かめる必要がある。


決済アイテムの問い合わせ

あなたのアプリからユーザーによってなされた決済情報を取り出すには、In-app Billingバージョン3サービスでgetPurchasesメソッドを呼び出せばよい。メソッドをIn-app Billing APIバージョン3、呼び出し元アプリのパッケージネーム、決済タイプ(inappまたはsubs)を通す。

Bundle ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);

Google Playサービスは現在デバイスにログが書き込まれているユーザーアカウントによって作られた決済のみを返す。リクエストが成功している場合、戻り値としてのバンドルは0のレスポンスコードを持っている。レスポンスバンドルはプロダクトIDの一覧、各々の決済の注文詳細の一覧、各々の決済のシグネチャーを含んでいる。

パフォーマンスを改善するために、getPurchaseが初めて呼ばれた際、in-app Billingサービスはユーザーが所持している700商品を上限に返す。ユーザーが大量の商品を所持している場合、Google Playは文字列トークンを含んでいる。その文字列トークンはINAPP_CONTINUATION_TOKENをキーにしてマッピングされている。そのキーはレスポンスバンドルの中にある。レスポンスバンドルは多くの商品が取り出せることを示すためのものである。あなたのアプリは次のgetPurchasesコールを作ることができるそして、このトークンの中で引数として通している。Google Playはレスポンスバンドルの中で継続的なトークンを返し続ける。それはユーザーが所持しているすべての商品があなたのアプリに送られるまでだ。

getPurchasesによって返されるより多くの情報を知りたい場合はin-app Billing Referenceを参照。次の例はどのようにあなたがレスポンスからこのデータを取り出すかを示している。


決済の消費

あなたはIn-app Billingバージョン3APIを使うことができる。Google Playでのin-app商品の決済オーナーを追うために。一度in-app商品が決済されると、それはownedとみなされ、Google Playから決済されることができない。あなたはin-app商品に関する消費リクエストを送らなければならない。Google Playがそれを再び決済可能にする前に。

重要:マネージドin-app商品は消費可能である。だが定期購入は消費可能ではない。

どのようにあなたがアプリ内で消費メカニズムを使うかはあなた次第である。基本的にはあなたあhin-app商品のために一時的な便益とともに消費を実装する。一時的な便益とはユーザーが複数回決済したいかもしれないものである(例えばゲーム内通貨や装備など)。あなたは基本的にin-app商品のために消費の実装をしたくないだろう。in-app商品は一度だけ決済ができ、恒久的な効果をもたらす(例えばプレミアムアップグレード)。

決済消費を記録するために、consumePurchaseメソッドをIn-app Billingサービスに送ること。また、決済が削除されたことを一意に示すpurchaseToken文字列の中に通すこと。purchaseTokenは決済の成功リクエストを追うためのGoogle PlayサービスによってINAPP_PURCHASE_DATA文字列の中に返されたデータの一部である。この例では、あなたは商品の消費を記録している。この商品はtoken変数の中でpurchaseTokenに一意に特定されている。

int response = mService.consumePurchase(3, getPackageName(), token);

警告:consumePurchaseメソッドをメインスレッド内で呼んではいけない。あなたのメインスレッドをブロックするネットワークリクエストのトリガーとなるメソッドを呼んでしまうからだ。その代わりにあなたは独立したスレッドを作り、その中でconsumePurchaseメソッドを呼ぶこと。

どのようにin-app商品をユーザーにプロビジョニングするを管理し、追跡することはあなたの責任である。例えば、もしユーザーがゲーム内通貨を決済する場合、あなたは決済された通貨量とともにプレイヤーの商品一覧を更新するべきである。

セキュリティ推奨:あなたは消費リクエストを送らなければならない。ユーザーに対して消費可能なin-app決済の便益をプロビジョニングする前に。あなたがアイテムをプロビジョニングする前に、Google Playから消費性向レスポンスを受け取っていることを必ず確認すること。


定期購入の実装

定期購入に対する決済フローを開始することはsubsにセットされなければならない商品タイプの例外とともに、商品に対する決済フローを開始するのと似ている。決済結果はあなたのアクティビティのonActivityResultメソッドによって運ばれる。in-app商品のケースと全く同様である。

アクティブな定期購入問い合わせをするためにはgetPurchasesメソッドを使い、再度subsでセットされた商品タイプパラメーターとともに使う。

このコールはユーザーが所持しているアクティブなすべての定期購入とともにバンドルを返す。一度定期購入が更新なしで期限切れになると、返されたバンドルの中にもはやそれは現れない。


あなたのアプリをセキュアにする

アプリへ送られたトランザクション情報の整合性を保証するのを助けるために、Google Playは決済注文に対するレスポンスデータを含むJSON文字列に署名をしている。Google Playはプライベートキーを使っている。そのプライベートキーは署名を作るためにデベロッパーコンソール内であなたのアプリケーションとひもづけられている。デベロッパーコンソールは各々のアプリに対してRSAキーペアを生成する。

ノート:このキーペアの公開鍵部分おw見つけるためにはデベロッパーコンソール内でアプリケーション詳細を開き、Service & APIsをクリックする。そしてYour License Key for This Applicationと書かれたフィールドを見る。

Base64でエンコードされたGoogle Playによってい生成されたRSA公開鍵はバイナリーエンコードされたX.509 subjectPublicKeyInfo DER SEQUENCE形式だ。Google Playライセンスで使われているものと同じ公開鍵だ。

あなたのアプリが署名済みのレスポンスを受けたとき、あなたは署名を照合したRSAキーペアの公開鍵部分を使用することができる。署名照合を行うことで、あなたはレスポンスがいたずらによるものなのか、調整されたものなのかを見破ることができる。あなたはアプリ内に署名照合段階を実行することができる。しかし、もしあなたのアプリがセキュアなリモートサーバーに接続している場合、我々はそのサーバー上で署名照合を行うことを推奨する。

セキュリティと設計に関するベストプラクティスに関する情報がもっと知りたい場合はSecurity and Designを参照。






Implementing In-app Billing (IAB Version 3)

In-app Billing on Google Play provides a straightforward, simple interface for sending In-app Billing requests and managing In-app Billing transactions using Google Play. The information below covers the basics of how to make calls from your application to the In-app Billing service using the Version 3 API.
Note: To see a complete implementation and learn how to test your application, see the Selling In-app Products training class. The training class provides a complete sample In-app Billing application, including convenience classes to handle key tasks related to setting up your connection, sending billing requests and processing responses from Google Play, and managing background threading so that you can make In-app Billing calls from your main activity.
Before you start, be sure that you read the In-app Billing Overview to familiarize yourself with concepts that will make it easier for you to implement In-app Billing.
To implement In-app Billing in your application, you need to do the following:
  1. Add the In-app Billing library to your project.
  2. Update your AndroidManifest.xml file.
  3. Create a ServiceConnection and bind it to IInAppBillingService.
  4. Send In-app Billing requests from your application to IInAppBillingService.
  5. Handle In-app Billing responses from Google Play.

Adding the AIDL file to your project


IInAppBillingService.aidl is an Android Interface Definition Language (AIDL) file that defines the interface to the In-app Billing Version 3 service. You will use this interface to make billing requests by invoking IPC method calls.
To get the AIDL file:
  1. Open the Android SDK Manager.
  2. In the SDK Manager, expand the Extras section.
  3. Select Google Play Billing Library.
  4. Click Install packages to complete the download.
The IInAppBillingService.aidl file will be installed to <sdk>/extras/google/play_billing/.
To add the AIDL to your project:
  1. Copy the IInAppBillingService.aidl file to your Android project.
    • If you are using Eclipse:
      1. If you are starting from an existing Android project, open the project in Eclipse. If you are creating a new Android project from scratch, click File > New > Android Application Project, then follow the instructions in the New Android Application wizard to create a new project in your workspace.
      2. In the /src directory, click File > New > Package, then create a package named com.android.vending.billing.
      3. Copy the IInAppBillingService.aidl file from <sdk>/extras/google/play_billing/ and paste it into the src/com.android.vending.billing/ folder in your workspace.
    • If you are developing in a non-Eclipse environment: Create the following directory /src/com/android/vending/billing and copy the IInAppBillingService.aidl file into this directory. Put the AIDL file into your project and use the Ant tool to build your project so that the IInAppBillingService.java file gets generated.
  2. Build your application. You should see a generated file named IInAppBillingService.java in the /gen directory of your project.

Updating Your Application's Manifest


In-app billing relies on the Google Play application, which handles all communication between your application and the Google Play server. To use the Google Play application, your application must request the proper permission. You can do this by adding the com.android.vending.BILLING permission to your AndroidManifest.xml file. If your application does not declare the In-app Billing permission, but attempts to send billing requests, Google Play will refuse the requests and respond with an error.
To give your app the necessary permission, add this line in your Android.xml manifest file:
<uses-permission android:name="com.android.vending.BILLING" />

Creating a ServiceConnection


Your application must have a ServiceConnection to facilitate messaging between your application and Google Play. At a minimum, your application must do the following:
  • Bind to IInAppBillingService.
  • Send billing requests (as IPC method calls) to the Google Play application.
  • Handle the synchronous response messages that are returned with each billing request.

Binding to IInAppBillingService

To establish a connection with the In-app Billing service on Google Play, implement a ServiceConnection to bind your activity to IInAppBillingService. Override the onServiceDisconnected and onServiceConnected methods to get a reference to the IInAppBillingService instance after a connection has been established.
IInAppBillingService mService;
ServiceConnection mServiceConn = new ServiceConnection() {
   @Override
   public void onServiceDisconnected(ComponentName name) {
       mService = null;
   }

   @Override
   public void onServiceConnected(ComponentName name, 
      IBinder service) {
       mService = IInAppBillingService.Stub.asInterface(service);
   }
};
In your activity’s onCreate method, perform the binding by calling the bindService method. Pass the method an Intent that references the In-app Billing service and an instance of the ServiceConnection that you created.
@Override
public void onCreate(Bundle savedInstanceState) {    
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);        
    bindService(new 
        Intent("com.android.vending.billing.InAppBillingService.BIND"),
                mServiceConn, Context.BIND_AUTO_CREATE);
You can now use the mService reference to communicate with the Google Play service.
Important: Remember to unbind from the In-app Billing service when you are done with your Activity. If you don’t unbind, the open service connection could cause your device’s performance to degrade. This example shows how to perform the unbind operation on a service connection to In-app Billing called mServiceConn by overriding the activity’s onDestroy method.
@Override
public void onDestroy() {
    super.onDestroy();
    if (mServiceConn != null) {
        unbindService(mServiceConn);
    }   }
For a complete implementation of a service connection that binds to the IInAppBillingService, see the Selling In-app Products training class and associated sample.

Making In-app Billing Requests


Once your application is connected to Google Play, you can initiate purchase requests for in-app products. Google Play provides a checkout interface for users to enter their payment method, so your application does not need to handle payment transactions directly. When an item is purchased, Google Play recognizes that the user has ownership of that item and prevents the user from purchasing another item with the same product ID until it is consumed. You can control how the item is consumed in your application, and notify Google Play to make the item available for purchase again. You can also query Google Play to quickly retrieve the list of purchases that were made by the user. This is useful, for example, when you want to restore the user's purchases when your user launches your app.

Querying for Items Available for Purchase

In your application, you can query the item details from Google Play using the In-app Billing Version 3 API. To pass a request to the In-app Billing service, first create a Bundle that contains a String ArrayList of product IDs with key "ITEM_ID_LIST", where each string is a product ID for an purchasable item.
ArrayList skuList = new ArrayList();
skuList.add("premiumUpgrade");
skuList.add("gas");
Bundle querySkus = new Bundle();
querySkus.putStringArrayList(“ITEM_ID_LIST”, skuList);
To retrieve this information from Google Play, call the getSkuDetails method on the In-app Billing Version 3 API, and pass the method the In-app Billing API version (“3”), the package name of your calling app, the purchase type (“inapp”), and the Bundle that you created.
Bundle skuDetails = mService.getSkuDetails(3, 
   getPackageName(), "inapp", querySkus);
If the request is successful, the returned Bundlehas a response code of BILLING_RESPONSE_RESULT_OK (0).
Warning: Do not call the getSkuDetails method on the main thread. Calling this method triggers a network request which could block your main thread. Instead, create a separate thread and call the getSkuDetails method from inside that thread.
To see all the possible response codes from Google Play, see In-app Billing Reference.
The query results are stored in a String ArrayList with key DETAILS_LIST. The purchase information is stored in the String in JSON format. To see the types of product detail information that are returned, see In-app Billing Reference.
In this example, you are retrieving the prices for your in-app items from the skuDetails Bundle returned from the previous code snippet.
int response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0) {
   ArrayList responseList 
      = skuDetails.getStringArrayList("DETAILS_LIST");
   
   for (String thisResponse : responseList) {
      JSONObject object = new JSONObject(thisResponse);
      String sku = object.getString("productId");
      String price = object.getString("price");
      if (sku.equals("premiumUpgrade")) mPremiumUpgradePrice = price;
      else if (sku.equals("gas")) mGasPrice = price;
   }
}

Purchasing an Item

To start a purchase request from your app, call the getBuyIntent method on the In-app Billing service. Pass in to the method the In-app Billing API version (“3”), the package name of your calling app, the product ID for the item to purchase, the purchase type (“inapp” or "subs"), and a developerPayload String. The developerPayload String is used to specify any additional arguments that you want Google Play to send back along with the purchase information.
Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(),
   sku, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");
If the request is successful, the returned Bundle has a response code of BILLING_RESPONSE_RESULT_OK (0) and a PendingIntent that you can use to start the purchase flow. To see all the possible response codes from Google Play, see In-app Billing Reference. Next, extract a PendingIntent from the response Bundle with key BUY_INTENT.
PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
To complete the purchase transaction, call the startIntentSenderForResult method and use the PendingIntent that you created. In this example, you are using an arbitrary value of 1001 for the request code.
startIntentSenderForResult(pendingIntent.getIntentSender(),
   1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0),
   Integer.valueOf(0));
Google Plays sends a response to your PendingIntent to the onActivityResult method of your application. The onActivityResult method will have a result code of Activity.RESULT_OK (1) or Activity.RESULT_CANCELED (0). To see the types of order information that is returned in the response Intent, see In-app Billing Reference.
The purchase data for the order is a String in JSON format that is mapped to the INAPP_PURCHASE_DATA key in the response Intent, for example:
'{ 
   "orderId":"12999763169054705758.1371079406387615", 
   "packageName":"com.example.app",
   "productId":"exampleSku",
   "purchaseTime":1345678900000,
   "purchaseState":0,
   "developerPayload":"bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ",
   "purchaseToken":"rojeslcdyyiapnqcynkjyyjh"
 }'

Continuing from the previous example, you get the response code, purchase data, and signature from the response Intent.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
   if (requestCode == 1001) {           
      int responseCode = data.getIntExtra("RESPONSE_CODE", 0);
      String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
      String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");
        
      if (resultCode == RESULT_OK) {
         try {
            JSONObject jo = new JSONObject(purchaseData);
            String sku = jo.getString("productId");
            alert("You have bought the " + sku + ". Excellent choice, 
               adventurer!");
          }
          catch (JSONException e) {
             alert("Failed to parse purchase data.");
             e.printStackTrace();
          }
      }
   }
}
Security Recommendation: When you send a purchase request, create a String token that uniquely identifies this purchase request and include this token in the developerPayload.You can use a randomly generated string as the token. When you receive the purchase response from Google Play, make sure to check the returned data signature, the orderId, and the developerPayload String. For added security, you should perform the checking on your own secure server. Make sure to verify that the orderId is a unique value that you have not previously processed, and the developerPayload String matches the token that you sent previously with the purchase request.

Querying for Purchased Items

To retrieve information about purchases made by a user from your app, call the getPurchases method on the In-app Billing Version 3 service. Pass in to the method the In-app Billing API version (“3”), the package name of your calling app, and the purchase type (“inapp” or "subs").
Bundle ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);
The Google Play service returns only the purchases made by the user account that is currently logged in to the device. If the request is successful, the returned Bundle has a response code of 0. The response Bundle also contains a list of the product IDs, a list of the order details for each purchase, and the signatures for each purchase.
To improve performance, the In-app Billing service returns only up to 700 products that are owned by the user when getPurchase is first called. If the user owns a large number of products, Google Play includes a String token mapped to the key INAPP_CONTINUATION_TOKEN in the response Bundle to indicate that more products can be retrieved. Your application can then make a subsequent getPurchases call, and pass in this token as an argument. Google Play continues to return a continuation token in the response Bundle until all products that are owned by the user has been sent to your app.
For more information about the data returned by getPurchases, see In-app Billing Reference. The following example shows how you can retrieve this data from the response.
int response = ownedItems.getInt("RESPONSE_CODE");
if (response == 0) {
   ArrayList ownedSkus = 
      ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
   ArrayList purchaseDataList = 
      ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
   ArrayList signatureList = 
      ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE");
   String continuationToken = 
      ownedItems.getString("INAPP_CONTINUATION_TOKEN");
   
   for (int i = 0; i < purchaseDataList.size(); ++i) {
      String purchaseData = purchaseDataList.get(i);
      String signature = signatureList.get(i);
      String sku = ownedSkus.get(i);
  
      // do something with this purchase information
      // e.g. display the updated list of products owned by user
   } 

   // if continuationToken != null, call getPurchases again 
   // and pass in the token to retrieve more items
}

Consuming a Purchase

You can use the In-app Billing Version 3 API to track the ownership of purchased in-app products in Google Play. Once an in-app product is purchased, it is considered to be "owned" and cannot be purchased from Google Play. You must send a consumption request for the in-app product before Google Play makes it available for purchase again.
Important: Managed in-app products are consumable, but subscriptions are not.
How you use the consumption mechanism in your app is up to you. Typically, you would implement consumption for in-app products with temporary benefits that users may want to purchase multiple times (for example, in-game currency or equipment). You would typically not want to implement consumption for in-app products that are purchased once and provide a permanent effect (for example, a premium upgrade).
To record a purchase consumption, send the consumePurchase method to the In-app Billing service and pass in the purchaseToken String value that identifies the purchase to be removed. The purchaseToken is part of the data returned in the INAPP_PURCHASE_DATA String by the Google Play service following a successful purchase request. In this example, you are recording the consumption of a product that is identified with the purchaseToken in the token variable.
int response = mService.consumePurchase(3, getPackageName(), token);
Warning: Do not call the consumePurchase method on the main thread. Calling this method triggers a network request which could block your main thread. Instead, create a separate thread and call the consumePurchase method from inside that thread.
It's your responsibility to control and track how the in-app product is provisioned to the user. For example, if the user purchased in-game currency, you should update the player's inventory with the amount of currency purchased.
Security Recommendation: You must send a consumption request before provisioning the benefit of the consumable in-app purchase to the user. Make sure that you have received a successful consumption response from Google Play before you provision the item.

Implementing Subscriptions

Launching a purchase flow for a subscription is similar to launching the purchase flow for a product, with the exception that the product type must be set to "subs". The purchase result is delivered to your Activity's onActivityResult method, exactly as in the case of in-app products.
Bundle bundle = mService.getBuyIntent(3, "com.example.myapp",
   MY_SKU, "subs", developerPayload);
PendingIntent pendingIntent = bundle.getParcelable(RESPONSE_BUY_INTENT);
if (bundle.getInt(RESPONSE_CODE) == BILLING_RESPONSE_RESULT_OK) {
   // Start purchase flow (this brings up the Google Play UI).
   // Result will be delivered through onActivityResult().
   startIntentSenderForResult(pendingIntent, RC_BUY, new Intent(),
       Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
}
To query for active subscriptions, use the getPurchases method, again with the product type parameter set to "subs".
Bundle activeSubs = mService.getPurchases(3, "com.example.myapp",
                   "subs", continueToken);
The call returns a Bundle with all the active subscriptions owned by the user. Once a subscription expires without renewal, it will no longer appear in the returned Bundle.

Securing Your Application


To help ensure the integrity of the transaction information that is sent to your application, Google Play signs the JSON string that contains the response data for a purchase order. Google Play uses the private key that is associated with your application in the Developer Console to create this signature. The Developer Console generates an RSA key pair for each application.

Note:To find the public key portion of this key pair, open your application's details in the Developer Console, then click on Services & APIs, and look at the field titled Your License Key for This Application.
The Base64-encoded RSA public key generated by Google Play is in binary encoded, X.509 subjectPublicKeyInfo DER SEQUENCE format. It is the same public key that is used with Google Play licensing.
When your application receives this signed response you can use the public key portion of your RSA key pair to verify the signature. By performing signature verification you can detect responses that have been tampered with or that have been spoofed. You can perform this signature verification step in your application; however, if your application connects to a secure remote server then we recommend that you perform the signature verification on that server.
For more information about best practices for security and design, see Security and Design.

Google Play In-app Billingを訳してみる「In-app Billing Version 3」

In-app Billing バージョン3

In-app Billing バージョン3APIはあなたの開発したアプリケーションにIn-app Billingを組み込むことをさらに容易にしている。このバージョンの特徴は改善された同期決済フローを組み込んでいる点だ。APIは消費アイテムやin-app決済データのローカルキャッシュの所有権を追尾することを容易にする。


商品タイプ

あなたは自分の商品をGoogle Play Developer Consoleを使用することで定義を行う。商品には商品タイプ、SKU、価格、商品説明などが含まれる。さらなる情報はIn-app Billingの管理を参照。バージョン3APIはマネージドのin-app商品と定期購入をサポートしている。


マネージドIn-app商品

マネージドin-app商品はGoogle Playによって所有権情報が追尾され、管理されるアイテムのことを指す。ユーザーがマネージドin-appアイテムを購入するとき、Google Playはユーザーごとの各アイテムに対する決済情報を保存する。これは特定のユーザーが決済を行ったアイテムの状態を復元するために、あなたがあとでいつでもGoogle Playに問い合わせができるようにする。例えユーザーがアプリをアンインストールしたりデバイスを変えたとしても、この情報はGoogle Playサーバーに永続化される。

もしあなたがバージョン3APIを使っているならば、あなたは開発したアプリの中でマネージドアイテムも消費することができる。あなたは何回も消費できるような(ゲーム内通貨、燃料、魔法の呪文など)アイテムの消費に対する一般的な実装をするだろう。一度決済がされると、Google Playに消費リクエストを送ることによりあなたがそのアイテムを消費するまでは、マネージドアイテムはは再び購入することはできない。さらにin-app商品消費に関して学びたければ消費アイテムを参照。


定期購入

定期購入はIn-app Billingで提供されている商品タイプだ。この商品タイプはあなたの開発したアプリ内で、あなたがコンテンツ、サービス、機能を月ごと、または年ごとに売ることができるようにするものだ。あなたは定期購入をほぼあらゆるタイプのデジタルコンテンツをあらゆるタイプのアプリやゲームから定期販売することができる。どのように定期購入が機能するか理解したい場合はIn-app Billing定期購入を参照。

バージョン3APIで、定期購入販売や定期決済情報の回収に際し、あなたはin-app商品と同じ決済フローを使うことができる。コーディング例を見たい方は定期購入実装を参照。

重要:in-app商品と違い、定期購入は消費することができない。


決済アイテム

バージョン3APIに関する典型的な決済フローは以下のとおり。

1.あなたのアプリケーションはisBillingSupportedリクエストをGoogle Playに送る。それはあなたの使っているIn-app Billing APIのバージョンがサポートされているのかを確認するために行う。

2.あなたのアプリケーションの開始時、もしくはユーザーのログイン時にユーザーがどんなアイテムを所持しているのかを決定するために、Google Playに確認をするのは良い対処法である。ユーザーのin-app決済を問い合わせるためには、getPurchasesリクエストを送ればよい。もしリクエストが成功した場合はGoogle PlayはBundleを返す。Bundleには決済アイテムの商品ID一覧、個別の商品詳細一覧、それら決済のsignature一覧が含まれる。

3.大抵の場合、あなたは決済可能な商品をユーザーに知らせたいはずだ。あなたがGoogle Playで定義したin-app商品の詳細を問い合わせるには、あなたのアプリケーションはgetSkuDetailsリクエストを送れば良い。あなたは問い合わせリクエストの中で商品ID一覧を記載しなければならない。もしリクエストが成功した場合、Google PlayはBundleを返す。このBundleは商品価格、タイトル、詳細説明、決済タイプを含んだ商品詳細が含まれている。

4.もしin-app商品をユーザーが所持していない場合、あなたはin-app商品の決済を開始することができる。決済リクエストを開始するには、あなたのアプリケーションはgetBuyIntentリクエストを送る。そこには他のパラメーターに加え、決済アイテムの商品IDも規定する。あなたはDeveloper Consoleで新たなin-app商品を作る場合には商品IDを記録しておいたほうがよい。

a.Google PlayはPendingIntentを含んだBundleを返す。PendingIntentは決済の精算UIを開始する際にあなたのアプリケーションが使用するものである。

b.あなたのアプリケーションはstartIntentSenderForResultメソッドを呼び出すことで、未決済の目的を始める。

c.精算フローが完了した際には(これはユーザーがアイテムの決済に成功したか、もしくは決済をキャンセルした場合)、Google PlayはあなたのonActivityResultメソッドに対してIntentレスポンスを送る。onActivityResultの結果コードは決済が成功したのかキャンセルされたのかを示す。Intentレスポンスは決済アイテムに関する情報を含んでいる。この決済アイテムは、決済トランザクションを一意に規定するためにGoogle Playによって生成されたpurchaseToken文字列を含んでいる。Intentはあなたのprivate developer keyでサインされた決済signatureも含んでいる。

バージョン3APIコールとサーバーレスポンスに関してより知りたい方はIn-app Billing レファレンスを参照。


In-app商品の消費

あなたはin-app商品のユーザー所有権を追尾するための消費メカニズムを使うことができる。

バージョン3では、すべてのin-app商品はマネージドである。このマネージドの意味はすべてのin-appアイテム決済のユーザー所有権はGoogle Playによって管理され、あなたのアプリは必要なときにユーザー決済情報の問い合せができるという意味である。ユーザーがin-app商品の決済に成功したときは、その決済はGoogle Playに記録される。一度in-app商品が決済されると、"owned(所有している)"とみなされる。owned状態のin-app商品はGoogle Playで決済することができない。あなたはownedのin-app商品に対して消費リクエストを送らなければならない。そうすればGoogle Playはその商品を再び決済可能にすることができる。in-app商品を消費すると、"unowned(非所有)"状態に変わり、前の決済データは廃棄される。

ユーザーによって所有された商品リストを取り出すためにはあなたのアプリケーションはgetPurchasesコールをGoogle Playに送る。あなたのアプリケーションはconsumePurchaseコールを送ることによって消費リクエストを生成することができる。リクエストの引数には、あなたはin-app商品にユニークなpurchaseToken文字列を入れなければならない。この文字列は決済された時にGoogle Playから得られるものだ。Google Playは消費が正しく記録されたかどうかを示すステータスコードを返す。


非消費と消費in-app商品

あなたが自分のin-app商品を非消費アイテムとして扱うか消費アイテムとして扱うかを決めるのはあなた次第だ。

非消費アイテム
基本的にあなたはin-app商品に関する消費の実装をしなくてよい。この商品はあなたのアプリケーション内で一度だけ決済ができる、永久的に便益を提供する。一度決済されたら、これらのアイテムは永久的にそのユーザーのGoogleアカウントに紐づく。非消費in-appアイテムの例はプレミアムアップグレードやレベルパックだ。

消費アイテム
対照的に、あなたは複数回消費ができるようにアイテムに関する実装を行う。基本的にこれらのアイテムはある一時的な効果をもたらす。例えば、ユーザーのゲーム内キャラクターがライフポイントやゲーム内商品のコインを得ることが該当する。あなたのアプリ内で決済したアイテムの便益や効果を消費することをin-app商品のプロビジョニングと呼ぶ。あなたはin-app商品がどのようにユーザーにプロビジョンされたかを追跡し、管理を行う責任がある。

重要:あなたのアプリ内で消費可能なin-app商品をプロビジョニング剃る前に、あなたはGoogle Playに消費リクエストを送らなければならない。また、消費が記録されたことを示す成功レスポンスを受け取らなければならない。


あなたのアプリケーション内で消費可能な商品を管理する

ここでは消費可能なin-app商品の決済に関する基本フローに関して記載をする。

1.getBuyIntentコールで決済フローを立ち上げる
2.Google Playから決済が成功したかどうかを示すレスポンスBundleを受け取る
3.もし決済が成功していたら、consumePurchaseコールを生成することで決済を消費する
4.消費が成功したかどうかを示すGoogle Playからのレスポンスコードを受け取る
5.もし消費が成功していたら、あなたのアプリ内で商品をプロビジョニングする

その後、ユーザーがあなたのアプリを始める、もしくはログインした際に、あなたはユーザーが未処理の消費可能なin-app商品を所有していないかどうかをチェックする必要がある。もし未処理のものがあった場合、それらのアイテムの消費とプロビジョニングを確実にすること。以下があなたが自分のアプリ内で消費可能なin-app商品を実装した際の、推奨されるアプリケーション開始フローである。

1.ユーザーが所有しているin-app商品を問い合わせるために、getPurchaseリクエストを送る
2.もし消費可能なin-app商品があった場合、consumePurchaseコールを送り、アイテムを消費する。このステップは必須である。なぜなら、アプリケーションが消費可能アイテムに関する決済オーダーを完了させたが、アプリケーションが消費リクエストを送る前にアプリが停まるか接続が切れてしまうことがあるからだ。
3.消費が成功したかどうかを示すGoogle Playからのレスポンスコードを受け取る
4.消費が成功した場合、商品のプロビジョニングをアプリ内で行う


ローカルキャッシング

Google Playクライアントは現在、デバイス内でIn-app Billing情報をキャッシュしているので、あなたはバージョン3APIをこれらの情報をより頻繁に問い合わせるために使用することができる。例えばgetPurchasesコールを通してなど。前のバージョンのAPIとは違い、多くのバージョン3APIコールはGoogle Playへのネットワーク接続を通す代わりにキャッシュ参照を通してサービスを行う。このことで、APIの応答時間は劇的に向上している。





In-app Billing Version 3

The In-app Billing Version 3 API makes it easier for you to integrate In-app Billing into your applications. The features in this version include improved synchronous purchase flow, APIs to let you easily track ownership of consumable goods, and local caching of in-app purchase data.

Product Types


You define your products using the Google Play Developer Console, including product type, SKU, price, description, and so on. For more information, see Administering In-app Billing. The Version 3 API supports managed in-app products and subscriptions.

Managed In-app Products

Managed in-app products are items that have their ownership information tracked and managed by Google Play. When a user purchases a managed in-app item, Google Play stores the purchase information for each item on a per-user basis. This enables you to later query Google Play at any time to restore the state of the items a specific user has purchased. This information is persistent on the Google Play servers even if the user uninstalls the application or if they change devices.
If you are using the Version 3 API, you can also consume managed items within your application. You would typically implement consumption for items that can be purchased multiple times (such as in-game currency, fuel, or magic spells). Once purchased, a managed item cannot be purchased again until you consume the item, by sending a consumption request to Google Play. To learn more about in-app product consumption, see Consuming Items

Subscriptions

A subscription is a product type offered in In-app Billing that lets you sell content, services, or features to users from inside your app with recurring monthly or annual billing. You can sell subscriptions to almost any type of digital content, from any type of app or game. To understand how subscriptions work, see In-app Billing Subscriptions.
With the Version 3 API, you can use the same purchase flow for buying subscriptions and retrieving subscription purchase information as with in-app products. For a code example, see Implementing Subscriptions.
Important: Unlike in-app products, subscriptions cannot be consumed.

Purchasing Items



Figure 1. The basic sequence for a purchase request.
A typical purchase flow with the Version 3 API is as follows:
  1. Your application sends a isBillingSupported request to Google Play to determine that the target version of the In-app Billing API that you are using is supported.
  2. When your application starts or user logs in, it's good practice to check with Google Play to determine what items are owned by the user. To query the user's in-app purchases, send a getPurchases request. If the request is successful, Google Play returns a Bundle containing a list of product IDs of the purchased items, a list of the individual purchase details, and a list of the signatures for the purchases.
  3. Usually, you'll want to inform the user of the products that are available for purchase. To query the details of the in-app products that you defined in Google Play, your application can send a getSkuDetails request. You must specify a list of product IDs in the query request. If the request is successful, Google Play returns a Bundle containing product details including the product’s price, title, description, and the purchase type.
  4. If an in-app product is not owned by the user, you can initiate a purchase for it. To start a purchase request, your application sends a getBuyIntent request, specifying the product ID of the item to purchase, along with other parameters. You should record the product ID when you create a new in-app product in the Developer Console.
    1. Google Play returns a Bundle that contains a PendingIntent which you application uses to start the checkout UI for the purchase.
    2. Your application launches the pending intent by calling the startIntentSenderForResult method.
    3. When the checkout flow finishes (that is, the user successfully purchases the item or cancels the purchase), Google Play sends a response Intent to your onActivityResult method. The result code of the onActivityResult has a result code that indicates whether the purchase was successful or canceled. The response Intent contains information about the purchased item, including a purchaseToken String that is generated by Google Play to uniquely identify this purchase transaction. The Intent also contains the signature of the purchase, signed with your private developer key.

To learn more about the Version 3 API calls and server responses, see In-app Billing Reference.

Consuming In-app Products


You can use the consumption mechanism to track the user's ownership of in-app products.
In Version 3, all in-app products are managed. This means that the user's ownership of all in-app item purchases is maintained by Google Play, and your application can query the user's purchase information when needed. When the user successfully purchases an in-app product, that purchase is recorded in Google Play. Once an in-app product is purchased, it is considered to be "owned". In-app products in the "owned" state cannot be purchased from Google Play. You must send a consumption request for the "owned" in-app product before Google Play makes it available for purchase again. Consuming the in-app product reverts it to the "unowned" state, and discards the previous purchase data.

Figure 2. The basic sequence for a consumption request.
To retrieve the list of product's owned by the user, your application sends a getPurchases call to Google Play. Your application can make a consumption request by sending a consumePurchase call. In the request argument, you must specify the in-app product's unique purchaseToken String that you obtained from Google Play when it was purchased. Google Play returns a status code indicating if the consumption was recorded successfully.

Non-consumable and Consumable In-app Products

It's up to you to decide if you want to handle your in-app products as non-consumable or consumable items.
Non-consumable Items
Typically, you would not implement consumption for in-app products that can only be purchased once in your application and provide a permanent benefit. Once purchased, these items will be permanently associated to the user's Google account. An example of a non-consumable in-app product is a premium upgrade or a level pack.
Consumable items
In contrast, you can implement consumption for items that can be made available for purchase multiple times. Typically, these items provide certain temporary effects. For example, the user's in-game character might gain life points or gain extra gold coins in their inventory. Dispensing the benefits or effects of the purchased item in your application is called provisioning the in-app product. You are responsible for controlling and tracking how in-app products are provisioned to the users.
Important: Before provisioning the consumable in-app product in your application, you must send a consumption request to Google Play and receive a successful response indicating that the consumption was recorded.

Managing consumable purchases in your application

Here is the basic flow for purchasing a consumable in-app product:
  1. Launch a purchase flow with a getBuyIntent call
  2. Get a response Bundlefrom Google Play indicating if the purchase completed successfully.
  3. If the purchase was successful, consume the purchase by making a consumePurchase call.
  4. Get a response code from Google Play indicating if the consumption completed successfully.
  5. If the consumption was successful, provision the product in your application.
Subsequently, when the user starts up or logs in to your application, you should check if the user owns any outstanding consumable in-app products; if so, make sure to consume and provision those items. Here's the recommended application startup flow if you implement consumable in-app products in your application:
  1. Send a getPurchases request to query the owned in-app products for the user.
  2. If there are any consumable in-app products, consume the items by calling consumePurchase. This step is necessary because the application might have completed the purchase order for the consumable item, but stopped or got disconnected before the application had the chance to send a consumption request.
  3. Get a response code from Google Play indicating if the consumption completed successfully.
  4. If the consumption was successful, provision the product in your application.

Local Caching


Because the Google Play client now caches In-app Billing information locally on the device, you can use the Version 3 API to query for this information more frequently, for example through a getPurchases call. Unlike with previous versions of the API, many Version 3 API calls will be serviced through cache lookups instead of through a network connection to Google Play, which significantly speeds up the API's response time. 

Google Play In-app Billingを訳してみる「Overview」

In-app Billingの概要

このドキュメントは基本的なIn-app Billingの構成要素や機能に関して記載している。それら構成要素や機能はあなたが開発したアプリケーションにIn-app Billingの機能を加えるために理解する必要のあるものだ。


In-app Billing API

あなたのアプリケーションはIn-app BillingサービスにAPIを用いてアクセスする。そのAPIはデバイスにインストールされたGoogle Play appによってさらされている。Google Play appはあなたのアプリケーションとGoogle Play サーバーの間の決済リクエストやレスポンスを伝搬している。実際、あなたのアプリケーションは決して直接にGoogle Playサーバーと通信を行うことはない。その代わり、あなたのアプリケーションは決済リクエストをGoogle Playアプリケーションに対してプロセス間通信(IPC)を通して行い、Google Play appからレスポンスを受け取る。あなたのアプリケーションは自分自身とGoogle Playサーバー間のネットワーク接続を管理したりはしない。

In-app billing Version 3は最新バージョンで、様々なアンドロイドデバイス間での広い互換性を維持している。In-app Billing Version 3はAndroid2.2とそれ以上で動くデバイスをサポートしている。これらのバージョンはGoogle Play ストアがインストールされた最新バージョンを所持している(アクティブデバイスの圧倒的多数を占めている)

Version 3 の特徴
・リクエストは最新のAPIを通じて送られる。そのAPIはあなたが容易にGoogle Playより商品詳細をリクエストしたり、in-app商品の注文を行ったり、あなたの所有権に基づいて迅速にアイテムを返させる
・オーダー情報は決済の完了時、同期的にデバイスに伝搬する
・すべての決済は「管理(これはGoogle Playがin-app製品のユーザーの所有権を追い続けるということ)」されている。ユーザーはin-appアイテムの複数のコピーを持つことができない。あらゆる時点で一つのコピーのみ持つことができる
・決済アイテムは消費することができる。消費されたとき、そのアイテムは「非所有」の状態に戻り、再度Google Playから購入することができる
・定期購入の機能をサポートしている

In-app Billingの他のバージョンの詳細についてはバージョンノートを参照。


In-app商品

In-app商品はデジタル商品だ。そのデジタル商品はあなたの作ったアプリケーションからユーザーに対して販売を行う際に提供するものだ。デジタル商品の例としてゲーム内通貨、ユーザー体験を高めるアプリ機能のアップグレード、あなたの作ったアプリの新コンテンツが含まれる。

あなたはIn-app Billingをデジタルコンテンツの販売にのみ使用することができる。あなたはIn-app Billingを物理的な商品の販売、個人的なサービス、物理的な配送を必要とする何かに使用することはできない。価格のついたアプリケーションとは異なり、一度ユーザーがIn-app商品を購入すると返金画面は表示されない。

Google Playはコンテンツ付与のフォームは何ら提供をしない。あなたは自分の開発したアプリ内で販売をするデジタルコンテンツの付与を担当する。In-app商品は常に明確に一対一アプリに紐付いている。それはつまり、特定のアプリケーションは他のアプリケーションによって公開されたin-app商品を購入することはできないということだ。それがたとえ統一デベロッパーによるものだったとしても。


商品タイプ

In-app Billingは異なる商品タイプをサポートしている。この商品タイプはあなたの開発したアプリケーションをマネタイズする方法に柔軟性を与えている。すべてのケースにおいて、あなたはGoogle Play Developer Consoleを使うことで商品を定義できる。

あなたはIn-app Billingアプリケーションにこれら商品タイプを規定することができる - in-app商品か定期購入かの管理を。Google playはユーザーアカウントごとにあなたのアプリケーションでin-app商品か定期購入かに関する所有権を管理、追尾する。In-app Billing Version 3でサポートされている商品タイプに関して学びたい人はこちら


Google Play Developer Console

Developer ConsoleはあなたがIn-app Billing アプリケーションを発行できる場所であり、あなたの開発したアプリで決済できるいろいろなin-app商品を管理する場所だ。

あなたはデジタルアイテムの商品リストを作ることができる。そのデジタルアイテムはあなたの開発したアプリケーションに関連し、一度きりの決済や繰り返し行われる定期購入のアイテムも含んでいる。各々のアイテムに対して、あなたはアイテムのユニークproduct ID(SKUも含む)、product type,価格、商品説明のような情報を定義することができ、またどのようにGoogle Playがその商品の決済を管理し、追尾するかも定義することができる。

あなたはリリースしていないテストアプリへのアクセスを許可するテストアカウントの作成も行うことができる。

Developer Consoleを使ってどのようにin-app商品や商品リストを設定するのかを学びたければ、In-app Billingの管理を参照。


Google Play決済フロー

Google Playはアプリケーションの決済で使われているものと同じ精算バックエンドを使用している。だから、あなたの開発したアプリのユーザーは一貫した馴染みのある決済フローを経験する。

重要:Google Play上でIn-app Billingサービスを使うためにはGoogle Wallet merchantアカウントを持たなければならない。

決済を開始するにあたり、あなたの開発したアプリケーションは特定のin-app商品に対するリクエストを送る。Google Playはその時決済に関する精算詳細のすべてを管理する。その決済というのは、リクエスト、決済フォームのバリデート、決済トランザクションのプロセスを含む。

精算プロセスが完了したとき、Google Playはあなたのアプリケーションに決済詳細を送る。決済詳細はorder番号、注文日と時間、払われた金額などだ。決済のどのポイントでも、あなたの開発したアプリケーションは決済トランザクションの管理をする必要はない。その役割はGoogle Playによって行われる。

図1.アプリケーションはIn-app Billingリクエストを自身の独自URを通して始める(最初の画像)。Google Playは精算ユーザーインターフェースを提供することでリクエストの処理を行う(真ん中の画像)。精算が完了したとき、アプリケーションは再開される。


サンプルアプリケーション

あなたの開発したアプリケーションにIn-app Billingを組み込む助けになるよう、Android SDKはサンプルアプリケーションを提供している。そのサンプルアプリはどのようにin-app商品や定期購入をアプリの中から販売するのかの実演をしている。

バージョン3APIのためのTrivialDriveサンプルアプリはドライビングゲームのおけるin-app商品や定期購入決済を実装するために、In-app Billing Version 3 APIをどのように使えばよいかを示している。そのアプリケーションはIn-app Billingリクエストをどのように送るか、そしてGoogle Playからの同期レスポンスをどう管理するかの実演をしている。そのアプリケーションはどのようにAPIでアイテム消費が記録されるかも示している。バージョン3サンプルは自動署名検証の実行機能と同様のIn-app Billing管理に便利なクラスも含んでいる。

推奨:アプリケーションをリリースする前にはコードの難読化処理を行ったほうがよい。さらなる情報は、セキュリティと設計を参照。


バージョン移行の判断について

もしあなたがバージョン2やそれ以前の既に存在しているIn-app Billing実装を使用しているのであれば、都合がつく最も早い段階で、In-app Billing Version 3への移行を強く推奨する。

もしあなたがin-app商品を売るアプリを既にリリースしているのであれば、以下に留意のこと。
・あなたが以前Developer Consoleで定義していた商品や定期購入の管理はバージョン3でも以前と同様に動く
・現在のアプリケーションで定義していたあなたの開発したアプリから直で動く(unmanaged)アイテムはGoogle Play管理の(managedな)商品として扱われる。もしあなたがバージョン3APIを使ってこれらのアイテムに関する決済リクエストを起こった場合は。あなたはこれらのアイテムに関して、新たな商品登録をDeveloper Consoleで作る必要はない。そして、あなたはこれらのアイテムの決済を行う際に、同じプロダクトIDを使うことができる。もしあなたがバージョン2やそれ以前のAPIを使ってこれらアイテムの決済を行う場合はunmanagedとして取り扱い続けることができる。


In-app Billing Overview

Quickview

  • Use In-app Billing to sell digital goods, including one-time items and recurring subscriptions.
  • Supported for any app published on Google Play. You only need a Google Play Developer Console account and a Google Wallet merchant account.
  • Checkout processing is automatically handled by Google Play, with the same look-and-feel as for app purchases.

In this document

  1. In-app Billing API
  2. In-app Products
    1. Product Types
  3. Google Play Developer Console
  4. Google Play Purchase Flow
  5. Sample App
  6. Migration Considerations

Related Samples

  1. Sample Application (V3)
This documentation describes the fundamental In-app Billing components and features that you need to understand in order to add In-app Billing features into your application.

In-app Billing API


Your application accesses the In-app Billing service using an API that is exposed by the Google Play app that is installed on the device. The Google Play app then conveys billing requests and responses between your application and the Google Play server. In practice, your application never directly communicates with the Google Play server. Instead, your application sends billing requests to the Google Play application over interprocess communication (IPC) and receives responses from the Google Play app. Your application does not manage any network connections between itself and the Google Play server.
In-app Billing can be implemented only in applications that you publish through Google Play. To complete in-app purchase requests, the Google Play app must be able to access the Google Play server over the network.
In-app billing Version 3 is the latest version, and maintains very broad compatibility across the range of Android devices. In-app Billing Version 3 is supported on devices running Android 2.2 or higher that have the latest version of the Google Play store installed (a vast majority of active devices).

Version 3 features

  • Requests are sent through a streamlined API that allows you to easily request product details from Google Play, order in-app products, and quickly restore items based on users' product ownership
  • Order information is synchronously propagated to the device on purchase completion
  • All purchases are “managed” (that is, Google Play keeps track of the user's ownership of in-app products). The user cannot own multiple copies of an in-app item; only one copy can be owned at any point in time
  • Purchased items can be consumed. When consumed, the item reverts to the "unowned" state and can be purchased again from Google Play
  • Provides support for subscriptions
For details about other versions of In-app Billing, see the Version Notes.

In-app Products


In-app products are the digital goods that you offer for sale from inside your application to users. Examples of digital goods includes in-game currency, application feature upgrades that enhance the user experience, and new content for your application.
You can use In-app Billing to sell only digital content. You cannot use In-app Billing to sell physical goods, personal services, or anything that requires physical delivery. Unlike with priced applications, once the user has purchased an in-app product there is no refund window.
Google Play does not provide any form of content delivery. You are responsible for delivering the digital content that you sell in your applications. In-app products are always explicitly associated with one and only one app. That is, one application cannot purchase an in-app product published for another app, even if they are from the same developer.

Product types

In-app Billing supports different product types to give you flexibility in how you monetize your application. In all cases, you define your products using the Google Play Developer Console.
You can specify these types of products for your In-app Billing application — managed in-app products and subscriptions. Google Play handles and tracks ownership for in-app products and subscriptions on your application on a per user account basis. Learn more about the product types supported by In-app Billing Version 3.

Google Play Developer Console


The Developer Console is where you can publish your In-app Billing application, and manage the various in-app products that are available for purchase from your application.
You can create a product list of digital goods that are associated with your application, including items for one-time purchase and recurring subscriptions. For each item, you can define information such as the item’s unique product ID (also called its SKU), product type, pricing, description, and how Google Play should handle and track purchases for that product.
You can also create test accounts to authorize access for testing applications that are unpublished.
To learn how to use the Developer Console to configure your in-app products and product list, see Administering In-app Billing.

Google Play Purchase Flow


Google Play uses the same checkout backend service as is used for application purchases, so your users experience a consistent and familiar purchase flow.
Important: You must have a Google Wallet merchant account to use the In-app Billing service on Google Play.
To initiate a purchase, your application sends a billing request for a specific in-app product. Google Play then handles all of the checkout details for the transaction, including requesting and validating the form of payment and processing the financial transaction.
When the checkout process is complete, Google Play sends your application the purchase details, such as the order number, the order date and time, and the price paid. At no point does your application have to handle any financial transactions; that role is provided by Google Play.

Figure 1. Applications initiate In-app Billing requests through their own UI (first screen). Google Play responds to the request by providing the checkout user interface (middle screen). When checkout is complete, the application resumes.

Sample Application


To help you integrate In-app Billing into your application, the Android SDK provides a sample application that demonstrates how to sell in-app products and subscriptions from inside an app.
The TrivialDrive sample for the Version 3 API sample shows how to use the In-app Billing Version 3 API to implement in-app product and subscription purchases for a driving game. The application demonstrates how to send In-app Billing requests, and handle synchronous responses from Google Play. The application also shows how to record item consumption with the API. The Version 3 sample includes convenience classes for processing In-app Billing operations as well as perform automatic signature verification.
Recommendation: Make sure to obfuscate the code in your application before you publish it. For more information, see Security and Design.

Migration Considerations


If you have an existing In-app Billing implementation that uses Version 2 or earlier, it is strongly recommended that you migrate to In-app Billing Version 3 at your earliest convenience.
If you have published apps selling in-app products, note that:
  • Managed items and subscriptions that you have previously defined in the Developer Console will work with Version 3 as before.
  • Unmanaged items that you have defined for existing applications will be treated as managed products if you make a purchase request for these items using the Version 3 API. You do not need to create a new product entry in Developer Console for these items, and you can use the same product IDs to purchase these items. They will still continue to be treated as unmanaged items if you make a purchase request for them using the Version 2 or earlier API.