2014/08/24

Android:Selling In-app Products

Introduction

AndroidではGoogle Playサービスを利用してアプリ内課金を比較的容易に導入できます.
本稿ではビジネス戦略の1つ”アプリ内課金”にフォーカスしたAndroid Developers | Selling In-app Productsを翻訳し, その実装方法について学びます.

Selling In-app Products

In this class, you’ll learn how to perform common In-app Billing operations from Android applications.

本章では, アプリ内課金に関する共通のオペレーションについて記載する.

In-app billing is a service hosted on Google Play that lets you charge for digital content or for upgrades in your app. The In-app Billing API makes it easy for you to integrate In-app Billing into your applications. You can request product details from Google Play, issue orders for in-app products, and quickly retrieve ownership information based on users’ purchase history. You can also query the Google Play service for details about in-app products, such as local pricing and availability.

アプリ内課金はデジタルコンテンツやアプリの有料アップグレードの請求に利用できるGoogle Playのサービスである.
アプリ内課金APIは簡単にアプリケーションに組み込むことができる.
Google Playに商品の詳細をリクエストしたり, アプリ内商品のオーダを発行したり,
ユーザのアイテム購入履歴から所有者情報を復元したりもできる.
そして, アプリ内商品のローカル価格や有効性についての詳細をGoogle Playに問い合わせできる.

Google Play provides a checkout interface that makes user interactions with the In-app Billing service seamless, and provides a more intuitive experience to your users.

Google Playはシームレスな清算インタフェースをアプリ内課金サービスで提供し, より直感的なユーザ体験を提供する.

This class describes how to get started with the Version 3 API. To learn how to use the version 2 API, see Implementing In-App Billing (V2).

この投稿ではIn-app Billing APIのVer.3について記載する. Ver.2のAPIについて知りたい場合はImplementing In-App Billing (V2).を参照.

Preparing Your In-app Billing Application

Before you can start using the In-app Billing service, you’ll need to add the library that contains the In-app Billing Version 3 API to your Android project. You also need to set the permissions for your application to communicate with Google Play. In addition, you’ll need to establish a connection between your application and Google Play. You should also verify that the In-app Billing API version that you are using in your application is supported by Google Play.

アプリ内課金サービスを利用するためにはAndroidプロジェクトへIn-app Billing Ver.3 APIし,
Google Playと通信するためにパーミッションの定義を必要とする.
さらに, 使用するアプリ内課金のAPIバージョンが, 連携するGoogle Playでサポートされているかを確認する必要がある.

Download the Sample Application

In this training class, you will use a reference implementation for the In-app Billing Version 3 API called the TrivialDrive sample application. The sample includes convenience classes to quickly set up the In-app Billing service, marshal and unmarshal data types, and handle In-app Billing requests from the main thread of your application.

ここでは, In-app Billing API Ver.3 を使用するTrivialDriveサンプルアプリを例に実装方法を見る.
サンプルアプリは, In-app Billing serviceのセットアップがすぐにでき, 組織化および非組織化されたデータ種別, そしてアプリmainスレッドでIn-app Billingリクエストをハンドルする便利クラスを含んでいる.

To download the sample application:

  • Open the Android SDK Manager.
  • In the SDK Manager, expand the Extras section.
  • Select Google Play Billing Library.
  • Click Install packages to complete the download.

The sample files will be installed to <sdk>/extras/google/play_billing/.

サンプルアプリのダウンロード方法は次の通り.

  1. Android SDK Managerを起動
  2. SDK ManagerでExtrasセクションを展開
  3. Google Play Billing Libraryを選択
  4. Install packagesを選択してダウンロードする

サンプルは<sdk>/extras/google/play_billing/にダウンロードされる.

Add Your Application to the Developer Console

The Google Play Developer Console is where you publish your In-app Billing application and manage the various digital goods that are available for purchase from your application. When you create a new application entry in the Developer Console, it automatically generates a public license key for your application.

Google Play Developer Consoleはアプリ内課金アプリを公開し, アプリで購入可能な様々な商品の管理も行う.
Developer Consoleで新規にアプリ登録した場合は, 自動でパブリックライセンスキーが払い出される.

You will need this key to establish a trusted connection from your application to the Google Play servers. You only need to generate this key once per application, and don’t need to repeat these steps when you update the APK file for your application.

パブリックライセンスキーは, アプリとGoogle Play間でセキュア接続を確立するために必要になる.
このキーを生成するのは一度だけで. アプリアップデートの度に毎回生成し直す必要はない.

