Home | History | Annotate | Download | only in billing
      1 page.title=Implementing In-app Billing
      2 parent.title=In-app Billing
      3 parent.link=index.html
      4 page.tags="inapp, billing, iap"
      5 @jd:body
      6 
      7 <div id="qv-wrapper">
      8 <div id="qv">
      9   <h2>In this document</h2>
     10   <ol>
     11     <li><a href="#billing-add-aidl">Adding the AIDL file</a></li>
     12     <li><a href="#billing-permission">Updating Your Manifest</a></li>
     13     <li><a href="#billing-service">Creating a ServiceConnection</a></li>
     14     <li><a href="#billing-requests">Making In-app Billing Requests</a>
     15        <ol>
     16        <li><a href="#QueryDetails">Querying Items Available for Purchase</a><li>
     17        <li><a href="#Purchase">Purchasing an Item</a></li>
     18        <li><a href="#QueryPurchases">Querying Purchased Items</a></li>
     19        <li><a href="#Consume">Consuming a Purchase</a></li>
     20        <li><a href="#Subs">Implementing Subscriptions</a></li>
     21        </ol>
     22     </li>
     23     <li><a href="#billing-security">Securing Your App</a>
     24   </ol>
     25   <h2>Reference</h2>
     26   <ol>
     27     <li><a href="{@docRoot}google/play/billing/billing_reference.html">In-app Billing
     28     Reference (V3)</a></li>
     29   </ol>
     30   <h2>Related Samples</h2>
     31   <ol>
     32     <li><a href="{@docRoot}training/in-app-billing/preparing-iab-app.html#GetSample">Sample Application (V3)</a></li>
     33   </ol>
     34   <h2>See also</h2>
     35   <ol>
     36     <li><a href="{@docRoot}training/in-app-billing/index.html">Selling In-app Products</a></li>
     37   </ol>
     38 </div>
     39 </div>
     40 
     41 <p>
     42   In-app Billing on Google Play provides a straightforward, simple interface
     43   for sending In-app Billing requests and managing In-app Billing transactions
     44   using Google Play. The information below covers the basics of how to make
     45   calls from your application to the In-app Billing service using the Version 3
     46   API.
     47 </p>
     48 
     49 <p class="note">
     50   <strong>Note:</strong> To see a complete implementation and learn how to test
     51   your application, see the <a href=
     52   "{@docRoot}training/in-app-billing/index.html">Selling In-app Products</a>
     53   training class. The training class provides a complete sample In-app Billing
     54   application, including convenience classes to handle key tasks related to
     55   setting up your connection, sending billing requests and processing responses
     56   from Google Play, and managing background threading so that you can make
     57   In-app Billing calls from your main activity.
     58 </p>
     59 
     60 <p>
     61   Before you start, be sure that you read the <a href=
     62   "{@docRoot}google/play/billing/billing_overview.html">In-app Billing
     63   Overview</a> to familiarize yourself with concepts that will make it easier
     64   for you to implement In-app Billing.
     65 </p>
     66 
     67 <p>To implement In-app Billing in your application, you need to do the
     68 following:</p>
     69 
     70 <ol>
     71   <li>Add the In-app Billing library to your project.</li>
     72   <li>Update your {@code AndroidManifest.xml} file.</li>
     73   <li>Create a {@code ServiceConnection} and bind it to
     74 {@code IInAppBillingService}.</li>
     75   <li>Send In-app Billing requests from your application to
     76 {@code IInAppBillingService}.</li>
     77   <li>Handle In-app Billing responses from Google Play.</li>
     78 </ol>
     79 
     80 <h2 id="billing-add-aidl">Adding the AIDL file to your project</h2>
     81 
     82 <p>{@code IInAppBillingService.aidl} is an Android Interface Definition
     83 Language (AIDL) file that defines the interface to the In-app Billing Version
     84 3 service. You will use this interface to make billing requests by invoking IPC
     85 method calls.</p>
     86 <p>To get the AIDL file:</p>
     87 <ol>
     88 <li>Open the <a href="{@docRoot}tools/help/sdk-manager.html">Android SDK Manager</a>.</li>
     89 <li>In the SDK Manager, expand the {@code Extras} section.</li>
     90 <li>Select <strong>Google Play Billing Library</strong>.</li>
     91 <li>Click <strong>Install packages</strong> to complete the download.</li>
     92 </ol>
     93 <p>The {@code IInAppBillingService.aidl} file will be installed to {@code &lt;sdk&gt;/extras/google/play_billing/}.</p>
     94 
     95 <p>To add the AIDL to your project:</p>
     96 
     97 <ol>
     98   <li>First, download the Google Play Billing Library to your Android project:
     99       <ol type="a">
    100       <li>Select <strong>Tools > Android > SDK Manager</strong>.</li>
    101       <li>Under <strong>Appearance & Behavior > System Settings > Android SDK</strong>,
    102           select the <em>SDK Tools</em> tab to select and download <em>Google Play Billing
    103           Library</em>.</li></ol>
    104 
    105   <li>Next, copy the {@code IInAppBillingService.aidl} file to your project.
    106     <ul>
    107       <li>If you are using Android Studio:
    108         <ol type="a">
    109           <li>Navigate to {@code src/main} in the Project tool window.</li>
    110 
    111           <li>Select <strong>File > New > Directory</strong> and enter {@code aidl} in the
    112           <em>New Directory</em> window, then select <strong>OK</strong>.
    113 
    114           <li>Select <strong>File > New > Package</strong> and enter
    115           {@code com.android.vending.billing} in the <em>New Package</em> window, then select
    116           <strong>OK</strong>.</li>
    117 
    118           <li>Using your operating system file explorer, navigate to
    119           {@code &lt;sdk&gt;/extras/google/play_billing/}, copy the
    120           {@code IInAppBillingService.aidl} file, and paste it into the
    121           {@code com.android.vending.billing} package in your project.
    122           </li>
    123         </ol>
    124       </li>
    125 
    126       <li>If you are developing in a non-Android Studio environment: Create the
    127       following directory {@code /src/com/android/vending/billing} and copy the
    128       {@code IInAppBillingService.aidl} file into this directory. Put the AIDL
    129       file into your project and use the Gradle tool to build your project so that
    130       the <code>IInAppBillingService.java</code> file gets generated.
    131       </li>
    132     </ul>
    133   </li>
    134 
    135   <li>Build your application. You should see a generated file named {@code
    136   IInAppBillingService.java} in the {@code /gen} directory of your project.
    137   </li>
    138 </ol>
    139 
    140 <h2 id="billing-permission">Updating Your App's Manifest</h2>
    141 
    142 <p>
    143   In-app billing relies on the Google Play application, which handles all
    144   communication between your application and the Google Play server. To use the
    145   Google Play application, your application must request the proper permission.
    146   You can do this by adding the {@code com.android.vending.BILLING} permission
    147   to your AndroidManifest.xml file. If your application does not declare the
    148   In-app Billing permission, but attempts to send billing requests, Google Play
    149   will refuse the requests and respond with an error.
    150 </p>
    151 
    152 <p>
    153   To give your app the necessary permission, add this line in the {@code
    154   AndroidManifest.xml} file:
    155 </p>
    156 
    157 <pre>
    158 &lt;uses-permission android:name="com.android.vending.BILLING" /&gt;
    159 </pre>
    160 
    161 <h2 id="billing-service">Creating a ServiceConnection</h2>
    162 
    163 <p>
    164   Your application must have a {@link android.content.ServiceConnection} to
    165   facilitate messaging between your application and Google Play. At a minimum,
    166   your application must do the following:
    167 </p>
    168 
    169 <ul>
    170   <li>Bind to {@code IInAppBillingService}.
    171   <li>Send billing requests (as IPC method calls) to the Google Play application.</li>
    172   <li>Handle the synchronous response messages that are returned with each billing request.</li>
    173 </ul>
    174 
    175 <h3>Binding to IInAppBillingService</h3>
    176 
    177 <p>
    178   To establish a connection with the In-app Billing service on Google Play,
    179   implement a {@link android.content.ServiceConnection} to bind your activity
    180   to {@code IInAppBillingService}. Override the {@link
    181   android.content.ServiceConnection#onServiceDisconnected
    182   onServiceDisconnected} and {@link
    183   android.content.ServiceConnection#onServiceConnected onServiceConnected}
    184   methods to get a reference to the {@code IInAppBillingService} instance after
    185   a connection has been established.
    186 </p>
    187 
    188 <pre>
    189 IInAppBillingService mService;
    190 
    191 ServiceConnection mServiceConn = new ServiceConnection() {
    192    &#64;Override
    193    public void onServiceDisconnected(ComponentName name) {
    194        mService = null;
    195    }
    196 
    197    &#64;Override
    198    public void onServiceConnected(ComponentName name,
    199       IBinder service) {
    200        mService = IInAppBillingService.Stub.asInterface(service);
    201    }
    202 };
    203 </pre>
    204 
    205 <p>
    206   In your activitys {@link android.app.Activity#onCreate onCreate} method,
    207   perform the binding by calling the {@link android.content.Context#bindService
    208   bindService} method. Pass the method an {@link android.content.Intent} that
    209   references the In-app Billing service and an instance of the {@link
    210   android.content.ServiceConnection} that you created, and explicitly set the
    211   Intent's target package name to <code>com.android.vending</code>  the
    212   package name of Google Play app.
    213 </p>
    214 
    215 <p class="caution">
    216   <strong>Caution:</strong> To protect the security of billing transactions,
    217   always make sure to explicitly set the intent's target package name to
    218   <code>com.android.vending</code>, using {@link
    219   android.content.Intent#setPackage(java.lang.String) setPackage()} as shown in
    220   the example below. Setting the package name explicitly ensures that
    221   <em>only</em> the Google Play app can handle billing requests from your app,
    222   preventing other apps from intercepting those requests.
    223 </p>
    224 
    225 <pre>&#64;Override
    226 public void onCreate(Bundle savedInstanceState) {
    227   super.onCreate(savedInstanceState);
    228   setContentView(R.layout.activity_main);
    229   Intent serviceIntent =
    230       new Intent("com.android.vending.billing.InAppBillingService.BIND");
    231   serviceIntent.setPackage("com.android.vending");
    232   bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
    233 }
    234 </pre>
    235 
    236 <p>
    237   You can now use the mService reference to communicate with the Google Play
    238   service.
    239 </p>
    240 
    241 <p class="note">
    242   <strong>Important:</strong> Remember to unbind from the In-app Billing
    243   service when you are done with your {@link android.app.Activity}. If you
    244   dont unbind, the open service connection could cause your devices
    245   performance to degrade. This example shows how to perform the unbind
    246   operation on a service connection to In-app Billing called {@code
    247   mServiceConn} by overriding the activitys {@link
    248   android.app.Activity#onDestroy onDestroy} method.
    249 </p>
    250 
    251 <pre>
    252 &#64;Override
    253 public void onDestroy() {
    254     super.onDestroy();
    255     if (mService != null) {
    256         unbindService(mServiceConn);
    257     }
    258 }
    259 </pre>
    260 
    261 <p>
    262   For a complete implementation of a service connection that binds to the
    263   {@code IInAppBillingService}, see the <a href=
    264   "{@docRoot}training/in-app-billing/preparing-iab-app.html">Selling In-app
    265   Products</a> training class and associated sample.
    266 </p>
    267 <h2 id="billing-requests">Making In-app Billing Requests</h2>
    268 <p>
    269   Once your application is connected to Google Play, you can initiate purchase
    270   requests for in-app products. Google Play provides a checkout interface for
    271   users to enter their payment method, so your application does not need to
    272   handle payment transactions directly. When an item is purchased, Google Play
    273   recognizes that the user has ownership of that item and prevents the user
    274   from purchasing another item with the same product ID until it is consumed.
    275   You can control how the item is consumed in your application, and notify
    276   Google Play to make the item available for purchase again. You can also query
    277   Google Play to quickly retrieve the list of purchases that were made by the
    278   user. This is useful, for example, when you want to restore the user's
    279   purchases when your user launches your app.
    280 </p>
    281 
    282 <h3 id="QueryDetails">Querying for Items Available for Purchase</h3>
    283 
    284 <p>
    285   In your application, you can query the item details from Google Play using
    286   the In-app Billing Version 3 API. To pass a request to the In-app Billing
    287   service, first create a {@link android.os.Bundle} that contains a String
    288   {@link java.util.ArrayList} of product IDs with key "ITEM_ID_LIST", where
    289   each string is a product ID for an purchasable item.
    290 </p>
    291 
    292 <pre>
    293 ArrayList&lt;String&gt; skuList = new ArrayList&lt;String&gt; ();
    294 skuList.add("premiumUpgrade");
    295 skuList.add("gas");
    296 Bundle querySkus = new Bundle();
    297 querySkus.putStringArrayList(ITEM_ID_LIST, skuList);
    298 </pre>
    299 
    300 <p>
    301   To retrieve this information from Google Play, call the {@code getSkuDetails}
    302   method on the In-app Billing Version 3 API, and pass the method the In-app
    303   Billing API version (3), the package name of your calling app, the purchase
    304   type (inapp), and the {@link android.os.Bundle} that you created.
    305 </p>
    306 
    307 <pre>
    308 Bundle skuDetails = mService.getSkuDetails(3,
    309    getPackageName(), "inapp", querySkus);
    310 </pre>
    311 
    312 <p>
    313   If the request is successful, the returned {@link android.os.Bundle}has a
    314   response code of {@code BILLING_RESPONSE_RESULT_OK} (0).
    315 </p>
    316 
    317 <p class="note">
    318   <strong>Warning:</strong> Do not call the {@code getSkuDetails} method on the
    319   main thread. Calling this method triggers a network request which could block
    320   your main thread. Instead, create a separate thread and call the {@code
    321   getSkuDetails} method from inside that thread.
    322 </p>
    323 
    324 <p>
    325   To see all the possible response codes from Google Play, see <a href=
    326   "{@docRoot}google/play/billing/billing_reference.html#billing-codes">In-app
    327   Billing Reference</a>.
    328 </p>
    329 
    330 <p>
    331   The query results are stored in a String ArrayList with key {@code
    332   DETAILS_LIST}. The purchase information is stored in the String in JSON
    333   format. To see the types of product detail information that are returned, see
    334   <a href=
    335   "{@docRoot}google/play/billing/billing_reference.html#getSkuDetails">In-app
    336   Billing Reference</a>.
    337 </p>
    338 
    339 <p>
    340   In this example, you are retrieving the prices for your in-app items from the
    341   skuDetails {@link android.os.Bundle} returned from the previous code snippet.
    342 </p>
    343 
    344 <pre>
    345 int response = skuDetails.getInt("RESPONSE_CODE");
    346 if (response == 0) {
    347    ArrayList&lt;String&gt; responseList
    348       = skuDetails.getStringArrayList("DETAILS_LIST");
    349 
    350    for (String thisResponse : responseList) {
    351       JSONObject object = new JSONObject(thisResponse);
    352       String sku = object.getString("productId");
    353       String price = object.getString("price");
    354       if (sku.equals("premiumUpgrade")) mPremiumUpgradePrice = price;
    355       else if (sku.equals("gas")) mGasPrice = price;
    356    }
    357 }
    358 </pre>
    359 
    360 <h3 id="Purchase">Purchasing an Item</h3>
    361 <p>
    362   To start a purchase request from your app, call the {@code getBuyIntent}
    363   method on the In-app Billing service. Pass in to the method the In-app
    364   Billing API version (3), the package name of your calling app, the product
    365   ID for the item to purchase, the purchase type (inapp or "subs"), and a
    366   {@code developerPayload} String. The {@code developerPayload} String is used
    367   to specify any additional arguments that you want Google Play to send back
    368   along with the purchase information.
    369 </p>
    370 
    371 <pre>
    372 Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(),
    373    sku, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");
    374 </pre>
    375 
    376 <p>
    377   If the request is successful, the returned {@link android.os.Bundle} has a
    378   response code of {@code BILLING_RESPONSE_RESULT_OK} (0) and a {@link
    379   android.app.PendingIntent} that you can use to start the purchase flow. To
    380   see all the possible response codes from Google Play, see <a href=
    381   "{@docRoot}google/play/billing/billing_reference.html#billing-codes">In-app
    382   Billing Reference</a>. Next, extract a {@link android.app.PendingIntent} from
    383   the response {@link android.os.Bundle} with key {@code BUY_INTENT}.
    384 </p>
    385 
    386 <pre>
    387 PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
    388 </pre>
    389 
    390 <p>
    391   To complete the purchase transaction, call the {@link
    392   android.app.Activity#startIntentSenderForResult startIntentSenderForResult}
    393   method and use the {@link android.app.PendingIntent} that you created. In
    394   this example, you are using an arbitrary value of 1001 for the request code.
    395 </p>
    396 
    397 <pre>
    398 startIntentSenderForResult(pendingIntent.getIntentSender(),
    399    1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0),
    400    Integer.valueOf(0));
    401 </pre>
    402 
    403 <p>
    404   Google Play sends a response to your {@link android.app.PendingIntent} to the
    405   {@link android.app.Activity#onActivityResult onActivityResult} method of your
    406   application. The {@link android.app.Activity#onActivityResult
    407   onActivityResult} method will have a result code of {@code
    408   Activity.RESULT_OK} (1) or {@code Activity.RESULT_CANCELED} (0). To see the
    409   types of order information that is returned in the response {@link
    410   android.content.Intent}, see <a href=
    411   "{@docRoot}google/play/billing/billing_reference.html#getBuyIntent">In-app
    412   Billing Reference</a>.
    413 </p>
    414 
    415 <p>
    416   The purchase data for the order is a String in JSON format that is mapped to
    417   the {@code INAPP_PURCHASE_DATA} key in the response {@link
    418   android.content.Intent}, for example:
    419 </p>
    420 
    421 <pre>
    422 '{
    423    "orderId":"GPA.1234-5678-9012-34567",
    424    "packageName":"com.example.app",
    425    "productId":"exampleSku",
    426    "purchaseTime":1345678900000,
    427    "purchaseState":0,
    428    "developerPayload":"bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ",
    429    "purchaseToken":<em>"opaque-token-up-to-1000-characters"</em>
    430  }'
    431 </pre>
    432 
    433 <p class="note">
    434   <strong>Note:</strong> Google Play generates a token for the purchase. This
    435   token is an opaque character sequence that may be up to 1,000 characters
    436   long. Pass this entire token to other methods, such as when you consume the
    437   purchase, as described in <a href=
    438   "{@docRoot}training/in-app-billing/purchase-iab-products.html#Consume">Consume
    439   a Purchase</a>. Do not abbreviate or truncate this token; you must save and
    440   return the entire token.
    441 </p>
    442 
    443 <p>
    444   Continuing from the previous example, you get the response code, purchase
    445   data, and signature from the response {@link android.content.Intent}.
    446 </p>
    447 
    448 <pre>
    449 &#64;Override
    450 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    451    if (requestCode == 1001) {
    452       int responseCode = data.getIntExtra("RESPONSE_CODE", 0);
    453       String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
    454       String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");
    455 
    456       if (resultCode == RESULT_OK) {
    457          try {
    458             JSONObject jo = new JSONObject(purchaseData);
    459             String sku = jo.getString("productId");
    460             alert("You have bought the " + sku + ". Excellent choice,
    461                adventurer!");
    462           }
    463           catch (JSONException e) {
    464              alert("Failed to parse purchase data.");
    465              e.printStackTrace();
    466           }
    467       }
    468    }
    469 }
    470 </pre>
    471 
    472 <p class="note">
    473   <strong>Security Recommendation:</strong> When you send a purchase request,
    474   create a String token that uniquely identifies this purchase request and
    475   include this token in the {@code developerPayload}.You can use a randomly
    476   generated string as the token. When you receive the purchase response from
    477   Google Play, make sure to check the returned data signature, the {@code
    478   orderId}, and the {@code developerPayload} String. For added security, you
    479   should perform the checking on your own secure server. Make sure to verify
    480   that the {@code orderId} is a unique value that you have not previously
    481   processed, and the {@code developerPayload} String matches the token that you
    482   sent previously with the purchase request.
    483 </p>
    484 
    485 <h3 id="QueryPurchases">Querying for Purchased Items</h3>
    486 
    487 <p>
    488   To retrieve information about purchases made by a user from your app, call
    489   the {@code getPurchases} method on the In-app Billing Version 3 service. Pass
    490   in to the method the In-app Billing API version (3), the package name of
    491   your calling app, and the purchase type (inapp or "subs").
    492 </p>
    493 
    494 <pre>
    495 Bundle ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);
    496 </pre>
    497 
    498 <p>
    499   The Google Play service returns only the purchases made by the user account
    500   that is currently logged in to the device. If the request is successful, the
    501   returned {@link android.os.Bundle} has a response code of 0. The response
    502   {@link android.os.Bundle} also contains a list of the product IDs, a list of
    503   the order details for each purchase, and the signatures for each purchase.
    504 </p>
    505 
    506 <p>
    507   To improve performance, the In-app Billing service returns only up to 700
    508   products that are owned by the user when {@code getPurchase} is first called.
    509   If the user owns a large number of products, Google Play includes a String
    510   token mapped to the key {@code INAPP_CONTINUATION_TOKEN} in the response
    511   {@link android.os.Bundle} to indicate that more products can be retrieved.
    512   Your application can then make a subsequent {@code getPurchases} call, and
    513   pass in this token as an argument. Google Play continues to return a
    514   continuation token in the response {@link android.os.Bundle} until all
    515   products that are owned by the user has been sent to your app.
    516 </p>
    517 
    518 <p>For more information about the data returned by {@code getPurchases}, see
    519   <a href="{@docRoot}google/play/billing/billing_reference.html#getPurchases">
    520   In-app Billing Reference</a>. The following example shows how you can
    521   retrieve this data from the response.
    522 </p>
    523 
    524 <pre>
    525 int response = ownedItems.getInt("RESPONSE_CODE");
    526 if (response == 0) {
    527    ArrayList&lt;String&gt; ownedSkus =
    528       ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
    529    ArrayList&lt;String&gt;  purchaseDataList =
    530       ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
    531    ArrayList&lt;String&gt;  signatureList =
    532       ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE_LIST");
    533    String continuationToken =
    534       ownedItems.getString("INAPP_CONTINUATION_TOKEN");
    535 
    536    for (int i = 0; i &lt; purchaseDataList.size(); ++i) {
    537       String purchaseData = purchaseDataList.get(i);
    538       String signature = signatureList.get(i);
    539       String sku = ownedSkus.get(i);
    540 
    541       // do something with this purchase information
    542       // e.g. display the updated list of products owned by user
    543    }
    544 
    545    // if continuationToken != null, call getPurchases again
    546    // and pass in the token to retrieve more items
    547 }
    548 </pre>
    549 
    550 
    551 <h3 id="Consume">Consuming a Purchase</h3>
    552 
    553 <p>
    554   You can use the In-app Billing Version 3 API to track the ownership of
    555   purchased in-app products in Google Play. Once an in-app product is
    556   purchased, it is considered to be "owned" and cannot be purchased from Google
    557   Play. You must send a consumption request for the in-app product before
    558   Google Play makes it available for purchase again.
    559 </p>
    560 
    561 <p class="caution">
    562   <strong>Important</strong>: Managed in-app products are consumable, but
    563   subscriptions are not.
    564 </p>
    565 
    566 <p>
    567   How you use the consumption mechanism in your app is up to you. Typically,
    568   you would implement consumption for in-app products with temporary benefits
    569   that users may want to purchase multiple times (for example, in-game currency
    570   or equipment). You would typically not want to implement consumption for
    571   in-app products that are purchased once and provide a permanent effect (for
    572   example, a premium upgrade).
    573 </p>
    574 
    575 <p>
    576   To record a purchase consumption, send the {@code consumePurchase} method to
    577   the In-app Billing service and pass in the {@code purchaseToken} String value
    578   that identifies the purchase to be removed. The {@code purchaseToken} is part
    579   of the data returned in the {@code INAPP_PURCHASE_DATA} String by the Google
    580   Play service following a successful purchase request. In this example, you
    581   are recording the consumption of a product that is identified with the {@code
    582   purchaseToken} in the {@code token} variable.
    583 </p>
    584 
    585 <pre>
    586 int response = mService.consumePurchase(3, getPackageName(), token);
    587 </pre>
    588 
    589 <p class="note">
    590   <strong>Warning:</strong> Do not call the {@code consumePurchase} method on
    591   the main thread. Calling this method triggers a network request which could
    592   block your main thread. Instead, create a separate thread and call the {@code
    593   consumePurchase} method from inside that thread.
    594 </p>
    595 
    596 <p>
    597   It's your responsibility to control and track how the in-app product is
    598   provisioned to the user. For example, if the user purchased in-game currency,
    599   you should update the player's inventory with the amount of currency
    600   purchased.
    601 </p>
    602 
    603 <p class="note">
    604   <strong>Security Recommendation:</strong> You must send a consumption request
    605   before provisioning the benefit of the consumable in-app purchase to the
    606   user. Make sure that you have received a successful consumption response from
    607   Google Play before you provision the item.
    608 </p>
    609 
    610 <h3 id="Subs">Implementing Subscriptions</h3>
    611 
    612 <p>Launching a purchase flow for a subscription is similar to launching the
    613 purchase flow for a product, with the exception that the product type must be set
    614 to "subs". The purchase result is delivered to your Activity's
    615 {@link android.app.Activity#onActivityResult onActivityResult} method, exactly
    616 as in the case of in-app products.</p>
    617 
    618 <pre>
    619 Bundle bundle = mService.getBuyIntent(3, "com.example.myapp",
    620    MY_SKU, "subs", developerPayload);
    621 
    622 PendingIntent pendingIntent = bundle.getParcelable(RESPONSE_BUY_INTENT);
    623 if (bundle.getInt(RESPONSE_CODE) == BILLING_RESPONSE_RESULT_OK) {
    624    // Start purchase flow (this brings up the Google Play UI).
    625    // Result will be delivered through onActivityResult().
    626    startIntentSenderForResult(pendingIntent, RC_BUY, new Intent(),
    627        Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
    628 }
    629 </pre>
    630 
    631 <p>To query for active subscriptions, use the {@code getPurchases} method, again
    632 with the product type parameter set to "subs".</p>
    633 
    634 <pre>
    635 Bundle activeSubs = mService.getPurchases(3, "com.example.myapp",
    636                    "subs", continueToken);
    637 </pre>
    638 
    639 <p>The call returns a {@code Bundle} with all the active subscriptions owned by
    640 the user. Once a subscription expires without renewal, it will no longer appear
    641 in the returned {@code Bundle}.</p>
    642 
    643 <h2 id="billing-security">Securing Your Application</h2>
    644 
    645 <p>To help ensure the integrity of the transaction information that is sent to
    646 your application, Google Play signs the JSON string that contains the response
    647 data for a purchase order. Google Play uses the private key that is associated
    648 with your application in the Developer Console to create this signature. The
    649 Developer Console generates an RSA key pair for each application.<p>
    650 
    651 <p class="note"><strong>Note:</strong>To find the public key portion of this key
    652 pair, open your application's details in the Developer Console, then click on
    653 <strong>Services &amp; APIs</strong>, and look at the field titled
    654 <strong>Your License Key for This Application</strong>.</p>
    655 
    656 <p>The Base64-encoded RSA public key generated by Google Play is in binary
    657 encoded, X.509 subjectPublicKeyInfo DER SEQUENCE format. It is the same public
    658 key that is used with Google Play licensing.</p>
    659 
    660 <p>When your application receives this signed response you can
    661 use the public key portion of your RSA key pair to verify the signature.
    662 By performing signature verification you can detect responses that have
    663 been tampered with or that have been spoofed. You can perform this signature
    664 verification step in your application; however, if your application connects
    665 to a secure remote server then we recommend that you perform the signature
    666 verification on that server.</p>
    667 
    668 <p>For more information about best practices for security and design, see <a
    669 href="{@docRoot}google/play/billing/billing_best_practices.html">Security and
    670 Design</a>.</p>
    671