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