To add your application to the Developer Console:

  1. Go to the Google Play Developer Console site and log in. You will need to register for a new developer account, if you have not registered previously. To sell in-app items, you also need to have a Google Wallet merchant account.
  2. Click on Try the new design to access the preview version of the Developer Console, if you are not already logged on to that version.
  3. In the All Applications tab, add a new application entry.
    • Click Add new application.
    • Enter a name for your new In-app Billing application.
    • Click Prepare Store Listing.
  4. In the Services & APIs tab, find and make a note of the public license key that Google Play generated for your application. This is a Base64 string that you will need to include in your application code later.

Your application should now appear in the list of applications in Developer Console.

Developer Consoleにアプリを追加する:

  1. Google Play Developer Consoleにログインする. 開発用アカウントを持っていない場合は作成する.
    アプリ内商品を売るにはGoogle Wallet merchantアカウントが必要になる.
  2. プレビューバージョンのDeveloper Consoleにルグインしていない場合はTry the new designをクリック
  3. All Applicationタブから新しくアプリを登録
    - Add new applicationをクリック
    - In-app Billingアプリの名前を入力
    - Prepare Store Listingをクリック
  4. Service & APIsタブで, 生成されたパブリックライセンスキーをメモする.
    キーはBase64エンコードされた文字列で, 後でアプリに組み込む必要がある.

これでアプリがDeveloper Consoleのアプリ一覧に追加される.

Add the In-app Billing Library

To use the In-app Billing Version 3 features, you must add the IInAppBillingService.aidl file to your Android project. This Android Interface Definition Language (AIDL) file defines the interface to the Google Play service.

In-app Builling Ver.3 APIを使うためには, Google Playサービスのインターフェースを定義したIInAppBillingService.aidlをAndroidプロジェクトへ追加する.

You can find the IInAppBillingService.aidl file in the provided sample app. Depending on whether you are creating a new application or modifying an existing application, follow the instructions below to add the In-app Billing Library to your project.

サンプルアプリもIInAppBillingService.aidlを持っている.
In-app Billing Version 3 library追加の手順を, 新規アプリ作成する場合 or 既存アプリを変更する場合 それぞれで例示する.

New Project

To add the In-app Billing Version 3 library to your new In-app Billing project:

新規アプリ作成する場合:

  1. Copy the TrivialDrive sample files into your Android project.
  2. Modify the package name in the files you copied to use the package name for your project. In Eclipse, you can use this shortcut: right-click the package name, then select Refactor > Rename.
  3. Open the AndroidManifest.xml file and update the package attribute value to use the package name for your project.
  4. Fix import statements as needed so that your project compiles correctly. In Eclipse, you can use this shortcut: press Ctrl+Shift+O in each file showing errors.
  5. Modify the sample to create your own application. Remember to copy the Base64 public license key for your application from the Developer Console over to your MainActivity.java.
  1. TrivialDriveサンプルにあるファイルをプロジェクトにコピーする
  2. ファイル内のパッケージ名を自アプリのパッケージ名に置き換える
  3. AndroidManifest.xmlのパッケージ名をあなたのアプリのパッケージ名に置き換える
  4. 必要なクラスをimportし, エラーをとる
  5. MainActivity.javaに, Developer Consoleで払い出されたBase64パブリックライセンスキーに置き換える
Existing Project

To add the In-app Billing Version 3 library to your existing In-app Billing project:

既存プロジェクトに追加する場合:

  1. Copy the IInAppBillingService.aidl file to your Android project.
    • If you are using Eclipse: Import the IInAppBillingService.aidl file into your /src directory.
    • 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.
  2. Build your application. You should see a generated file named IInAppBillingService.java in the /gen directory of your project.
  3. Add the helper classes from the /util directory of the TrivialDrive sample to your project. Remember to change the package name declarations in those files accordingly so that your project compiles correctly.
  1. IInAppBillingService.aidlファイルをプロジェクトにコピーする
  2. プロジェクトをビルドし, /genに生成されたIInAppBillingService.javaファイルを確認する
  3. TriviaDriveサンプルの/utilディレクトリにあるヘルパークラスをプロジェクトにコピーしてパッケージ名を変更する(パッケージ名は適宜変更する)

Your project should now contain the In-app Billing Version 3 library.

これでアプリにIn-app Billing Ver.3 libraryが取り込まれる.

Set the Billing Permission

Your app needs to have permission to communicate request and response messages to the Google Play’s billing service. To give your app the necessary permission, add this line in your AndroidManifest.xml manifest file:

