1page.title=Implementing In-app Billing 2parent.title=In-app Billing 3parent.link=index.html 4page.tags="inapp, billing, iap" 5@jd:body 6 7<div id="qv-wrapper"> 8<div id="qv"> 9 <h2>In this document</h2> 10 <ol> 11 <li><a href="#billing-add-aidl">Adding the AIDL file</a></li> 12 <li><a href="#billing-permission">Updating Your Manifest</a></li> 13 <li><a href="#billing-service">Creating a ServiceConnection</a></li> 14 <li><a href="#billing-requests">Making In-app Billing Requests</a> 15 <ol> 16 <li><a href="#QueryDetails">Querying Items Available for Purchase</a><li> 17 <li><a href="#Purchase">Purchasing an Item</a></li> 18 <li><a href="#QueryPurchases">Querying Purchased Items</a></li> 19 <li><a href="#Consume">Consuming a Purchase</a><li> 20 <li><a href="#Subs">Implementing Subscriptions</a><li> 21 </ol> 22 </li> 23 <li><a href="#billing-security">Securing Your App</a> 24 </ol> 25 <h2>Reference</h2> 26 <ol> 27 <li><a href="{@docRoot}google/play/billing/billing_reference.html">In-app Billing 28 Reference (V3)</a></li> 29 </ol> 30 <h2>Related Samples</h2> 31 <ol> 32 <li><a href="{@docRoot}training/in-app-billing/preparing-iab-app.html#GetSample">Sample Application (V3)</a></li> 33 </ol> 34 <h2>See also</h2> 35 <ol> 36 <li><a href="{@docRoot}training/in-app-billing/index.html">Selling In-app Products</a></li> 37 </ol> 38</div> 39</div> 40 41<p>In-app Billing on Google Play provides a straightforward, simple interface for sending In-app Billing requests and managing In-app Billing transactions using Google Play. The information below covers the basics of how to make calls from your application to the In-app Billing service using the Version 3 API. </p> 42 43<p class="note"><strong>Note:</strong> To see a complete implementation and learn how to test your application, see the <a href="{@docRoot}training/in-app-billing/index.html">Selling In-app Products</a> training class. The training class provides a complete sample In-app Billing application, including convenience classes to handle key tasks related to setting up your connection, sending billing requests and processing responses from Google Play, and managing background threading so that you can make In-app Billing calls from your main activity.</p> 44 45<p>Before you start, be sure that you read the <a href="{@docRoot}google/play/billing/billing_overview.html">In-app Billing Overview</a> to familiarize yourself with 46concepts that will make it easier for you to implement In-app Billing.</p> 47 48<p>To implement In-app Billing in your application, you need to do the 49following:</p> 50<ol> 51 <li>Add the In-app Billing library to your project.</li> 52 <li>Update your {@code AndroidManifest.xml} file.</li> 53 <li>Create a {@code ServiceConnection} and bind it to 54{@code IInAppBillingService}.</li> 55 <li>Send In-app Billing requests from your application to 56{@code IInAppBillingService}.</li> 57 <li>Handle In-app Billing responses from Google Play.</li> 58</ol> 59 60<h2 id="billing-add-aidl">Adding the AIDL file to your project</h2> 61 62<p>{@code IInAppBillingService.aidl} is an Android Interface Definition 63Language (AIDL) file that defines the interface to the In-app Billing Version 643 service. You will use this interface to make billing requests by invoking IPC 65method calls.</p> 66<p>To get the AIDL file:</p> 67<ol> 68<li>Open the <a href="{@docRoot}tools/help/sdk-manager.html">Android SDK Manager</a>.</li> 69<li>In the SDK Manager, expand the {@code Extras} section.</li> 70<li>Select <strong>Google Play Billing Library</strong>.</li> 71<li>Click <strong>Install packages</strong> to complete the download.</li> 72</ol> 73<p>The {@code IInAppBillingService.aidl} file will be installed to {@code <sdk>/extras/google/play_billing/}.</p> 74 75<p>To add the AIDL to your project:</p> 76<ol> 77<li>Copy the {@code IInAppBillingService.aidl} file to your Android project. 78 <ul> 79 <li>If you are using Eclipse: 80 <ol type="a"> 81 <li>If you are starting from an existing Android project, open the project 82in Eclipse. If you are creating a new Android project from scratch, click 83<strong>File</strong> > <strong>New</strong> > <strong>Android Application 84Project</strong>, then follow the instructions in the <strong>New Android 85Application</strong> wizard to create a new project in your workspace.</li> 86 <li>In the {@code /src} directory, click <strong>File</strong> > 87<strong>New</strong> > <strong>Package</strong>, then create a package named {@code com.android.vending.billing}.</li> 88 <li>Copy the {@code IInAppBillingService.aidl} file from {@code <sdk>/extras/google/play_billing/} and paste it into the {@code src/com.android.vending.billing/} 89folder in your workspace.</li> 90 </ol> 91 </li> 92 <li>If you are developing in a non-Eclipse environment: Create the following 93directory {@code /src/com/android/vending/billing} and copy the 94{@code IInAppBillingService.aidl} file into this directory. Put the AIDL file 95into your project and use the Ant tool to build your project so that the 96<code>IInAppBillingService.java</code> file gets generated.</li> 97 </ul> 98</li> 99<li>Build your application. You should see a generated file named 100{@code IInAppBillingService.java} in the {@code /gen} directory of your 101project.</li> 102</ol> 103 104 105<h2 id="billing-permission">Updating Your Application's Manifest</h2> 106 107<p>In-app billing relies on the Google Play application, which handles all communication between your application and the Google Play server. To use the Google Play application, your application must request the proper permission. You can do this by adding the {@code com.android.vending.BILLING} permission to your AndroidManifest.xml file. If your application does not declare the In-app Billing permission, but attempts to send billing requests, Google Play will refuse the requests and respond with an error.</p> 108 109<p>To give your app the necessary permission, add this line in your {@code Android.xml} manifest file:</p> 110<pre> 111<uses-permission android:name="com.android.vending.BILLING" /> 112</pre> 113 114<h2 id="billing-service">Creating a ServiceConnection</h2> 115 116<p>Your application must have a {@link android.content.ServiceConnection} to facilitate messaging between 117your application and Google Play. At a minimum, your application must do the following:</p> 118 119<ul> 120 <li>Bind to {@code IInAppBillingService}. 121 <li>Send billing requests (as IPC method calls) to the Google Play application.</li> 122 <li>Handle the synchronous response messages that are returned with each billing request.</li> 123</ul> 124 125<h3>Binding to IInAppBillingService</h3> 126<p>To establish a connection with the In-app Billing service on Google Play, implement a {@link android.content.ServiceConnection} to bind your activity to {@code IInAppBillingService}. Override the {@link android.content.ServiceConnection#onServiceDisconnected onServiceDisconnected} and {@link 127android.content.ServiceConnection#onServiceConnected onServiceConnected} methods to get a reference to the {@code IInAppBillingService} instance after a connection has been established.</p> 128<pre> 129IInAppBillingService mService; 130 131ServiceConnection mServiceConn = new ServiceConnection() { 132 @Override 133 public void onServiceDisconnected(ComponentName name) { 134 mService = null; 135 } 136 137 @Override 138 public void onServiceConnected(ComponentName name, 139 IBinder service) { 140 mService = IInAppBillingService.Stub.asInterface(service); 141 } 142}; 143</pre> 144 145<p>In your activity’s {@link android.app.Activity#onCreate onCreate} method, perform the binding by calling the {@link android.content.Context#bindService bindService} method. Pass the method an {@link android.content.Intent} that references the In-app Billing service and an instance of the {@link android.content.ServiceConnection} that you created, and explicitly set the Intent's target package name to <code>com.android.vending</code> — the package name of Google Play app.</p> 146 147<p class="caution"><strong>Caution:</strong> To protect the security of billing transactions, always make sure to explicitly set the intent's target package name to <code>com.android.vending</code>, using {@link android.content.Intent#setPackage(java.lang.String) setPackage()} as shown in the example below. Setting the package name explicitly ensures that <em>only</em> the Google Play app can handle billing requests from your app, preventing other apps from intercepting those requests.</p> 148 149<pre>@Override 150public void onCreate(Bundle savedInstanceState) { 151 super.onCreate(savedInstanceState); 152 setContentView(R.layout.activity_main); 153 Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND"); 154 serviceIntent.setPackage("com.android.vending"); 155 bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE); 156</pre> 157<p>You can now use the mService reference to communicate with the Google Play service.</p> 158<p class="note"><strong>Important:</strong> Remember to unbind from the In-app Billing service when you are done with your {@link android.app.Activity}. If you don’t unbind, the open service connection could cause your device’s performance to degrade. This example shows how to perform the unbind operation on a service connection to In-app Billing called {@code mServiceConn} by overriding the activity’s {@link android.app.Activity#onDestroy onDestroy} method.</p> 159<pre> 160@Override 161public void onDestroy() { 162 super.onDestroy(); 163 if (mService != null) { 164 unbindService(mServiceConn); 165 } 166} 167</pre> 168 169<p>For a complete implementation of a service connection that binds to the {@code IInAppBillingService}, 170see the <a href="{@docRoot}training/in-app-billing/preparing-iab-app.html">Selling In-app 171Products</a> training class and associated sample.</p> 172 173<h2 id="billing-requests">Making In-app Billing Requests</h2> 174<p>Once your application is connected to Google Play, you can initiate purchase requests for in-app products. Google Play provides a checkout interface for users to enter their payment method, so your application does not need to handle payment transactions directly. When an item is purchased, Google Play recognizes that the user has ownership of that item and prevents the user from purchasing another item with the same product ID until it is consumed. You can control how the item is consumed in your application, and notify Google Play to make the item available for purchase again. You can also query Google Play to quickly retrieve the list of purchases that were made by the user. This is useful, for example, when you want to restore the user's purchases when your user launches your app. 175</p> 176 177<h3 id="QueryDetails">Querying for Items Available for Purchase</h3> 178<p>In your application, you can query the item details from Google Play using the In-app Billing Version 3 API. To pass a request to the In-app Billing service, first create a {@link android.os.Bundle} that contains a String {@link java.util.ArrayList} of product IDs with key "ITEM_ID_LIST", where each string is a product ID for an purchasable item.</p> 179<pre> 180ArrayList<String> skuList = new ArrayList<String> (); 181skuList.add("premiumUpgrade"); 182skuList.add("gas"); 183Bundle querySkus = new Bundle(); 184querySkus.putStringArrayList(“ITEM_ID_LIST”, skuList); 185</pre> 186<p>To retrieve this information from Google Play, call the {@code getSkuDetails} method on the In-app Billing Version 3 API, and pass the method the In-app Billing API version (“3”), the package name of your calling app, the purchase type (“inapp”), and the {@link android.os.Bundle} that you created.</p> 187<pre> 188Bundle skuDetails = mService.getSkuDetails(3, 189 getPackageName(), "inapp", querySkus); 190</pre> 191<p>If the request is successful, the returned {@link android.os.Bundle}has a response code of {@code BILLING_RESPONSE_RESULT_OK} (0).</p> 192<p class="note"><strong>Warning:</strong> Do not call the {@code getSkuDetails} method on the main thread. Calling this method triggers a network request which could block your main thread. Instead, create a separate thread and call the {@code getSkuDetails} method from inside that thread.</p> 193 194<p>To see all the possible response codes from Google Play, see <a href="{@docRoot}google/play/billing/billing_reference.html#billing-codes">In-app Billing Reference</a>.</p> 195 196<p>The query results are stored in a String ArrayList with key {@code DETAILS_LIST}. The purchase information is stored in the String in JSON format. To see the types of product detail information that are returned, see <a href="{@docRoot}google/play/billing/billing_reference.html#getSkuDetails">In-app Billing Reference</a>.</p> 197 198<p>In this example, you are retrieving the prices for your in-app items from the skuDetails {@link android.os.Bundle} returned from the previous code snippet.</p> 199<pre> 200int response = skuDetails.getInt("RESPONSE_CODE"); 201if (response == 0) { 202 ArrayList<String> responseList 203 = skuDetails.getStringArrayList("DETAILS_LIST"); 204 205 for (String thisResponse : responseList) { 206 JSONObject object = new JSONObject(thisResponse); 207 String sku = object.getString("productId"); 208 String price = object.getString("price"); 209 if (sku.equals("premiumUpgrade")) mPremiumUpgradePrice = price; 210 else if (sku.equals("gas")) mGasPrice = price; 211 } 212} 213</pre> 214 215<h3 id="Purchase">Purchasing an Item</h3> 216<p>To start a purchase request from your app, call the {@code getBuyIntent} method on the In-app Billing service. Pass in to the method the In-app Billing API version (“3”), the package name of your calling app, the product ID for the item to purchase, the purchase type (“inapp” or "subs"), and a {@code developerPayload} String. The {@code developerPayload} String is used to specify any additional arguments that you want Google Play to send back along with the purchase information.</p> 217 218<pre> 219Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(), 220 sku, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ"); 221</pre> 222<p> 223If the request is successful, the returned {@link android.os.Bundle} has a response code of {@code BILLING_RESPONSE_RESULT_OK} (0) and a {@link android.app.PendingIntent} that you can use to start the purchase flow. To see all the possible response codes from Google Play, see <a href="{@docRoot}google/play/billing/billing_reference.html#billing-codes">In-app Billing Reference</a>. Next, extract a {@link android.app.PendingIntent} from the response {@link android.os.Bundle} with key {@code BUY_INTENT}. 224</p> 225<pre> 226PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT"); 227</pre> 228<p> 229To complete the purchase transaction, call the {@link android.app.Activity#startIntentSenderForResult startIntentSenderForResult} method and use the {@link android.app.PendingIntent} that you created. In this example, you are using an arbitrary value of 1001 for the request code.</p> 230<pre> 231startIntentSenderForResult(pendingIntent.getIntentSender(), 232 1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0), 233 Integer.valueOf(0)); 234</pre> 235<p>Google Play sends a response to your {@link android.app.PendingIntent} to the {@link android.app.Activity#onActivityResult onActivityResult} method of your application. The {@link android.app.Activity#onActivityResult onActivityResult} method will have a result code of {@code Activity.RESULT_OK} (1) or {@code Activity.RESULT_CANCELED} (0). To see the types of order information that is returned in the response {@link android.content.Intent}, see <a href="{@docRoot}google/play/billing/billing_reference.html#getBuyIntent">In-app Billing Reference</a>.</p> 236 237<p>The purchase data for the order is a String in JSON format that is mapped to the {@code INAPP_PURCHASE_DATA} key in the response {@link android.content.Intent}, for example: 238<pre> 239'{ 240 "orderId":"12999763169054705758.1371079406387615", 241 "packageName":"com.example.app", 242 "productId":"exampleSku", 243 "purchaseTime":1345678900000, 244 "purchaseState":0, 245 "developerPayload":"bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ", 246 "purchaseToken":<em>"opaque-token-up-to-1000-characters"</em> 247 }' 248</pre> 249</p> 250 251<p class="note"><strong>Note:</strong> Google Play generates a token for the 252purchase. This token is an opaque character sequence that may be up to 1,000 253characters long. Pass this entire token to other methods, such as when you 254consume the purchase, as described in 255<a href="{@docRoot}training/in-app-billing/purchase-iab-products.html#Consume">Consume 256a Purchase</a>. Do not abbreviate or truncate this token; you must save and 257return the entire token.</p> 258 259<p>Continuing from the previous example, you get the response code, purchase data, and signature from the response {@link android.content.Intent}.</p> 260<pre> 261@Override 262protected void onActivityResult(int requestCode, int resultCode, Intent data) { 263 if (requestCode == 1001) { 264 int responseCode = data.getIntExtra("RESPONSE_CODE", 0); 265 String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA"); 266 String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE"); 267 268 if (resultCode == RESULT_OK) { 269 try { 270 JSONObject jo = new JSONObject(purchaseData); 271 String sku = jo.getString("productId"); 272 alert("You have bought the " + sku + ". Excellent choice, 273 adventurer!"); 274 } 275 catch (JSONException e) { 276 alert("Failed to parse purchase data."); 277 e.printStackTrace(); 278 } 279 } 280 } 281} 282</pre> 283<p class="note"><strong>Security Recommendation:</strong> When you send a purchase request, create a String token that uniquely identifies this purchase request and include this token in the {@code developerPayload}.You can use a randomly generated string as the token. When you receive the purchase response from Google Play, make sure to check the returned data signature, the {@code orderId}, and the {@code developerPayload} String. For added security, you should perform the checking on your own secure server. Make sure to verify that the {@code orderId} is a unique value that you have not previously processed, and the {@code developerPayload} String matches the token that you sent previously with the purchase request.</p> 284 285<h3 id="QueryPurchases">Querying for Purchased Items</h3> 286<p>To retrieve information about purchases made by a user from your app, call the {@code getPurchases} method on the In-app Billing Version 3 service. Pass in to the method the In-app Billing API version (“3”), the package name of your calling app, and the purchase type (“inapp” or "subs").</p> 287<pre> 288Bundle ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null); 289</pre> 290<p>The Google Play service returns only the purchases made by the user account that is currently logged in to the device. If the request is successful, the returned {@link android.os.Bundle} has a response code of 0. The response {@link android.os.Bundle} also contains a list of the product IDs, a list of the order details for each purchase, and the signatures for each purchase.</p> 291<p>To improve performance, the In-app Billing service returns only up to 700 products that are owned by the user when {@code getPurchase} is first called. If the user owns a large number of products, Google Play includes a String token mapped to the key {@code INAPP_CONTINUATION_TOKEN} in the response {@link android.os.Bundle} to indicate that more products can be retrieved. Your application can then make a subsequent {@code getPurchases} call, and pass in this token as an argument. Google Play continues to return a continuation token in the response {@link android.os.Bundle} until all products that are owned by the user has been sent to your app.</p> 292<p>For more information about the data returned by {@code getPurchases}, see <a href="{@docRoot}google/play/billing/billing_reference.html#getPurchases">In-app Billing Reference</a>. The following example shows how you can retrieve this data from the response. 293<pre> 294int response = ownedItems.getInt("RESPONSE_CODE"); 295if (response == 0) { 296 ArrayList<String> ownedSkus = 297 ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST"); 298 ArrayList<String> purchaseDataList = 299 ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST"); 300 ArrayList<String> signatureList = 301 ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE_LIST"); 302 String continuationToken = 303 ownedItems.getString("INAPP_CONTINUATION_TOKEN"); 304 305 for (int i = 0; i < purchaseDataList.size(); ++i) { 306 String purchaseData = purchaseDataList.get(i); 307 String signature = signatureList.get(i); 308 String sku = ownedSkus.get(i); 309 310 // do something with this purchase information 311 // e.g. display the updated list of products owned by user 312 } 313 314 // if continuationToken != null, call getPurchases again 315 // and pass in the token to retrieve more items 316} 317 318</pre> 319 320<h3 id="Consume">Consuming a Purchase</h3> 321<p>You can use the In-app Billing Version 3 API to track the ownership of 322purchased in-app products in Google Play. Once an in-app product is purchased, 323it is considered to be "owned" and cannot be purchased from Google Play. You 324must send a consumption request for the in-app product before Google Play makes 325it available for purchase again.</p> 326<p class="caution"><strong>Important</strong>: Managed in-app products are 327consumable, but subscriptions are not.</p> 328<p>How you use the consumption mechanism in your app is up to you. Typically, 329you would implement consumption for in-app products with temporary benefits that 330users may want to purchase multiple times (for example, in-game currency or 331equipment). You would typically not want to implement consumption for in-app 332products that are purchased once and provide a permanent effect (for example, 333a premium upgrade).</p> 334<p>To record a purchase consumption, send the {@code consumePurchase} method to 335the In-app Billing service and pass in the {@code purchaseToken} String value 336that identifies the purchase to be removed. The {@code purchaseToken} is part 337of the data returned in the {@code INAPP_PURCHASE_DATA} String by the Google 338Play service following a successful purchase request. In this example, you are 339recording the consumption of a product that is identified with the 340{@code purchaseToken} in the {@code token} variable.</p> 341<pre> 342int response = mService.consumePurchase(3, getPackageName(), token); 343</pre> 344<p class="note"><strong>Warning:</strong> Do not call the {@code consumePurchase} method on the main thread. Calling this method triggers a network request which could block your main thread. Instead, create a separate thread and call the {@code consumePurchase} method from inside that thread.</p> 345<p>It's your responsibility to control and track how the in-app product is provisioned to the user. For example, if the user purchased in-game currency, you should update the player's inventory with the amount of currency purchased.</p> 346<p class="note"><strong>Security Recommendation:</strong> You must send a consumption request before provisioning the benefit of the consumable in-app purchase to the user. Make sure that you have received a successful consumption response from Google Play before you provision the item.</p> 347 348<h3 id="Subs">Implementing Subscriptions</h3> 349<p>Launching a purchase flow for a subscription is similar to launching the 350purchase flow for a product, with the exception that the product type must be set 351to "subs". The purchase result is delivered to your Activity's 352{@link android.app.Activity#onActivityResult onActivityResult} method, exactly 353as in the case of in-app products.</p> 354<pre> 355Bundle bundle = mService.getBuyIntent(3, "com.example.myapp", 356 MY_SKU, "subs", developerPayload); 357 358PendingIntent pendingIntent = bundle.getParcelable(RESPONSE_BUY_INTENT); 359if (bundle.getInt(RESPONSE_CODE) == BILLING_RESPONSE_RESULT_OK) { 360 // Start purchase flow (this brings up the Google Play UI). 361 // Result will be delivered through onActivityResult(). 362 startIntentSenderForResult(pendingIntent, RC_BUY, new Intent(), 363 Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0)); 364} 365</pre> 366<p>To query for active subscriptions, use the {@code getPurchases} method, again 367with the product type parameter set to "subs".</p> 368<pre> 369Bundle activeSubs = mService.getPurchases(3, "com.example.myapp", 370 "subs", continueToken); 371</pre> 372<p>The call returns a {@code Bundle} with all the active subscriptions owned by 373the user. Once a subscription expires without renewal, it will no longer appear 374in the returned {@code Bundle}.</p> 375 376<h2 id="billing-security">Securing Your Application</h2> 377 378<p>To help ensure the integrity of the transaction information that is sent to 379your application, Google Play signs the JSON string that contains the response 380data for a purchase order. Google Play uses the private key that is associated 381with your application in the Developer Console to create this signature. The 382Developer Console generates an RSA key pair for each application.<p> 383 384<p class="note"><strong>Note:</strong>To find the public key portion of this key 385pair, open your application's details in the Developer Console, then click on 386<strong>Services & APIs</strong>, and look at the field titled 387<strong>Your License Key for This Application</strong>.</p> 388 389<p>The Base64-encoded RSA public key generated by Google Play is in binary 390encoded, X.509 subjectPublicKeyInfo DER SEQUENCE format. It is the same public 391key that is used with Google Play licensing.</p> 392 393<p>When your application receives this signed response you can 394use the public key portion of your RSA key pair to verify the signature. 395By performing signature verification you can detect responses that have 396been tampered with or that have been spoofed. You can perform this signature 397verification step in your application; however, if your application connects 398to a secure remote server then we recommend that you perform the signature 399verification on that server.</p> 400 401<p>For more information about best practices for security and design, see <a 402href="{@docRoot}google/play/billing/billing_best_practices.html">Security and Design</a>.</p> 403 404 405 406 407 408 409 410 411 412