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