Google Playの課金Serviceと通信する為に必要なPermissionをAndroidManifest.xmlに定義する.

<uses-permission android:name="com.android.vending.BILLING" />

Initiate a Connection with Google Play

You must bind your Activity to Google Play’s In-app Billing service to send In-app Billing requests to Google Play from your application. The convenience classes provided in the sample handles the binding to the In-app Billing service, so you don’t have to manage the network connection directly.

アプリからGoogle Playへ課金リクエストを送るには, ActivityをGoogle Playの課金Serviceにバインドする必要がある.
サンプルにあるヘルパークラスが課金Serviceへのバインドを処理するため, ネットワーク接続をあなたが直接意識する必要はない.

To set up synchronous communication with Google Play, create an IabHelper instance in your activity’s onCreate method. In the constructor, pass in the Context for the activity, along with a string containing the public license key that was generated earlier by the Google Play Developer Console.

Google Playとの同期通信を準備するため, ActivityonCreateメソッドでIabHelperインスタンスを生成する.
コンストラクタにはContextとパブリックライセンスキーを渡す.

Security Recommendation: It is highly recommended that you do not hard-code the exact public license key string value as provided by Google Play. Instead, you can construct the whole public license key string at runtime from substrings, or retrieve it from an encrypted store, before passing it to the constructor. This approach makes it more difficult for malicious third-parties to modify the public license key string in your APK file.

Security Recommendation:
パブリックライセンスキーは実行時に部分文字列から構築して生成するか, 暗号化して管理し, ハードコーディングは避けるように.
これは悪意のある第三者によるAPKにあるライセンスキーの改竄をより困難にする.

IabHelper mHelper;

@Override
public void onCreate(Bundle savedInstanceState) {
   // ...
   String base64EncodedPublicKey;

   // compute your public key and store it in base64EncodedPublicKey
   mHelper = new IabHelper(this, base64EncodedPublicKey);
}

Next, perform the service binding by calling the startSetup method on the IabHelper instance that you created. Pass the method an OnIabSetupFinishedListener instance, which is called once the IabHelper completes the asynchronous setup operation. As part of the setup process, the IabHelper also checks if the In-app Billing Version 3 API is supported by Google Play. If the API version is not supported, or if an error occured while establishing the service binding, the listener is notified and passed an IabResult object with the error message.

次に、IabHelperstartSetupメソッドを呼んでServiceをバインドする. 非同期のセットアップが完了するとOnIabSetupFinishedListenerのメソッドが呼ばれる.
セットアップではIabHelperが, Google PlayのIn-app Billing Ver.3サポートをチェックする.
もしAPIがサポートされていなかったり, サービスのバインドが失敗した場合には, エラーメッセージを含んだIabResultオブジェクトがリスナーに通知される.

mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
   public void onIabSetupFinished(IabResult result) {
      if (!result.isSuccess()) {
         // Oh noes, there was a problem.
         Log.d(TAG, "Problem setting up In-app Billing: " + result);
      }            
         // Hooray, IAB is fully set up!  
   }
});

If the setup completed successfully, you can now use the mHelper reference to communicate with the Google Play service. When your application is launched, it is a good practice to query Google Play to find out what in-app items are owned by a user. This is covered further in the Query Purchased Items section.

セットアップが正常に完了したらGoogle Play Serviceと通信するmHelperが使用できる.
アプリ起動時にユーザの商品所有状態をチェックするのが良い方法である.
これについてはQuery Purchased Itemsで述べる.

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. To unbind and free your system resources, call the IabHelper’s dispose method when your Activity gets destroyed.

重要: Activity終了時に課金Serviceをアンバインドすること.
アンバインドを忘れてサービスとのコネクションを接続したままにすると端末のパフォーマンスが悪くなる.
アンバインドとシステムリソースを解放するにはIabHelperdisposeメソッドをActivity破棄時に呼び出すこと.

@Override
public void onDestroy() {
   super.onDestroy();
   if (mHelper != null) mHelper.dispose();
   mHelper = null;
}

Establishing In-app Billing Products for Sale

Before publishing your In-app Billing application, you’ll need to define the product list of digital goods available for purchase in the Google Play Developer Console.

課金アプリを公開する前に, Google Play Developer Consoleで販売できる商品のプロダクトリストを定義する.

Specify In-app Products in Google Play

From the Developer Console, you can define product information for in-app products and associate the product list with your application.

Developer Consoleで, アプリ内商品を定義してアプリと関連付ける.

