1page.title=Implementing In-app Billing <span style="font-size:16px;">(IAB Version 2)</span> 2excludeFromSuggestions=true 3@jd:body 4 5<p class="caution" style= 6"background-color:#fffdeb;width:100%;margin-bottom:1em;padding:.5em;"> 7 The <strong>In-app Billing Version 2 API</strong> has been deprecated in 8 favor of the Version 3 API. If your app is using In-app Billing, please 9 <strong>make sure that it is using the Version 3 API</strong>. If your app is 10 still using the Version 2 API, you must <strong>migrate to the Version 3 API 11 as soon as possible</strong>.<br> 12 <br> 13 We plan to turn off the In-app Billing Version 2 service on <strong>January 14 27, 2015</strong>, after which time users will <strong>no longer be able to 15 purchase in-app items and subscriptions through the Version 2 API</strong>. 16 We strongly encourage and recommend you migrate your apps to use Version 3 17 API by November 2014, to provide ample time for users to update their apps to 18 the new version.<br> 19 <br> 20 For more information, please see the <a href= 21 "http://support.google.com/googleplay/android-developer/answer/6090268">Help Center 22 article</a>. For common questions about transitioning your implementation to 23 In-app Billing Version 3, please see <a href= 24 "{@docRoot}google/play/billing/billing_overview.html#migration">Migration 25 Considerations</a>. 26</p> 27 <div id="qv-wrapper" style="margin-top:0;"> 28<div id="qv"> 29 <h2>In this document</h2> 30 <ol> 31 <li><a href="#billing-download">Downloading the Sample</a></li> 32 <li><a href="#billing-add-aidl">Adding the AIDL file to your project</a></li> 33 <li><a href="#billing-permission">Updating Your Manifest</a></li> 34 <li><a href="#billing-service">Creating a Service</a></li> 35 <li><a href="#billing-broadcast-receiver">Creating a BroadcastReceiver</a></li> 36 <li><a href="#billing-security">Securing Your App</a></li> 37 <li><a href="#billing-implement">Modifying Your Application Code</a></li> 38 </ol> 39 <h2>Downloads</h2> 40 <ol> 41 <li><a href="#billing-download">Sample Application (V2)</a></li> 42 </ol> 43</div> 44</div> 45 46<p>This document helps you implement In-app Billing Version 2 by stepping through the primary 47implementation tasks, using the sample application as an example.</p> 48 49<p>Before you implement in-app billing in your own application, be sure that you read <a 50href="{@docRoot}google/play/billing/v2/api.html">Overview of In-app Billing Version 2</a> and <a 51href="{@docRoot}google/play/billing/billing_best_practices.html">Security and Design</a>. These 52documents provide background information that will make it easier for you to implement in-app 53billing.</p> 54 55<p>To implement in-app billing in your application, you need to do the following:</p> 56<ol> 57 <li><a href="#billing-download">Download the in-app billing sample application</a>.</li> 58 <li><a href="#billing-add-aidl">Add the IMarketBillingService.aidl file</a> to your project.</li> 59 <li><a href="#billing-permission">Update your AndroidManifest.xml file</a>.</li> 60 <li><a href="#billing-service">Create a Service</a> and bind it to the 61 <code>MarketBillingService</code> so your application can send billing requests and receive 62 billing responses from Google Play.</li> 63 <li><a href="#billing-broadcast-receiver">Create a BroadcastReceiver</a> to handle broadcast 64 intents from Google Play.</li> 65 <li><a href="#billing-signatures">Create a security processing component</a> to verify the 66 integrity of the transaction messages that are sent by Google Play.</li> 67 <li><a href="#billing-implement">Modify your application code</a> to support in-app billing.</li> 68</ol> 69 70<h2 id="billing-download">Downloading the Sample Application</h2> 71 72<p>The in-app billing sample application shows you how to perform several tasks that are common to 73all in-app billing implementations, including:</p> 74 75<ul> 76 <li>Sending in-app billing requests to Google Play.</li> 77 <li>Handling synchronous responses from Google Play.</li> 78 <li>Handling broadcast intents (asynchronous responses) from Google Play.</li> 79 <li>Using in-app billing security mechanisms to verify the integrity of billing responses.</li> 80 <li>Creating a user interface that lets users select items for purchase.</li> 81</ul> 82 83<p>The sample application includes an application file (<code>Dungeons.java</code>), the AIDL file 84for the <code>MarketBillingService</code> (<code>IMarketBillingService.aidl</code>), and several 85classes that demonstrate in-app billing messaging. It also includes a class that demonstrates basic 86security tasks, such as signature verification.</p> 87 88<p>Table 1 lists the source files that are included with the sample application.</p> 89<p class="table-caption" id="source-files-table"><strong>Table 1.</strong> In-app billing sample 90application source files.</p> 91 92<table> 93<tr> 94<th>File</th> 95<th>Description</th> 96</tr> 97 98<tr> 99<td>IMarketBillingService.aidl</td> 100<td>Android Interface Definition Library (AIDL) file that defines the IPC interface to Google 101Play's in-app billing service (<code>MarketBillingService</code>).</td> 102</tr> 103 104<tr> 105<td>Dungeons.java</td> 106<td>Sample application file that provides a UI for making purchases and displaying purchase 107history.</td> 108</tr> 109 110<tr> 111<td>PurchaseDatabase.java</td> 112<td>A local database for storing purchase information.</td> 113</tr> 114 115<tr> 116 <td>BillingReceiver.java</td> 117 <td>A {@link android.content.BroadcastReceiver} that receives asynchronous response messages 118 (broadcast intents) from Google Play. Forwards all messages to the 119 <code>BillingService</code>.</td> 120</tr> 121<tr> 122 <td>BillingService.java</td> 123 <td>A {@link android.app.Service} that sends messages to Google Play on behalf of the 124 application by connecting (binding) to the <code>MarketBillingService</code>.</td> 125</tr> 126 127<tr> 128 <td>ResponseHandler.java</td> 129 <td>A {@link android.os.Handler} that contains methods for updating the purchases database and the 130 UI.</td> 131</tr> 132 133<tr> 134 <td>PurchaseObserver.java</td> 135 <td>An abstract class for observing changes related to purchases.</td> 136</tr> 137 138<tr> 139<td>Security.java</td> 140<td>Provides various security-related methods.</td> 141</tr> 142 143<tr> 144<td>Consts.java</td> 145<td>Defines various Google Play constants and sample application constants. All constants that 146are defined by Google Play must be defined the same way in your application.</td> 147</tr> 148 149<tr> 150<td>Base64.java and Base64DecoderException.java</td> 151<td>Provides conversion services from binary to Base64 encoding. The <code>Security</code> class 152relies on these utility classes.</td> 153</tr> 154 155</table> 156 157<p>The in-app billing sample application is available as a downloadable component of the Android 158SDK. To download the sample application component, launch the Android SDK Manager and then 159select the <strong>Google Market Billing package</strong> component (see figure 1), and click <strong>Install 160Selected</strong> to begin the download.</p> 161 162 163<img src="{@docRoot}images/billing_package.png" height="325" id="figure1" /> 164<p class="img-caption"> 165 <strong>Figure 1.</strong> The Google Market Billing package contains the sample application and 166 the AIDL file. 167</p> 168 169<p>When the download is complete, the Android SDK Manager saves the component into the 170following directory:</p> 171 172<p><code><sdk>/extras/google/market_billing/</code></p> 173 174<p>If you want to see an end-to-end demonstration of in-app billing before you integrate in-app 175billing into your own application, you can build and run the sample application. Building and 176running the sample application involves three tasks:</p> 177 178<ul> 179 <li>Configuring and building the sample application.</li> 180 <li>Uploading the sample application to Google Play.</li> 181 <li>Setting up test accounts and running the sample application.</li> 182</ul> 183 184<p class="note"><strong>Note:</strong> Building and running the sample application is necessary only 185if you want to see a demonstration of in-app billing. If you do not want to run the sample 186application, you can skip to the next section, <a href="#billing-add-aidl">Adding the AIDL file to 187your project</a>.</p> 188 189<h3>Configuring and building the sample application</h3> 190 191<p>Before you can run the sample application, you need to configure it and build it by doing the 192following:</p> 193 194<ol> 195 <li><strong>Add your app's public key to the sample application code.</strong> 196 <p>This enables the application to verify the signature of the transaction information that is 197 returned from Google Play. To add your public key to the sample application code, do the 198 following:</p> 199 <ol> 200 <li>Log in to your Google Play <a href="http://play.google.com/apps/publish">Developer 201 console</a>.</li> 202 <li>On the upper left part of the page, All Applications, click the application name.</strong>.</li> 203 <li>On the Edit Profile page, scroll down to the <strong>Licensing & In-app 204 Billing</strong> panel.</li> 205 <li>Copy your public key.</li> 206 <li>Open <code>src/com/example/dungeons/Security.java</code> in the editor of your choice. 207 <p>You can find this file in the sample application's project folder.</p> 208 </li> 209 <li>Add your public key to the following line of code: 210 <p><code>String base64EncodedPublicKey = "your public key here";</code></p> 211 </li> 212 <li>Save the file.</li> 213 </ol> 214 </li> 215 <li><strong>Change the package name of the sample application.</strong> 216 <p>The current package name is <code>com.example.dungeons</code>. Google Play does not let 217 you upload applications with package names that contain <code>com.example</code>, so you must 218 change the package name to something else.</p> 219 </li> 220 <li><strong>Build the sample application in release mode and sign it.</strong> 221 <p>To learn how to build and sign applications, see <a 222 href="{@docRoot}tools/building/index.html">Building and Running</a>.</p> 223 </li> 224</ol> 225 226<h3>Uploading the sample application</h3> 227 228<p>After you build a release version of the sample application and sign it, you need to upload it as 229a draft to the Google Play Developer Console. You also need to create a product list for the in-app 230items that are available for purchase in the sample application. The following instructions show you 231how to do this.</p> 232 233<p class="caution"><strong>Caution:</strong> Draft applications are no longer 234supported. To test an application, publish it in the <a 235href="{@docRoot}distribute/googleplay/developer-console.html#alpha-beta">alpha 236or beta channels</a>. For more information, see <a 237href="{@docRoot}google/play/billing/billing_testing.html#draft_apps">Draft Apps 238are No Longer Supported</a>.</p> 239 240<ol> 241 <li><strong>Upload the release version of the sample application to Google Play.</strong> 242 <p>Do not publish the sample application; leave it as an unpublished draft application. The 243 sample application is for demonstration purposes only and should not be made publicly available 244 on Google Play. To learn how to upload an application to Google Play, see <a 245 href="http://support.google.com/googleplay/android-developer/bin/answer.py?hl=en&answer=113469">Uploading 246 applications</a>.</p> 247 </li> 248 <li><strong>Create a product list for the sample application.</strong> 249 <p>The sample application lets you purchase two items: a two-handed sword 250 (<code>sword_001</code>) and a potion (<code>potion_001</code>). We recommend that you set up 251 your product list so that <code>sword_001</code> has a purchase type of "Managed per user 252 account" and <code>potion_001</code> has a purchase type of "Unmanaged" so you can see how these 253 two purchase types behave. To learn how to set up a product list, see <a 254 href="{@docRoot}google/play/billing/billing_admin.html#billing-list-setup">Creating a Product 255 List</a>.</p> 256 <p class="note"><strong>Note:</strong> You must publish the items in your product 257 list (<code>sword_001</code> and <code>potion_001</code>) even though you are not publishing the 258 sample application. Also, you must have a Google payments merchant account to add items to the 259 sample application's product list.</p> 260 </li> 261</ol> 262 263<h3>Running the sample application</h3> 264 265<p>You cannot run the sample application in the emulator. You must install the sample application 266onto a device to run it. To run the sample application, do the following:</p> 267 268<ol> 269 <li><strong>Make sure you have at least one test account registered under your Google Play 270 publisher account.</strong> 271 <p>You cannot purchase items from yourself, so you need to 272 create at least one test account that you can use to purchase items in the sample application. 273 To learn how to set up a test account, see <a 274 href="{@docRoot}google/play/billing/billing_testing.html#billing-testing-setup">Setting up Test 275 Accounts</a>.</p> 276 </li> 277 <li><strong>Verify that your device is running a supported version of the Google Play 278 application or the MyApps application.</strong> 279 <p>If your device is running Android 3.0, in-app billing requires version 5.0.12 (or higher) of 280 the MyApps application. If your device is running any other version of Android, in-app billing 281 requires version 2.3.4 (or higher) of the Google Play application. To learn how to check the 282 version of the Google Play application, see <a 283 href="http://market.android.com/support/bin/answer.py?answer=190860">Updating Google 284 Play</a>.</p> 285 </li> 286 <li><strong>Install the application onto your device.</strong> 287 <p>Even though you uploaded the application to Google Play, the application is not published, 288 so you cannot download it from Google Play to a device. Instead, you must install the 289 application onto your device. To learn how to install an application onto a device, see <a 290 href="{@docRoot}tools/building/building-cmdline.html#RunningOnDevice">Running on a 291 device</a>.</p> 292 </li> 293 <li><strong>Make one of your test accounts the primary account on your device.</strong> 294 <p>The primary account on your device must be one of the <a 295 href="{@docRoot}google/play/billing/billing_admin.html#billing-testing-setup">test accounts</a> 296 that you registered on the Google Play Developer Console. If the primary account on your device is not a 297 test account, you must do a factory reset of the device and then sign in with one of your test 298 accounts. To perform a factory reset, do the following:</p> 299 <ol> 300 <li>Open Settings on your device.</li> 301 <li>Touch <strong>Privacy</strong>.</li> 302 <li>Touch <strong>Factory data reset</strong>.</li> 303 <li>Touch <strong>Reset phone</strong>.</li> 304 <li>After the phone resets, be sure to sign in with one of your test accounts during the 305 device setup process.</li> 306 </ol> 307 </li> 308 <li><strong>Run the application and purchase the sword or the potion.</strong> 309 <p>When you use a test account to purchase items, the test account is billed through Google 310 payments and your Google payments merchant account receives a payout for the purchase. 311 Therefore, you may want to refund purchases that are made with test accounts, otherwise the 312 purchases will show up as actual payouts to your merchant account.</p> 313</ol> 314 315<p class="note"><strong>Note</strong>: Debug log messages are turned off by default in the 316sample application. You can turn them on by setting the variable <code>DEBUG</code> 317to <code>true</code> in the <code>Consts.java</code> file.</p> 318 319<h2 id="billing-add-aidl">Adding the AIDL file to your project</h2> 320 321<p>The sample application contains an Android Interface Definition Language (AIDL) file, which 322defines the interface to Google Play's in-app billing service 323(<code>MarketBillingService</code>). When you add this file to your project, the Android build 324environment creates an interface file (<code>IMarketBillingService.java</code>). You can then use 325this interface to make billing requests by invoking IPC method calls.</p> 326 327<p>If you are using the ADT plug-in with Eclipse, you can just add this file to your 328<code>/src</code> directory. Eclipse will automatically generate the interface file when you build 329your project (which should happen immediately). If you are not using the ADT plug-in, you can put 330the AIDL file into your project and use the Ant tool to build your project so that the 331<code>IMarketBillingService.java</code> file gets generated.</p> 332 333<p>To add the <code>IMarketBillingService.aidl</code> file to your project, do the following:</p> 334 335<ol> 336 <li>Create the following directory in your application's <code>/src</code> directory: 337 <p><code>com/android/vending/billing/</code></p> 338 </li> 339 <li>Copy the <code>IMarketBillingService.aidl</code> file into the 340 <code>sample/src/com/android/vending/billing/</code> directory.</li> 341 <li>Build your application.</li> 342</ol> 343 344<p>You should now find a generated interface file named <code>IMarketBillingService.java</code> in 345the <code>gen</code> folder of your project.</p> 346 347<h2 id="billing-permission">Updating Your Application's Manifest</h2> 348 349<p>In-app billing relies on the Google Play application, which handles all communication between 350your application and the Google Play server. To use the Google Play application, your 351application must request the proper permission. You can do this by adding the 352<code>com.android.vending.BILLING</code> permission to your AndroidManifest.xml file. If your 353application does not declare the in-app billing permission, but attempts to send billing requests, 354Google Play will refuse the requests and respond with a <code>RESULT_DEVELOPER_ERROR</code> 355response code.</p> 356 357<p>In addition to the billing permission, you need to declare the {@link 358android.content.BroadcastReceiver} that you will use to receive asynchronous response messages 359(broadcast intents) from Google Play, and you need to declare the {@link android.app.Service} 360that you will use to bind with the <code>IMarketBillingService</code> and send messages to Google 361Play. You must also declare <a 362href="{@docRoot}guide/topics/manifest/intent-filter-element.html">intent filters</a> for the {@link 363android.content.BroadcastReceiver} so that the Android system knows how to handle the broadcast 364intents that are sent from the Google Play application.</p> 365 366<p>For example, here is how the in-app billing sample application declares the billing permission, 367the {@link android.content.BroadcastReceiver}, the {@link android.app.Service}, and the intent 368filters. In the sample application, <code>BillingReceiver</code> is the {@link 369android.content.BroadcastReceiver} that handles broadcast intents from the Google Play 370application and <code>BillingService</code> is the {@link android.app.Service} that sends requests 371to the Google Play application.</p> 372 373<pre> 374<?xml version="1.0" encoding="utf-8"?> 375<manifest xmlns:android="http://schemas.android.com/apk/res/android" 376 package="com.example.dungeons" 377 android:versionCode="1" 378 android:versionName="1.0"> 379 380 <uses-permission android:name="com.android.vending.BILLING" /> 381 382 <application android:icon="@drawable/icon" android:label="@string/app_name"> 383 <activity android:name=".Dungeons" android:label="@string/app_name"> 384 <intent-filter> 385 <action android:name="android.intent.action.MAIN" /> 386 <category android:name="android.intent.category.LAUNCHER" /> 387 </intent-filter> 388 </activity> 389 390 <service android:name="BillingService" /> 391 392 <receiver android:name="BillingReceiver"> 393 <intent-filter> 394 <action android:name="com.android.vending.billing.IN_APP_NOTIFY" /> 395 <action android:name="com.android.vending.billing.RESPONSE_CODE" /> 396 <action android:name="com.android.vending.billing.PURCHASE_STATE_CHANGED" /> 397 </intent-filter> 398 </receiver> 399 400 </application> 401</manifest> 402</pre> 403 404<h2 id="billing-service">Creating a Local Service</h2> 405 406<p>Your application must have a local {@link android.app.Service} to facilitate messaging between 407your application and Google Play. At a minimum, this service must do the following:</p> 408 409<ul> 410 <li>Bind to the <code>MarketBillingService</code>. 411 <li>Send billing requests (as IPC method calls) to the Google Play application. The five types 412 of billing requests include: 413 <ul> 414 <li><code>CHECK_BILLING_SUPPORTED</code> requests</li> 415 <li><code>REQUEST_PURCHASE</code> requests</li> 416 <li><code>GET_PURCHASE_INFORMATION</code> requests</li> 417 <li><code>CONFIRM_NOTIFICATIONS</code> requests</li> 418 <li><code>RESTORE_TRANSACTIONS</code> requests</li> 419 </ul> 420 </li> 421 <li>Handle the synchronous response messages that are returned with each billing request.</li> 422</ul> 423 424<h3>Binding to the MarketBillingService</h3> 425 426<p>Binding to the <code>MarketBillingService</code> is relatively easy if you've already added the 427<code>IMarketBillingService.aidl</code> file to your project. The following code sample shows how to 428use the {@link android.content.Context#bindService bindService()} method to bind a service to the 429<code>MarketBillingService</code>. You could put this code in your service's {@link 430android.app.Activity#onCreate onCreate()} method.</p> 431 432<pre> 433try { 434 boolean bindResult = mContext.bindService( 435 new Intent("com.android.vending.billing.MarketBillingService.BIND"), this, 436 Context.BIND_AUTO_CREATE); 437 if (bindResult) { 438 Log.i(TAG, "Service bind successful."); 439 } else { 440 Log.e(TAG, "Could not bind to the MarketBillingService."); 441 } 442} catch (SecurityException e) { 443 Log.e(TAG, "Security exception: " + e); 444} 445</pre> 446 447<p>After you bind to the service, you need to create a reference to the 448<code>IMarketBillingService</code> interface so you can make billing requests via IPC method calls. 449The following code shows you how to do this using the {@link 450android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback method.</p> 451 452<pre> 453/** 454 * The Android system calls this when we are connected to the MarketBillingService. 455 */ 456 public void onServiceConnected(ComponentName name, IBinder service) { 457 Log.i(TAG, "MarketBillingService connected."); 458 mService = IMarketBillingService.Stub.asInterface(service); 459 } 460</pre> 461 462<p>You can now use the <code>mService</code> reference to invoke the 463<code>sendBillingRequest()</code> method.</p> 464 465<p>For a complete implementation of a service that binds to the <code>MarketBillingService</code>, 466see the <code>BillingService</code> class in the sample application.</p> 467 468<h3>Sending billing requests to the MarketBillingService</h3> 469 470<p>Now that your {@link android.app.Service} has a reference to the 471<code>IMarketBillingService</code> interface, you can use that reference to send billing requests 472(via IPC method calls) to the <code>MarketBillingService</code>. The 473<code>MarketBillingService</code> IPC interface exposes a single public method 474(<code>sendBillingRequest()</code>), which takes a single {@link android.os.Bundle} parameter. The 475Bundle that you deliver with this method specifies the type of request you want to perform, using 476various key-value pairs. For instance, one key indicates the type of request you are making, another 477indicates the item being purchased, and another identifies your application. The 478<code>sendBillingRequest()</code> method immediately returns a Bundle containing an initial response 479code. However, this is not the complete purchase response; the complete response is delivered with 480an asynchronous broadcast intent. For more information about the various Bundle keys that are 481supported by the <code>MarketBillingService</code>, see <a 482href="{@docRoot}google/play/billing/v2/billing_reference.html#billing-interface">In-app Billing 483Service Interface</a>.</p> 484 485<p>You can use the <code>sendBillingRequest()</code> method to send five types of billing requests. 486The five request types are specified using the <code>BILLING_REQUEST</code> Bundle key. This Bundle 487key can have the following five values:</p> 488 489<ul> 490 <li><code>CHECK_BILLING_SUPPORTED</code>—verifies that the Google Play application 491 supports in-app billing and the version of the In-app Billing API available.</li> 492 <li><code>REQUEST_PURCHASE</code>—sends a purchase request for an in-app item.</li> 493 <li><code>GET_PURCHASE_INFORMATION</code>—retrieves transaction information for a purchase 494 or refund.</li> 495 <li><code>CONFIRM_NOTIFICATIONS</code>—acknowledges that you received the transaction 496 information for a purchase or refund.</li> 497 <li><code>RESTORE_TRANSACTIONS</code>—retrieves a user's transaction history for <a 498 href="{@docRoot}google/play/billing/billing_admin.html#billing-purchase-type">managed 499 purchases</a>.</li> 500</ul> 501 502<p>To make any of these billing requests, you first need to build an initial {@link 503android.os.Bundle} that contains the three keys that are required for all requests: 504<code>BILLING_REQUEST</code>, <code>API_VERSION</code>, and <code>PACKAGE_NAME</code>. The following 505code sample shows you how to create a helper method named <code>makeRequestBundle()</code> that does 506this.</p> 507 508<pre> 509protected Bundle makeRequestBundle(String method) { 510 Bundle request = new Bundle(); 511 request.putString(BILLING_REQUEST, method); 512 request.putInt(API_VERSION, 1); 513 request.putString(PACKAGE_NAME, getPackageName()); 514 return request; 515</pre> 516 517<p>To use this helper method, you pass in a <code>String</code> that corresponds to one of the five 518types of billing requests. The method returns a Bundle that has the three required keys defined. The 519following sections show you how to use this helper method when you send a billing request.</p> 520 521<p class="caution"><strong>Important</strong>: You must make all in-app billing requests from your 522application's main thread.</p> 523 524<h4>Verifying that in-app billing is supported (CHECK_BILLING_SUPPPORTED)</h4> 525 526<p>The following code sample shows how to verify whether the Google Play application supports 527in-app billing and confirm what version of the API it supports. In the sample, <code>mService</code> 528is an instance of the <code>MarketBillingService</code> interface.</p> 529 530<pre> 531/** 532* Request type is CHECK_BILLING_SUPPORTED 533*/ 534 Bundle request = makeRequestBundle("CHECK_BILLING_SUPPORTED"); 535 Bundle response = mService.sendBillingRequest(request); 536 // Do something with this response. 537} 538</pre> 539 540<p>The <code>makeRequestBundle()</code> method constructs an initial Bundle, which contains the 541three keys that are required for all requests: <code>BILLING_REQUEST</code>, 542<code>API_VERSION</code>, and <code>PACKAGE_NAME</code>. If you are offering subscriptions in 543your app, set the API_VERSION key to a value of "2", to confirm that In-app Billing v2 is 544available. For an example, see 545<a href="{@docRoot}google/play/billing/v2/billing_subscriptions.html#version">Subscriptions</a>.</p> 546 547<p>The <code>CHECK_BILLING_SUPPORTED</code> request returns a synchronous {@link 548android.os.Bundle} response, which contains only a single key: <code>RESPONSE_CODE</code>. The 549<code>RESPONSE_CODE</code> key can have the following values:</p> 550<ul> 551 <li><code>RESULT_OK</code>—the spedified version of in-app billing is supported.</li> 552 <li><code>RESULT_BILLING_UNAVAILABLE</code>—in-app billing is not available because the API 553 version you specified is not recognized or the user is not eligible to make in-app purchases (for 554 example, the user resides in a country that prohibits in-app purchases).</li> 555 <li><code>RESULT_ERROR</code>—there was an error connecting with the Google Play 556 application.</li> 557 <li><code>RESULT_DEVELOPER_ERROR</code>—the application is trying to make an in-app billing 558 request but the application has not declared the <code>com.android.vending.BILLING</code> 559 permission in its manifest. Can also indicate that an application is not properly signed, or that 560 you sent a malformed request.</li> 561</ul> 562 563<p>The <code>CHECK_BILLING_SUPPORTED</code> request does not trigger any asynchronous responses 564(broadcast intents).</p> 565 566<p>We recommend that you invoke the <code>CHECK_BILLING_SUPPORTED</code> request within a 567<code>RemoteException</code> block. When your code throws a <code>RemoteException</code> it 568indicates that the remote method call failed, which means that the Google Play application is out 569of date and needs to be updated. In this case, you can provide users with an error message that 570contains a link to the <a 571href="http://market.android.com/support/bin/answer.py?answer=190860">Updating Google Play</a> 572Help topic.</p> 573 574<p>The sample application demonstrates how you can handle this error condition (see 575<code>DIALOG_CANNOT_CONNECT_ID</code> in <code>Dungeons.java</code>).</p> 576 577<h4>Making a purchase request (REQUEST_PURCHASE)</h4> 578 579<p>To make a purchase request you must do the following:</p> 580 581<ul> 582 <li>Send the <code>REQUEST_PURCHASE</code> request.</li> 583 <li>Launch the {@link android.app.PendingIntent} that is returned from the Google Play 584 application.</li> 585 <li>Handle the broadcast intents that are sent by the Google Play application.</li> 586</ul> 587 588<h5>Making the request</h5> 589 590<p>You must specify four keys in the request {@link android.os.Bundle}. The following code sample 591shows how to set these keys and make a purchase request for a single in-app item. In the sample, 592<code>mProductId</code> is the Google Play product ID of an in-app item (which is listed in the 593application's <a href="{@docRoot}google/play/billing/billing_admin.html#billing-list-setup">product 594list</a>), and <code>mService</code> is an instance of the <code>MarketBillingService</code> 595interface.</p> 596 597<pre> 598/** 599* Request type is REQUEST_PURCHASE 600*/ 601 Bundle request = makeRequestBundle("REQUEST_PURCHASE"); 602 request.putString(ITEM_ID, mProductId); 603 // Request is for a standard in-app product 604 request.putString(ITEM_TYPE, "inapp"); 605 // Note that the developer payload is optional. 606 if (mDeveloperPayload != null) { 607 request.putString(DEVELOPER_PAYLOAD, mDeveloperPayload); 608 } 609 Bundle response = mService.sendBillingRequest(request); 610 // Do something with this response. 611</pre> 612<p>The <code>makeRequestBundle()</code> method constructs an initial Bundle, which contains the 613three keys that are required for all requests: <code>BILLING_REQUEST</code>, 614<code>API_VERSION</code>, and <code>PACKAGE_NAME</code>. The <code>ITEM_ID</code> key is then added 615to the Bundle prior to invoking the <code>sendBillingRequest()</code> method.</p> 616 617<p>The request returns a synchronous {@link android.os.Bundle} response, which contains three keys: 618<code>RESPONSE_CODE</code>, <code>PURCHASE_INTENT</code>, and <code>REQUEST_ID</code>. The 619<code>RESPONSE_CODE</code> key provides you with the status of the request and the 620<code>REQUEST_ID</code> key provides you with a unique request identifier for the request. The 621<code>PURCHASE_INTENT</code> key provides you with a {@link android.app.PendingIntent}, which you 622can use to launch the checkout UI.</p> 623 624<h5>Using the pending intent</h5> 625 626<p>How you use the pending intent depends on which version of Android a device is running. On 627Android 1.6, you must use the pending intent to launch the checkout UI in its own separate task 628instead of your application's activity stack. On Android 2.0 and higher, you can use the pending 629intent to launch the checkout UI on your application's activity stack. The following code shows you 630how to do this. You can find this code in the <code>PurchaseObserver.java</code> file in the sample 631application.</p> 632 633<pre> 634void startBuyPageActivity(PendingIntent pendingIntent, Intent intent) { 635 if (mStartIntentSender != null) { 636 // This is on Android 2.0 and beyond. The in-app checkout page activity 637 // will be on the activity stack of the application. 638 try { 639 // This implements the method call: 640 // mActivity.startIntentSender(pendingIntent.getIntentSender(), 641 // intent, 0, 0, 0); 642 mStartIntentSenderArgs[0] = pendingIntent.getIntentSender(); 643 mStartIntentSenderArgs[1] = intent; 644 mStartIntentSenderArgs[2] = Integer.valueOf(0); 645 mStartIntentSenderArgs[3] = Integer.valueOf(0); 646 mStartIntentSenderArgs[4] = Integer.valueOf(0); 647 mStartIntentSender.invoke(mActivity, mStartIntentSenderArgs); 648 } catch (Exception e) { 649 Log.e(TAG, "error starting activity", e); 650 } 651 } else { 652 // This is on Android 1.6. The in-app checkout page activity will be on its 653 // own separate activity stack instead of on the activity stack of 654 // the application. 655 try { 656 pendingIntent.send(mActivity, 0 /* code */, intent); 657 } catch (CanceledException e) { 658 Log.e(TAG, "error starting activity", e); 659 } 660 } 661} 662</pre> 663 664<p class="caution"><strong>Important:</strong> You must launch the pending intent from an activity 665context and not an application context. Also, you cannot use the <code>singleTop</code> <a 666href="{@docRoot}guide/topics/manifest/activity-element.html#lmode">launch mode</a> to launch the 667pending intent. If you do either of these, the Android system will not attach the pending intent to 668your application process. Instead, it will bring Google Play to the foreground, disrupting your 669application.</p> 670 671<h5>Handling broadcast intents</h5> 672 673<p>A <code>REQUEST_PURCHASE</code> request also triggers two asynchronous responses (broadcast 674intents). First, the Google Play application sends a <code>RESPONSE_CODE</code> broadcast intent, 675which provides error information about the request. If the request does not generate an 676error, the <code>RESPONSE_CODE</code> broadcast intent returns <code>RESULT_OK</code>, which 677indicates that the request was successfully sent. (To be clear, a <code>RESULT_OK</code> response 678does not indicate that the requested purchase was successful; it indicates that the request was sent 679successfully to Google Play.)</p> 680 681<p>Next, when the requested transaction changes state (for example, the purchase is successfully 682charged to a credit card or the user cancels the purchase), the Google Play application sends an 683<code>IN_APP_NOTIFY</code> broadcast intent. This message contains a notification ID, which you can 684use to retrieve the transaction details for the <code>REQUEST_PURCHASE</code> request.</p> 685 686<p class="note"><strong>Note:</strong> The Google Play application also sends 687an <code>IN_APP_NOTIFY</code> for refunds. For more information, see <a 688href="{@docRoot}google/play/billing/v2/api.html#billing-action-notify">Handling 689IN_APP_NOTIFY messages</a>.</p> 690 691<p>Because the purchase process is not instantaneous and can take several seconds (or more), you 692must assume that a purchase request is pending from the time you receive a <code>RESULT_OK</code> 693message until you receive an <code>IN_APP_NOTIFY</code> message for the transaction. While the 694transaction is pending, the Google Play checkout UI displays an "Authorizing purchase..." 695notification; however, this notification is dismissed after 60 seconds and you should not rely on 696this notification as your primary means of conveying transaction status to users. Instead, we 697recommend that you do the following:</p> 698 699<ul> 700 <li>Add an {@link android.app.Activity} to your application that shows users the status of pending 701and completed in-app purchases.</li> 702 <li>Use a <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html">status 703bar notification</a> to keep users informed about the progress of a purchase.</li> 704</ul> 705 706<p>To use these two UI elements, you could invoke a status bar notification with a ticker-text 707message that says "Purchase pending" when your application receives a <code>RESULT_OK</code> 708message. Then, when your application receives an <code>IN_APP_NOTIFY</code> message, you could 709update the notification with a new message that says "Purchase succeeded" or "Purchase failed." When 710a user touches the expanded status bar notification, you could launch the activity that shows the 711status of pending and completed in-app purchases.</p> 712 713<p>If you use some other UI technique to inform users about the state of a pending transaction, 714be sure that your pending status UI does not block your application. For example, you should avoid 715using a hovering progress wheel to convey the status of a pending transaction because a pending 716transaction could last a long time, particularly if a device loses network connectivity and cannot 717receive transaction updates from Google Play.</p> 718 719<p class="caution"><strong>Important:</strong> If a user purchases a managed item, you must prevent 720the user from purchasing the item again while the original transaction is pending. If a user 721attempts to purchase a managed item twice, and the first transaction is still pending, Google 722Play will display an error to the user; however, Google Play will not send an error to your 723application notifying you that the second purchase request was canceled. This might cause your 724application to get stuck in a pending state while it waits for an <code>IN_APP_NOTIFY</code> message 725for the second purchase request.</p> 726 727<h4>Retrieving transaction information for a purchase or refund (GET_PURCHASE_INFORMATION)</h4> 728 729<p>You retrieve transaction information in response to an <code>IN_APP_NOTIFY</code> broadcast 730intent. The <code>IN_APP_NOTIFY</code> message contains a notification ID, which you can use to 731retrieve transaction information.</p> 732 733<p>To retrieve transaction information for a purchase or refund you must specify five keys in the 734request {@link android.os.Bundle}. The following code sample shows how to set these keys and make 735the request. In the sample, <code>mService</code> is an instance of the 736<code>MarketBillingService</code> interface.</p> 737 738<pre> 739/** 740* Request type is GET_PURCHASE_INFORMATION 741*/ 742 Bundle request = makeRequestBundle("GET_PURCHASE_INFORMATION"); 743 request.putLong(REQUEST_NONCE, mNonce); 744 request.putStringArray(NOTIFY_IDS, mNotifyIds); 745 Bundle response = mService.sendBillingRequest(request); 746 // Do something with this response. 747} 748</pre> 749<p>The <code>makeRequestBundle()</code> method constructs an initial Bundle, which contains the 750three keys that are required for all requests: <code>BILLING_REQUEST</code>, 751<code>API_VERSION</code>, and <code>PACKAGE_NAME</code>. The additional keys are then added to the 752bundle prior to invoking the <code>sendBillingRequest()</code> method. The 753<code>REQUEST_NONCE</code> key contains a cryptographically secure nonce (number used once) that you 754must generate. The Google Play application returns this nonce with the 755<code>PURCHASE_STATE_CHANGED</code> broadcast intent so you can verify the integrity of the 756transaction information. The <code>NOTIFY_IDS</code> key contains an array of notification IDs, 757which you received in the <code>IN_APP_NOTIFY</code> broadcast intent.</p> 758 759<p>The request returns a synchronous {@link android.os.Bundle} response, which contains two keys: 760<code>RESPONSE_CODE</code> and <code>REQUEST_ID</code>. The <code>RESPONSE_CODE</code> key provides 761you with the status of the request and the <code>REQUEST_ID</code> key provides you with a unique 762request identifier for the request.</p> 763 764<p>A <code>GET_PURCHASE_INFORMATION</code> request also triggers two asynchronous responses 765(broadcast intents). First, the Google Play application sends a <code>RESPONSE_CODE</code> 766broadcast intent, which provides status and error information about the request. Next, if the 767request was successful, the Google Play application sends a <code>PURCHASE_STATE_CHANGED</code> 768broadcast intent. This message contains detailed transaction information. The transaction 769information is contained in a signed JSON string (unencrypted). The message includes the signature 770so you can verify the integrity of the signed string.</p> 771 772<h4>Acknowledging transaction information (CONFIRM_NOTIFICATIONS)</h4> 773 774<p>To acknowledge that you received transaction information you send a 775<code>CONFIRM_NOTIFICATIONS</code> request. You must specify four keys in the request {@link 776android.os.Bundle}. The following code sample shows how to set these keys and make the request. In 777the sample, <code>mService</code> is an instance of the <code>MarketBillingService</code> 778interface.</p> 779 780<pre> 781/** 782* Request type is CONFIRM_NOTIFICATIONS 783*/ 784 Bundle request = makeRequestBundle("CONFIRM_NOTIFICATIONS"); 785 request.putStringArray(NOTIFY_IDS, mNotifyIds); 786 Bundle response = mService.sendBillingRequest(request); 787 // Do something with this response. 788} 789</pre> 790<p>The <code>makeRequestBundle()</code> method constructs an initial Bundle, which contains the 791three keys that are required for all requests: <code>BILLING_REQUEST</code>, 792<code>API_VERSION</code>, and <code>PACKAGE_NAME</code>. The additional <code>NOTIFY_IDS</code> key 793is then added to the bundle prior to invoking the <code>sendBillingRequest()</code> method. The 794<code>NOTIFY_IDS</code> key contains an array of notification IDs, which you received in an 795<code>IN_APP_NOTIFY</code> broadcast intent and also used in a <code>GET_PURCHASE_INFORMATION</code> 796request.</p> 797 798<p>The request returns a synchronous {@link android.os.Bundle} response, which contains two keys: 799<code>RESPONSE_CODE</code> and <code>REQUEST_ID</code>. The <code>RESPONSE_CODE</code> key provides 800you with the status of the request and the <code>REQUEST_ID</code> key provides you with a unique 801request identifier for the request.</p> 802 803<p>A <code>CONFIRM_NOTIFICATIONS</code> request triggers a single asynchronous response—a 804<code>RESPONSE_CODE</code> broadcast intent. This broadcast intent provides status and error 805information about the request.</p> 806 807<p>You must send a confirmation when you receive transaction information from Google Play. If you 808don't send a confirmation message, Google Play will continue sending 809<code>IN_APP_NOTIFY</code> messages for the transactions you have not confirmed. Also, 810your application must be able to handle <code>IN_APP_NOTIFY</code> messages that contain multiple 811orders.</p> 812 813<p>In addition, as a best practice, you should not send a <code>CONFIRM_NOTIFICATIONS</code> request 814for a purchased item until you have delivered the item to the user. This way, if your application 815crashes or something else prevents your application from delivering the product, your application 816will still receive an <code>IN_APP_NOTIFY</code> broadcast intent from Google Play indicating 817that you need to deliver the product.</p> 818 819<h4>Restoring transaction information (RESTORE_TRANSACTIONS)</h4> 820 821<p>To restore a user's transaction information, you send a <code>RESTORE_TRANSACTIONS</code> 822request. You must specify four keys in the request {@link android.os.Bundle}. The following code 823sample shows how to set these keys and make the request. In the sample, <code>mService</code> is an 824instance of the <code>MarketBillingService</code> interface.</p> 825 826<pre> 827/** 828* Request type is RESTORE_TRANSACTIONS 829*/ 830 Bundle request = makeRequestBundle("RESTORE_TRANSACTIONS"); 831 request.putLong(REQUEST_NONCE, mNonce); 832 Bundle response = mService.sendBillingRequest(request); 833 // Do something with this response. 834} 835</pre> 836<p>The <code>makeRequestBundle()</code> method constructs an initial Bundle, which contains the 837three keys that are required for all requests: <code>BILLING_REQUEST</code>, 838<code>API_VERSION</code>, and <code>PACKAGE_NAME</code>. The additional <code>REQUEST_NONCE</code> 839key is then added to the bundle prior to invoking the <code>sendBillingRequest()</code> method. The 840<code>REQUEST_NONCE</code> key contains a cryptographically secure nonce (number used once) that you 841must generate. The Google Play application returns this nonce with the transactions information 842contained in the <code>PURCHASE_STATE_CHANGED</code> broadcast intent so you can verify the 843integrity of the transaction information.</p> 844 845<p>The request returns a synchronous {@link android.os.Bundle} response, which contains two keys: 846<code>RESPONSE_CODE</code> and <code>REQUEST_ID</code>. The <code>RESPONSE_CODE</code> key provides 847you with the status of the request and the <code>REQUEST_ID</code> key provides you with a unique 848request identifier for the request.</p> 849 850<p>A <code>RESTORE_TRANSACTIONS</code> request also triggers two asynchronous responses (broadcast 851intents). First, the Google Play application sends a <code>RESPONSE_CODE</code> broadcast intent, 852which provides status and error information about the request. Next, if the request was successful, 853the Google Play application sends a <code>PURCHASE_STATE_CHANGED</code> broadcast intent. This 854message contains the detailed transaction information. The transaction information is contained in a 855signed JSON string (unencrypted). The message includes the signature so you can verify the integrity 856of the signed string.</p> 857 858<p class="note"><strong>Note:</strong> You should use the <code>RESTORE_TRANSACTIONS</code> 859request type only when your application is installed for the first time on a device or when your 860application has been removed from a device and reinstalled.</p> 861 862<h3>Other service tasks</h3> 863 864<p>You may also want your {@link android.app.Service} to receive intent messages from your {@link 865android.content.BroadcastReceiver}. You can use these intent messages to convey the information that 866was sent asynchronously from the Google Play application to your {@link 867android.content.BroadcastReceiver}. To see an example of how you can send and receive these intent 868messages, see the <code>BillingReceiver.java</code> and <code>BillingService.java</code> files in 869the sample application. You can use these samples as a basis for your own implementation. However, 870if you use any of the code from the sample application, be sure you follow the guidelines in <a 871href="{@docRoot}google/play/billing/billing_best_practices.html">Security and Design</a>.</p> 872 873<h2 id="billing-broadcast-receiver">Creating a BroadcastReceiver</h2> 874 875<p>The Google Play application uses broadcast intents to send asynchronous billing responses to 876your application. To receive these intent messages, you need to create a {@link 877android.content.BroadcastReceiver} that can handle the following intents:</p> 878 879<ul> 880 <li>com.android.vending.billing.RESPONSE_CODE 881 <p>This broadcast intent contains a Google Play response code, and is sent after you make an 882 in-app billing request. For more information about the response codes that are sent with this 883 response, see <a 884 href="{@docRoot}google/play/billing/v2/billing_reference.html#billing-codes">Google Play Response 885 Codes for In-app Billing</a>.</p> 886 </li> 887 <li>com.android.vending.billing.IN_APP_NOTIFY 888 <p>This response indicates that a purchase has changed state, which means a purchase succeeded, 889 was canceled, or was refunded. For more information about notification messages, see <a 890 href="{@docRoot}google/play/billing/v2/billing_reference.html#billing-intents">In-app Billing 891 Broadcast Intents</a></p> 892 </li> 893 <li>com.android.vending.billing.PURCHASE_STATE_CHANGED 894 <p>This broadcast intent contains detailed information about one or more transactions. For more 895 information about purchase state messages, see <a 896 href="{@docRoot}google/play/billing/v2/billing_reference.html#billing-intents">In-app Billing 897 Broadcast Intents</a></p> 898 </li> 899</ul> 900 901<p>Each of these broadcast intents provide intent extras, which your {@link 902android.content.BroadcastReceiver} must handle. The intent extras are listed in the following table 903(see table 1).</p> 904 905<p class="table-caption"><strong>Table 1.</strong> Description of broadcast intent extras that are 906sent in response to billing requests.</p> 907 908<table> 909 910<tr> 911<th>Intent</th> 912<th>Extra</th> 913<th>Description</th> 914</tr> 915<tr> 916 <td><code>com.android.vending.billing.RESPONSE_CODE</code></td> 917 <td><code>request_id</code></td> 918 <td>A <code>long</code> representing a request ID. A request ID identifies a specific billing 919 request and is returned by Google Play at the time a request is made.</td> 920</tr> 921<tr> 922 <td><code>com.android.vending.billing.RESPONSE_CODE</code></td> 923 <td><code>response_code</code></td> 924 <td>An <code>int</code> representing the actual Google Play server response code.</td> 925</tr> 926<tr> 927 <td><code>com.android.vending.billing.IN_APP_NOTIFY</code></td> 928 <td><code>notification_id</code></td> 929 <td>A <code>String</code> representing the notification ID for a given purchase state change. 930 Google Play notifies you when there is a purchase state change and the notification includes a 931 unique notification ID. To get the details of the purchase state change, you send the notification 932 ID with the <code>GET_PURCHASE_INFORMATION</code> request.</td> 933</tr> 934<tr> 935 <td><code>com.android.vending.billing.PURCHASE_STATE_CHANGED</code></td> 936 <td><code>inapp_signed_data</code></td> 937 <td>A <code>String</code> representing the signed JSON string. The JSON string contains 938 information about the billing transaction, such as order number, amount, and the item that was 939 purchased or refunded.</td> 940</tr> 941<tr> 942 <td><code>com.android.vending.billing.PURCHASE_STATE_CHANGED</code></td> 943 <td><code>inapp_signature</code></td> 944 <td>A <code>String</code> representing the signature of the JSON string.</td> 945</tr> 946</table> 947 948<p>The following code sample shows how to handle these broadcast intents and intent extras within a 949{@link android.content.BroadcastReceiver}. The BroadcastReceiver in this case is named 950<code>BillingReceiver</code>, just as it is in the sample application.</p> 951 952<pre> 953public class BillingReceiver extends BroadcastReceiver { 954 955 private static final String TAG = "BillingReceiver"; 956 957 // Intent actions that we receive in the BillingReceiver from Google Play. 958 // These are defined by Google Play and cannot be changed. 959 // The sample application defines these in the Consts.java file. 960 public static final String ACTION_NOTIFY = 961 "com.android.vending.billing.IN_APP_NOTIFY"; 962 public static final String ACTION_RESPONSE_CODE = 963 "com.android.vending.billing.RESPONSE_CODE"; 964 public static final String ACTION_PURCHASE_STATE_CHANGED = 965 "com.android.vending.billing.PURCHASE_STATE_CHANGED"; 966 967 // The intent extras that are passed in an intent from Google Play. 968 // These are defined by Google Play and cannot be changed. 969 // The sample application defines these in the Consts.java file. 970 public static final String NOTIFICATION_ID = "notification_id"; 971 public static final String INAPP_SIGNED_DATA = "inapp_signed_data"; 972 public static final String INAPP_SIGNATURE = "inapp_signature"; 973 public static final String INAPP_REQUEST_ID = "request_id"; 974 public static final String INAPP_RESPONSE_CODE = "response_code"; 975 976 977 @Override 978 public void onReceive(Context context, Intent intent) { 979 String action = intent.getAction(); 980 if (ACTION_PURCHASE_STATE_CHANGED.equals(action)) { 981 String signedData = intent.getStringExtra(INAPP_SIGNED_DATA); 982 String signature = intent.getStringExtra(INAPP_SIGNATURE); 983 // Do something with the signedData and the signature. 984 } else if (ACTION_NOTIFY.equals(action)) { 985 String notifyId = intent.getStringExtra(NOTIFICATION_ID); 986 // Do something with the notifyId. 987 } else if (ACTION_RESPONSE_CODE.equals(action)) { 988 long requestId = intent.getLongExtra(INAPP_REQUEST_ID, -1); 989 int responseCodeIndex = intent.getIntExtra(INAPP_RESPONSE_CODE, 990 ResponseCode.RESULT_ERROR.ordinal()); 991 // Do something with the requestId and the responseCodeIndex. 992 } else { 993 Log.w(TAG, "unexpected action: " + action); 994 } 995 } 996 // Perform other processing here, such as forwarding intent messages 997 // to your local service. 998} 999</pre> 1000 1001<p>In addition to receiving broadcast intents from the Google Play application, your {@link 1002android.content.BroadcastReceiver} must handle the information it received in the broadcast intents. 1003Usually, your {@link android.content.BroadcastReceiver} does this by sending the information to a 1004local service (discussed in the next section). The <code>BillingReceiver.java</code> file in the 1005sample application shows you how to do this. You can use this sample as a basis for your own {@link 1006android.content.BroadcastReceiver}. However, if you use any of the code from the sample application, 1007be sure you follow the guidelines that are discussed in <a 1008href="{@docRoot}google/play/billing/billing_best_practices.html">Security and Design </a>.</p> 1009 1010<h2 id="billing-security">Securing Your Application</h2> 1011 1012<p>To help ensure the integrity of the transaction information that is sent to your application, 1013Google Play signs the JSON string that is contained in the <code>PURCHASE_STATE_CHANGED</code> 1014broadcast intent. Google Play uses the private key that is associated with your publisher account 1015to create this signature. The Developer Console generates an RSA key pair for each publisher account. 1016You can find the public key portion of this key pair on your account's profile page. It is the same 1017public key that is used with Google Play licensing.</p> 1018 1019<p>When Google Play signs a billing response, it includes the signed JSON string (unencrypted) 1020and the signature. When your application receives this signed response you can use the public key 1021portion of your RSA key pair to verify the signature. By performing signature verification you can 1022help detect responses that have been tampered with or that have been spoofed. You can perform this 1023signature verification step in your application; however, if your application connects to a secure 1024remote server then we recommend that you perform the signature verification on that server.</p> 1025 1026<p>In-app billing also uses nonces (a random number used once) to help verify the integrity of the 1027purchase information that's returned from Google Play. Your application must generate a nonce and 1028send it with a <code>GET_PURCHASE_INFORMATION</code> request and a <code>RESTORE_TRANSACTIONS</code> 1029request. When Google Play receives the request, it adds the nonce to the JSON string that 1030contains the transaction information. The JSON string is then signed and returned to your 1031application. When your application receives the JSON string, you need to verify the nonce as well as 1032the signature of the JSON string.</p> 1033 1034<p>For more information about best practices for security and design, see <a 1035href="{@docRoot}google/play/billing/billing_best_practices.html">Security and Design</a>.</p> 1036 1037<h3 id="billing-signatures">Verifying signatures and nonces</h3> 1038 1039<p>Google Play's in-app billing service uses two mechanisms to help verify the integrity of the 1040transaction information you receive from Google Play: nonces and signatures. A nonce (number used 1041once) is a cryptographically secure number that your application generates and sends with every 1042<code>GET_PURCHASE_INFORMATION</code> and <code>RESTORE_TRANSACTIONS</code> request. The nonce is 1043returned with the <code>PURCHASE_STATE_CHANGED</code> broadcast intent, enabling you to verify that 1044any given <code>PURCHASE_STATE_CHANGED</code> response corresponds to an actual request that you 1045made. Every <code>PURCHASE_STATE_CHANGED</code> broadcast intent also includes a signed JSON string 1046and a signature, which you can use to verify the integrity of the response.</p> 1047 1048<p>Your application must provide a way to generate, manage, and verify nonces. The following sample 1049code shows some simple methods you can use to do this.</p> 1050 1051<pre> 1052 private static final SecureRandom RANDOM = new SecureRandom(); 1053 private static HashSet<Long> sKnownNonces = new HashSet<Long>(); 1054 1055 public static long generateNonce() { 1056 long nonce = RANDOM.nextLong(); 1057 sKnownNonces.add(nonce); 1058 return nonce; 1059 } 1060 1061 public static void removeNonce(long nonce) { 1062 sKnownNonces.remove(nonce); 1063 } 1064 1065 public static boolean isNonceKnown(long nonce) { 1066 return sKnownNonces.contains(nonce); 1067 } 1068</pre> 1069 1070<p>Your application must also provide a way to verify the signatures that accompany every 1071<code>PURCHASE_STATE_CHANGED</code> broadcast intent. The <code>Security.java</code> file in the 1072sample application shows you how to do this. If you use this file as a basis for your own security 1073implementation, be sure to follow the guidelines in <a 1074href="{@docRoot}google/play/billing/billing_best_practices.html">Security and Design</a> and 1075obfuscate your code.</p> 1076 1077<p>You will need to use your Google Play public key to perform the signature verification. The 1078following procedure shows you how to retrieve Base64-encoded public key from the Google Play 1079Developer Console.</p> 1080 1081<ol> 1082 <li>Log in to your <a href="http://play.google.com/apps/publish">publisher account</a>.</li> 1083 <li>On the upper left part of the page, click <strong>All applications</strong> and then click 1084 the app name in the listing.</li> 1085 <li>Click <em>Services & APIs</em> and find "Your License Key for this Application" on the page. </li> 1086 <li>Copy the app's public key.</li> 1087</ol> 1088 1089<p class="caution"><strong>Important</strong>: To keep your public key safe from malicious users and 1090hackers, do not embed your public key as an entire literal string. Instead, construct the string at 1091runtime from pieces or use bit manipulation (for example, XOR with some other string) to hide the 1092actual key. The key itself is not secret information, but you do not want to make it easy for a 1093hacker or malicious user to replace the public key with another key.</p> 1094 1095<div style="width:640px;"> 1096<img src="{@docRoot}images/licensing_public_key.png" class="frame"> 1097<p class="img-caption"><strong>Figure 10982.</strong> An app's license key is available from the Services & APIs page in 1099the Developer Console.</p> 1100</div> 1101 1102 1103<h2 id="billing-implement">Modifying Your Application Code</h2> 1104 1105<p>After you finish adding in-app billing components to your project, you are ready to modify your 1106application's code. For a typical implementation, like the one that is demonstrated in the sample 1107application, this means you need to write code to do the following: </p> 1108 1109<ul> 1110 <li>Create a storage mechanism for storing users' purchase information.</li> 1111 <li>Create a user interface that lets users select items for purchase.</li> 1112</ul> 1113 1114<p>The sample code in <code>Dungeons.java</code> shows you how to do both of these tasks.</p> 1115 1116<h3>Creating a storage mechanism for storing purchase information</h3> 1117 1118<p>You must set up a database or some other mechanism for storing users' purchase information. The 1119sample application provides an example database (PurchaseDatabase.java); however, the example 1120database has been simplified for clarity and does not exhibit the security best practices that we 1121recommend. If you have a remote server, we recommend that you store purchase information on your 1122server instead of in a local database on a device. For more information about security best 1123practices, see <a href="{@docRoot}google/play/billing/billing_best_practices.html">Security and 1124Design</a>.</p> 1125 1126<p class="note"><strong>Note</strong>: If you store any purchase information on a device, be sure to 1127encrypt the data and use a device-specific encryption key. Also, if the purchase type for any of 1128your items is "unmanaged," we recommend that you back up the purchase information for these items to 1129a remote server or use Android's <a href="{@docRoot}guide/topics/data/backup.html">data 1130backup</a> framework to back up the purchase information. Backing up purchase information for 1131unmanaged items is important because unmanaged items cannot be restored by using the 1132<code>RESTORE_TRANSACTIONS</code> request type.</p> 1133 1134<h3>Creating a user interface for selecting items</h3> 1135 1136<p>You must provide users with a means for selecting items that they want to purchase. Google 1137Play provides the checkout user interface (which is where the user provides a form of payment and 1138approves the purchase), but your application must provide a control (widget) that invokes the 1139<code>sendBillingRequest()</code> method when a user selects an item for purchase.</p> 1140 1141<p>You can render the control and trigger the <code>sendBillingRequest()</code> method any way you 1142want. The sample application uses a spinner widget and a button to present items to a user and 1143trigger a billing request (see <code>Dungeons.java</code>). The user interface also shows a list of 1144recently purchased items.</p> 1145 1146