To add new in-app products to your product list:

新しいin-appプロダクトをリストに追加する方法:

  1. Build a signed APK file for your In-app Billing application. To learn how to build and sign your APK, see Building Your Application for Release. Make sure that you are using your final (not debug) certificate and private key to sign your application.
  2. In the Developer Console, open the application entry that you created earlier.
  3. Click on the APK tab then click on Upload new APK. Upload the signed APK file to the Developer Console. Don’t publish the app yet!
  4. Navigate to the uploaded app listing, and click on In-app Products.
  5. Click on the option to add a new product, then complete the form to specify the product information such as the item’s unique product ID (also called its SKU), description, price, and country availability. Note down the product ID since you might need this information to query purchase details in your application later.
    Important: The In-app Billing Version 3 service only supports managed in-app products, so make sure that you specify that the purchase type is ‘Managed’ when you add new items to your product list in the Developer Console.
  6. Once you have completed the form, activate the product so that your application can purchase it.
    Warning: It may take up to 2-3 hours after uploading the APK for Google Play to recognize your updated APK version. If you try to test your application before your uploaded APK is recognized by Google Play, your application will receive a ‘purchase cancelled’ response with an error message “This version of the application is not enabled for In-app Billing.”
  1. 商用署名済みAPKを作成する. 商用署名ビルドについてはBuilding Your Application for Releaseを参照.
  2. Developer Consoleでアプリの登録画面を開く
  3. APKタブ > Upload new APKと進み, 署名済みAPKをアップロードする(まだ公開しないこと!)
  4. アップロードしたアプリのIn-app Productをクリック.
  5. 新しい商品を追加するためのoptionをクリック.
    商品情報(アイテムのユニークID(SKU), 説明, 価格, 利用できる国)をフォームに入力する. ユニークIDはこのあとのアプリでの購入情報の問い合わせに必要になるため書き留めておくこと.
    重要:
    In-app Billing Ver.3サービスは管理されたアプリ内商品のみをサポートする.
    Developer Consoleで新しい商品をプロダクトリストに追加した際には, 購入種別が”Managed”に指定されていることを確認すること.
  6. 登録が終わったら商品をアプリで購入することが可能になる.
    注意:
    APKはGoogle Playにアップしてから2-3時間後に有効化される場合がある.
    もし反映されるよりも前にテストすると, “purcase cancelled”, “This version of the application is not enabled for In-app Billing”のエラーが応答される.

Query Items Available for Purchase

You can query Google Play to programmatically retrieve details of the in-app products that are associated with your application (such as the product’s price, title, description, and type). This is useful, for example, when you want to display a listing of unowned items that are still available for purchase to users.

アプリと関係する商品情報(商品価格, タイトル, 説明, 種別)をプログラマブルにGoogle Playへ問い合わせることができる.
例えば, 未購入の商品を表示したい場合などに使用される.

Note: When making the query, you will need to specify the product IDs for the products explicitly. You can manually find the product IDs from the Developer Console by opening the In-app Products tab for your application. The product IDs are listed under the column labeled Name/ID.

Note: クエリにはどの商品かを特定するための商品IDが必要になる.
商品IDはDeveloper ConsoleのIn-app ProductsタブにあるName/IDラベルのカラムにリストされている.

To retrieve the product details, call queryInventoryAsync(boolean, List, QueryInventoryFinishedListener) on your IabHelper instance.

商品を検索するのに, IabHelperqueryInventoryAsync(boolean, List, QueryInventoryFinishedListener)メソッドが使える.

  1. The first input argument indicates whether product details should be retrieved (should be set to true).
  2. The List argument consists of one or more product IDs (also called SKUs) for the products that you want to query.
  3. Finally, the QueryInventoryFinishedListener argument specifies a listener is notified when the query operation has completed and handles the query response.
  1. 1つめの引数は商品情報を検索対象とするかどうか(検索する場合はtrueをセット)
  2. 引数Listは, 検索対象の商品ID(SKU)を指定
  3. 引数QueryInventoryFinishedListenerは, クエリ完了とその結果を受け取るためのリスナを指定する

If you use the convenience classes provided in the sample, the classes will handle background thread management for In-app Billing requests, so you can safely make queries from the main thread of your application.

もしサンプルにあるヘルパークラスを使用すれば, 課金リクエストをバックグラウンドで実行するのでメインスレッドからでも安全に呼び出せる.

The following code shows how you can retrieve the details for two products with IDs SKU_APPLE and SKU_BANANA that you previously defined in the Developer Console.

次はDeveloper Consoleであらかじめ定義したSKU_APPLESKU_BANANA, 2つの商品詳細を検索するコード.

List additionalSkuList = new List();
additionalSkuList.add(SKU_APPLE);
additionalSkuList.add(SKU_BANANA);
mHelper.queryInventoryAsync(true, additionalSkuList,
   mQueryFinishedListener);

If the query is successful, the query results are stored in an Inventory object that is passed back to the listener.

クエリが成功したらInventoryオブジェクトに結果が格納されてリスナーに通知される.

The following code shows how you can retrieve the item prices from the result set.

次のコードは結果セットから商品価格を取り出す方法.

IabHelper.QueryInventoryFinishedListener 
   mQueryFinishedListener = new IabHelper.QueryInventoryFinishedListener() {
   public void onQueryInventoryFinished(IabResult result, Inventory inventory)   
   {
      if (result.isFailure()) {
         // handle error
         return;
       }

       String applePrice =
          inventory.getSkuDetails(SKU_APPLE).getPrice();
       String bananaPrice =
          inventory.getSkuDetails(SKU_BANANA).getPrice();

       // update the UI 
   }
}

Purchasing In-app Billing Products

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.

アプリとGoogle Playを接続すれば, アプリ内商品の購入リクエストを開始できる.
Google Playは支払い方法を指定できるチェックアウト用のインタフェースを提供するため, アプリは直接支払い処理を実装する必要がない.

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.

商品の支払いが完了した時, Google Playはユーザがその商品を所有したことを認識し, 同じIDの商品を購入できないようケアする.
アプリ内商品の消費はコントロールでき, 再び購入可能とするためにGoogle Playへ通知することができる.

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.

また, Google Playにユーザの購入履歴を問い合わせることができる.
例えば, アプリ起動時に購入履歴から商品の所有状態を復元するのに利用できる.

Purchase an Item

To start a purchase request from your app, call launchPurchaseFlow(Activity, String, int, OnIabPurchaseFinishedListener, String) on your IabHelper instance. You must make this call from the main thread of your Activity. Here’s an explaination of the launchPurchaseFlow method parameters:

アプリから購入リクエストを開始する時, IabHelperlaunchPurchaseFlow(Activity, String, int, OnIabPurchaseFinishedListener, String)を呼び出す. これはActivityのメインスレッドから呼ぶこと. launchPurchaseFlowメソッドのパラメータは下記の通り.

  • The first argument is the calling Activity.
  • The second argument is the product ID (also called its SKU) of the item to purchase. Make sure that you are providing the ID and not the product name. You must have previously defined and activated the item in the Developer Console, otherwise it won’t be recognized.
  • The third argument is a request code value. This value can be any positive integer. Google Play returns this request code to the calling Activity’s onActivityResult along with the purchase response.
  • The fourth argument is a listener that is notified when the purchase operation has completed and handles the purchase response from Google Play.
  • The fifth argument contains a ‘developer payload’ string that you can use to send supplemental information about an order (it can be an empty string). Typically, this is used to pass in a string token that uniquely identifies this purchase request. If you specify a string value, Google Play returns this string along with the purchase response. Subsequently, when you make queries about this purchase, Google Play returns this string together with the purchase details.
    Security Recommendation: It’s good practice to pass in a string that helps your application to identify the user who made the purchase, so that you can later verify that this is a legitimate purchase by that user. For consumable items, you can use a randomly generated string, but for non-consumable items you should use a string that uniquely identifies the user.
  • 第一引数は呼び出し元のActivity
  • 第二引数は購入アイテムの商品ID(SKU). 商品名ではなく商品IDとすること.
    商品は事前にDeveloper Consoleで定義しておかないと商品として認識されない.
  • 第三引数はリクエストコード. この値は正の数となる.
    Google Playは購入リクエストの応答(ActivityonActivityResult)で, このリクエストコードを返す
  • 第四引数は購入操作が完了し, Google Playからの応答をハンドルするリスナー
  • 第五引数は任意のヘッダ文字列(‘developer payload’), 注文の付加情報として使用できる(空文字でもよい)
    通常, 購入リクエストを識別するためのユニークID(token)が使用される.
    Google Playの購入レスポンスには, ここで指定した文字列が一緒に渡される.
    続いて, この購入情報を問い合わせる時, Google Playは購入情報の詳細と一緒にこの文字列を返す.
    Security Recommendation:
    この方法は誰の購入情報かを識別するのに良い方法となる.
    これにより, 後から商品購入の妥当性をチェックできる. 消耗品にはランダムなtokenを使い回すだろうが,
    永続的な商品の場合はユニークIDを使用すべきである.

The following example shows how you can make a purchase request for a product with ID SKU_GAS, using an arbitrary value of 10001 for the request code, and an encoded developer payload string.

次の例は, 商品IDがSKU_GAS, 任意のリクエストコード(10001), エンコードしたdeveloper payload文字列を指定したの商品購入リクエストを使用する方法である.

mHelper.launchPurchaseFlow(this, SKU_GAS, 10001,   
   mPurchaseFinishedListener, "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");

If the purchase order is successful, the response data from Google Play is stored in an Purchase object that is passed back to the listener.

もし購入オーダが成功すれば, Google Playからの応答データはPurchaseオブジェクトに格納されてリスナーに通知される.

The following example shows how you can handle the purchase response in the listener, depending on whether the purchase order was completed successfully, and whether the user purchased gas or a premium upgrade. In this example, gas is an in-app product that can be purchased multiple times, so you should consume the purchase to allow the user to buy it again. To learn how to consume purchases, see the [Consuming Products][t1_3c] section. The premium upgrade is a one-time purchase so you don’t need to consume it. It is good practice to update the UI immediately so that your users can see their newly purchased items.

次はリスナーで購入レスポンスをどのようにして処理するかを例示する.
レスポンスから購入した商品がgasなのかプレミアムアップグレードなのかで処理を分けている.
サンプルコードで, gasは複数回購入可能な商品であり, 再度購入できるよう消費させている.
どうやって購入した商品を消費させるかはConsuming Productsセクションで述べる.
プレミアムアップグレードは一度だけ購入できるアイテムであるため消費させない.
ユーザが購入できたことを認識できるよう, すぐにUIを更新するのが良い方法である.

IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener 
   = new IabHelper.OnIabPurchaseFinishedListener() {
   public void onIabPurchaseFinished(IabResult result, Purchase purchase) 
   {
      if (result.isFailure()) {
         Log.d(TAG, "Error purchasing: " + result);
         return;
      }      
      else if (purchase.getSku().equals(SKU_GAS)) {
         // consume the gas and update the UI
      }
      else if (purchase.getSku().equals(SKU_PREMIUM)) {
         // give user access to premium content and update the UI
      }
   }
};

Security Recommendation: When you receive the purchase response from Google Play, make sure to check the returned data signature, the orderId, and the developerPayload string in the Purchase object to make sure that you are getting the expected values. You should 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. As a further security precaution, you should perform the verification on your own secure server.

Security Recommendation: Google Playから支払いの応答を受けたとき, 返却されたPurchaseのsignature, orderId, developerPayloadが期待する値かチェックする(Man in the middle attackの防止). orderIdが過去に処理していないユニークな値であるか, developerPayloadtokenが購入リクエスト時のものと一致するか. 更に厳重に信頼できる自前のセキュアサーバであることが望ましい.

Query Purchased Items

Upon a successful purchase, the user’s purchase data is cached locally by Google Play’s In-app Billing service. It is good practice to frequently query the In-app Billing service for the user’s purchases, for example whenever the app starts up or resumes, so that the user’s current in-app product ownership information is always reflected in your app.

購入が成功すると, そのデータはGoogle Playのアプリ内課金サービスにローカルキャッシュされる.
アプリの開始時, 再開時にユーザ購入履歴をアプリ内課金サービスに頻繁に問い合わせすることは, アプリ内商品の所有情報を常に最新に保つのによい方法となる.

To retrieve the user’s purchases from your app, call queryInventoryAsync(QueryInventoryFinishedListener) on your IabHelper instance. The QueryInventoryFinishedListener argument specifies a listener that is notified when the query operation has completed and handles the query response. It is safe to make this call fom your main thread.

アプリからユーザ購入情報を復元するために, IabHelperqueryInventoryAsync(QueryInventoryFinishedListener)が使用できる. 引数QueryInventoryFinishedListenerはクエリ完了時に結果通知を受け取るリスナを指定する.
このメソッドはメインスレッドから呼び出すことができる.

mHelper.queryInventoryAsync(mGotInventoryListener);

If the query is successful, the query results are stored in an Inventory object that is passed back to the listener. The In-app Billing service returns only the purchases made by the user account that is currently logged in to the device.

クエリが成功したとき, Inventoryオブジェクトに結果が格納されリスナーに通知される.
アプリ内課金サービスは現在端末でログインされているユーザアカウントの購入のみを返却する.

IabHelper.QueryInventoryFinishedListener mGotInventoryListener 
   = new IabHelper.QueryInventoryFinishedListener() {
   public void onQueryInventoryFinished(IabResult result,
      Inventory inventory) {

      if (result.isFailure()) {
        // handle error here
      }
      else {
        // does the user have the premium upgrade?
        mIsPremium = inventory.hasPurchase(SKU_PREMIUM);        
        // update UI accordingly
      }
   }
};

Consume a Purchase

You can use the In-app Billing Version 3 API to track the ownership of purchased items in Google Play. Once an item is purchased, it is considered to be “owned” and cannot be purchased again from Google Play while in that state. You must send a consumption request for the item before Google Play makes it available for purchase again. All managed in-app products are consumable. How you use the consumption mechanism in your app is up to you. Typically, you would implement consumption for products with temporary benefits that users may want to purchase multiple times (for example, in-game currency or replenishable game tokens). You would typically not want to implement consumption for products that are purchased once and provide a permanent effect (for example, a premium upgrade).

In-app Billing Ver.3 APIはユーザがGoogle Playで購入した商品の所有情報を追跡するために使える.
商品を購入すると”owned(所有中)”とみなされ, この状態ではGoogle Playで再購入できなくなる.
再購入できるようにするには商品の消費リクエストをGoogle Playに送信しなくてはならない(Purchase(購入)とConsume(消費)は対の概念).
アプリ内商品は全て消費可能であるが, 消費メカニズムをどう使うかはアプリ次第となる.
通常, 一時的に役立つような商品(アプリ内通貨や補給物資)には消費を実装すべきで,
永続的な効果を持つ商品の場合(プレミアムアップグレードなど)は一度限りの購入で完結し, 消費は実装しない.

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.

Security Recommendation:
商品の消費を反映する前に, 消費リクエストを送信すべきである.
商品を提供する前に消費成功の応答をGoogle Playから受け取るように.

To record a purchase consumption, call consumeAsync(Purchase, OnConsumeFinishedListener) on your IabHelper instance. The first argument that the method takes is the Purchase object representing the item to consume. The second argument is a OnConsumeFinishedListener that is notified when the consumption operation has completed and handles the consumption response from Google Play. It is safe to make this call fom your main thread.

購入消費を記録するにはIabHelperconsumeAsync(Purchase, OnConsumeFinishedListener)メソッドを呼ぶ.
第一引数は消費するアイテムのPurchaseオブジェクトを指定する. 第二引数は消費処理が完了しGoogle Playから応答の通知を受け取るOnConsumeFinishedListenerを指定する.
これはメインメソッドから呼び出せる.

In this example, you want to consume the gas item that the user has previously purchased in your app.

ユーザが購入した商品”gas”を消費するサンプル.

mHelper.consumeAsync(inventory.getPurchase(SKU_GAS), 
   mConsumeFinishedListener);

The following example shows how to implement the OnConsumeFinishedListener.

OnConsumeFinishedListenerの実装サンプルは次の通り.

IabHelper.OnConsumeFinishedListener mConsumeFinishedListener =
   new IabHelper.OnConsumeFinishedListener() {
   public void onConsumeFinished(Purchase purchase, IabResult result) {
      if (result.isSuccess()) {
         // provision the in-app purchase to the user
         // (for example, credit 50 gold coins to player's character)
      }
      else {
         // handle error
      }
   }
};

Check for Consumable Items on Startup

It’s important to check for consumable items when the user starts up your application. Typically, you would first query the In-app Billing service for the items purchased by the user (via queryInventoryAsync), then get the consumable Purchase objects from the Inventory. If your application detects that are any consumable items that are owned by the user, you should send a consumption request to Google Play immediately and provision the item to the user. See the TrivialDrive sample for an example of how to implement this checking at startup.

アプリ起動時に消耗品をチェックすること.
まず始めにユーザが購入済みの商品をアプリ内課金サービスへ問い合わせる(queryInventoryAsyncを経由して). そして, Inventoryから消費できるPurchaseオブジェクトを取得する.
もし消耗品をユーザが所有している場合, Google Playに消費リクエストを送り, ユーザに提供すること.
これらの実装はTriviaDriveサンプルの例が参考になる.


Testing Your In-app Billing Application

To ensure that In-app Billing is functioning correctly in your application, you should test the test the application before you publish it on Google Play. Early testing also helps to ensure that the user flow for purchasing in-app items is not confusing or slow, and that users can see their newly purchased items in a timely way.

Google Playで公開する前にアプリ内課金が正しく動作しているかテストすること.
事前のテストで商品の購入フローが紛らわしいものでないか, 手間でないかを確認する.
そして, ユーザが新たに購入した商品をタイムリーに確認できることもテストする.

Test with Static Responses

Test your In-app Billing application with static responses by using Google Play’s reserved product IDs. By using reserved product IDs instead of actual product IDs, you can test the purchase flow without specifying an actual payment method or transferring money. To learn more about the reserved product IDs, see Testing In-app Billing.

Google Playで予約された商品IDを使った静的な応答でアプリの課金処理をテストできる.
予約された商品IDは本来の商品IDの代わりとなる.
これにより, 実際にお金を払うことなく購入テストが可能となる.
予約された商品IDについての詳細はTesting In-app Billingを参照.

Test with Your Own Product IDs

Because Google Play does not allow you to use your developer account to directly purchase in-app products that you have created yourself, you’ll need to create test acccounts under your developer account profile. To create a test account, simply enter a valid Google email address. Users with these test accounts will then be able to make in-app-billing purchases from uploaded, unpublished applications that you manage.

Google Playは開発用アカウントで直接商品を購入することを許可していないので, 購入テスト用のアカウントを作成する必要がある.
テストアカウントを作成するために有効なGmailアドレスを登録する.
テストアカウントを持つと, アップロードされた非公開状態のアプリでアプリ内課金をテストできるようになる.

To test your In-app Billing Version 3 application using your own product IDs:

自前の商品IDを使用してIn-app Billing Ver.3を使用した課金アプリをテストするには.

  1. In the Developer Console, add one or more tester accounts to the developer account that you are using to publish your application.
    a. Login to the Developer Console with your developer account.
    b. Click Settings > Account details, then in the License Testing section, add the Google email addresses for your tester accounts.
  2. Build a signed APK file for your In-app Billing application. To learn how to build and sign your APK, see Building Your Application for Release. Make sure that you are using your final (not debug) certificate and private key to sign your application.
  3. Make sure that you have uploaded the signed APK for your application to the Developer Console, and associated one or more in-app products with your application. You don’t need to publish the application on Google Play to test it.
    Warning: It may take up to 2-3 hours after uploading the APK for Google Play to recognize your updated APK version. If you try to test your application before your uploaded APK is recognized by Google Play, your application will receive a ‘purchase cancelled’ response with an error message “This version of the application is not enabled for In-app Billing.”
  4. Install the APK file to your physical test device by using the adb tool. To learn how to install the application, see Running on a Device. Make sure that:
    • Your test device is running on Android SDK Version 2.2 (API level 8) or higher, and is installed with Google Play client Version 3.9.16 or higher.
    • The android:versionCode and android:versionName attributes values in the AndroidManifest.xml of the application that you are installing matches the values of your APK in the Developer Console.
    • Your application is signed with the same certificate that you used for the APK that you uploaded to the Developer Console, before installing it on your device.
  5. Login to the test device by using a tester account. Test your In-app Billing application by purchasing a few items, and fix any issues that you encounter. To learn more about how you can perform large-scale testing of your In-app Billing app, see Test Purchases (In-app Billing Sandbox).
  1. Developer Consoleで1つ以上の購入テスト用アカウントを開発用アカウントに追加し, アプリを共有する
    a. Developer Consoleに開発用アカウントでログイン
    b. Settings > Accountの詳細をクリック, License Testingセクションに購入テスト用のGmailアドレスを追加
  2. 署名された課金アプリのAPKを作成. APKの署名方法についてはBuilding Your Application for Releaseを参照.
  3. Developer Consoleに署名されたアプリをアップロードする. そして, 1つ以上の商品をアプリに関連付ける.
    テストの為にGoogle Playにアプリを公開する必要はない.
  4. adbツールでテスト端末にAPKをインストールする. APKのインストールについてはRunning on a Deviceを参照. 次のことを確認すること:
    • デバイスのSDK Ver.が2.2(API Level8)以上であり, Google Play Ver.3.9.16以上であること
    • インストール前後のAPK署名がDeveloper ConsoleにアップロードされたAPKのものと同じであること
  5. テストデバイス上で購入テスト用アカウントでログインし, 課金アプリでいくつかの商品を購入し,
    テストして見つけた不具合を修正する. In-app Billingアプリの大規模テストについてはTest Purchases (In-app Billing Sandbox)を参照.

License:
Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.