1 page.title=Implementing In-app Billing <span style="font-size:16px;">(IAB Version 3)</span> 2 parent.title=In-app Billing 3 parent.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-add-aidl">Adding the AIDL file</a></li> 11 <li><a href="#billing-permission">Updating Your Manifest</a></li> 12 <li><a href="#billing-service">Creating a ServiceConnection</a></li> 13 <li><a href="#billing-requests">Making In-app Billing Requests</a> 14 <ol> 15 <li><a href="#QueryDetails">Querying Items Available for Purchase</a><li> 16 <li><a href="#Purchase">Purchasing an Item</a></li> 17 <li><a href="#QueryPurchases">Querying Purchased Items</a></li> 18 <li><a href="#Consume">Consuming a Purchase</a><li> 19 <li><a href="#Subs">Implementing Subscriptions</a><li> 20 </ol> 21 </li> 22 <li><a href="#billing-security">Securing Your App</a> 23 </ol> 24 <h2>Reference</h2> 25 <ol> 26 <li><a href="{@docRoot}google/play/billing/billing_reference.html">In-app Billing 27 Reference (V3)</a></li> 28 </ol> 29 <h2>Related Samples</h2> 30 <ol> 31 <li><a href="{@docRoot}training/in-app-billing/preparing-iab-app.html#GetSample">Sample Application (V3)</a></li> 32 </ol> 33 <h2>See also</h2> 34 <ol> 35 <li><a href="{@docRoot}training/in-app-billing/index.html">Selling In-app Products</a></li> 36 </ol> 37 </div> 38 </div> 39 40 <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> 41 42 <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> 43 44 <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 45 concepts that will make it easier for you to implement In-app Billing.</p> 46 47 <p>To implement In-app Billing in your application, you need to do the 48 following:</p> 49 <ol> 50 <li>Add the In-app Billing library to your project.</li> 51 <li>Update your {@code AndroidManifest.xml} file.</li> 52 <li>Create a {@code ServiceConnection} and bind it to 53 {@code IInAppBillingService}.</li> 54 <li>Send In-app Billing requests from your application to 55 {@code IInAppBillingService}.</li> 56 <li>Handle In-app Billing responses from Google Play.</li> 57 </ol> 58 59 <h2 id="billing-add-aidl">Adding the AIDL file to your project</h2> 60 61 <p>{@code IInAppBillingService.aidl} is an Android Interface Definition 62 Language (AIDL) file that defines the interface to the In-app Billing Version 63 3 service. You will use this interface to make billing requests by invoking IPC 64 method calls.</p> 65 <p>To get the AIDL file:</p> 66 <ol> 67 <li>Open the <a href="{@docRoot}tools/help/sdk-manager.html">Android SDK Manager</a>.</li> 68 <li>In the SDK Manager, expand the {@code Extras} section.</li> 69 <li>Select <strong>Google Play Billing Library</strong>.</li> 70 <li>Click <strong>Install packages</strong> to complete the download.</li> 71 </ol> 72 <p>The {@code IInAppBillingService.aidl} file will be installed to {@code <sdk>/extras/google/play_billing/}.</p> 73 74 <p>To add the AIDL to your project:</p> 75 <ol> 76 <li>Copy the {@code IInAppBillingService.aidl} file to your Android project. 77 <ul> 78 <li>If you are using Eclipse: 79 <ol type="a"> 80 <li>If you are starting from an existing Android project, open the project 81 in Eclipse. If you are creating a new Android project from scratch, click 82 <strong>File</strong> > <strong>New</strong> > <strong>Android Application 83 Project</strong>, then follow the instructions in the <strong>New Android 84 Application</strong> wizard to create a new project in your workspace.</li> 85 <li>In the {@code /src} directory, click <strong>File</strong> > 86 <strong>New</strong> > <strong>Package</strong>, then create a package named {@code com.android.vending.billing}.</li> 87 <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/} 88 folder in your workspace.</li> 89 </ol> 90 </li> 91 <li>If you are developing in a non-Eclipse environment: Create the following 92 directory {@code /src/com/android/vending/billing} and copy the 93 {@code IInAppBillingService.aidl} file into this directory. Put the AIDL file 94 into your project and use the Ant tool to build your project so that the 95 <code>IInAppBillingService.java</code> file gets generated.</li> 96 </ul> 97 </li> 98 <li>Build your application. You should see a generated file named 99 {@code IInAppBillingService.java} in the {@code /gen} directory of your 100 project.</li> 101 </ol> 102 103 104 <h2 id="billing-permission">Updating Your Application's Manifest</h2> 105 106 <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> 107 108 <p>To give your app the necessary permission, add this line in your {@code Android.xml} manifest file:</p> 109 <pre> 110 <uses-permission android:name="com.android.vending.BILLING" /> 111 </pre> 112 113 <h2 id="billing-service">Creating a ServiceConnection</h2> 114 115 <p>Your application must have a {@link android.content.ServiceConnection} to facilitate messaging between 116 your application and Google Play. At a minimum, your application must do the following:</p> 117 118 <ul> 119 <li>Bind to {@code IInAppBillingService}. 120 <li>Send billing requests (as IPC method calls) to the Google Play application.</li> 121 <li>Handle the synchronous response messages that are returned with each billing request.</li> 122 </ul> 123 124 <h3>Binding to IInAppBillingService</h3> 125 <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 126 android.content.ServiceConnection#onServiceConnected onServiceConnected} methods to get a reference to the {@code IInAppBillingService} instance after a connection has been established.</p> 127 <pre> 128 IInAppBillingService mService; 129 130 ServiceConnection mServiceConn = new ServiceConnection() { 131 @Override 132 public void onServiceDisconnected(ComponentName name) { 133 mService = null; 134 } 135 136 @Override 137 public void onServiceConnected(ComponentName name, 138 IBinder service) { 139 mService = IInAppBillingService.Stub.asInterface(service); 140 } 141 }; 142 </pre> 143 144 <p>In your activitys {@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.</p> 145 <pre> 146 @Override 147 public void onCreate(Bundle savedInstanceState) { 148 super.onCreate(savedInstanceState); 149 setContentView(R.layout.activity_main); 150 bindService(new 151 Intent("com.android.vending.billing.InAppBillingService.BIND"), 152 mServiceConn, Context.BIND_AUTO_CREATE); 153 </pre> 154 <p>You can now use the mService reference to communicate with the Google Play service.</p> 155 <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 dont unbind, the open service connection could cause your devices 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 activitys {@link android.app.Activity#onDestroy onDestroy} method.</p> 156 <pre> 157 @Override 158 public void onDestroy() { 159 super.onDestroy(); 160 if (mServiceConn != null) { 161 unbindService(mServiceConn); 162 } 163 } 164 </pre> 165 166 <p>For a complete implementation of a service connection that binds to the {@code IInAppBillingService}, 167 see the <a href="{@docRoot}training/in-app-billing/preparing-iab-app.html">Selling In-app 168 Products</a> training class and associated sample.</p> 169 170 <h2 id="billing-requests">Making In-app Billing Requests</h2> 171 <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. 172 </p> 173 174 <h3 id="QueryDetails">Querying for Items Available for Purchase</h3> 175 <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> 176 <pre> 177 ArrayList<String> skuList = new ArrayList<String>(); 178 skuList.add("premiumUpgrade"); 179 skuList.add("gas"); 180 Bundle querySkus = new Bundle(); 181 querySkus.putStringArrayList(ITEM_ID_LIST, skuList); 182 </pre> 183 <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> 184 <pre> 185 Bundle skuDetails = mService.getSkuDetails(3, 186 getPackageName(), "inapp", querySkus); 187 </pre> 188 <p>If the request is successful, the returned {@link android.os.Bundle}has a response code of {@code BILLING_RESPONSE_RESULT_OK} (0).</p> 189 <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> 190 191 <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> 192 193 <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> 194 195 <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> 196 <pre> 197 int response = skuDetails.getInt("RESPONSE_CODE"); 198 if (response == 0) { 199 ArrayList<String> responseList 200 = skuDetails.getStringArrayList("DETAILS_LIST"); 201 202 for (String thisResponse : responseList) { 203 JSONObject object = new JSONObject(thisResponse); 204 String sku = object.getString("productId"); 205 String price = object.getString("price"); 206 if (sku.equals("premiumUpgrade")) mPremiumUpgradePrice = price; 207 else if (sku.equals("gas")) mGasPrice = price; 208 } 209 } 210 </pre> 211 212 <h3 id="Purchase">Purchasing an Item</h3> 213 <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> 214 215 <pre> 216 Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(), 217 sku, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ"); 218 </pre> 219 <p> 220 If 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}. 221 </p> 222 <pre> 223 PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT"); 224 </pre> 225 <p> 226 To 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> 227 <pre> 228 startIntentSenderForResult(pendingIntent.getIntentSender(), 229 1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0), 230 Integer.valueOf(0)); 231 </pre> 232 <p>Google Plays 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> 233 234 <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: 235 <pre> 236 '{ 237 "orderId":"12999763169054705758.1371079406387615", 238 "packageName":"com.example.app", 239 "productId":"exampleSku", 240 "purchaseTime":1345678900000, 241 "purchaseState":0, 242 "developerPayload":"bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ", 243 "purchaseToken":"rojeslcdyyiapnqcynkjyyjh" 244 }' 245 </pre> 246 </p> 247 248 <p>Continuing from the previous example, you get the response code, purchase data, and signature from the response {@link android.content.Intent}.</p> 249 <pre> 250 @Override 251 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 252 if (requestCode == 1001) { 253 int responseCode = data.getIntExtra("RESPONSE_CODE", 0); 254 String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA"); 255 String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE"); 256 257 if (resultCode == RESULT_OK) { 258 try { 259 JSONObject jo = new JSONObject(purchaseData); 260 String sku = jo.getString("productId"); 261 alert("You have bought the " + sku + ". Excellent choice, 262 adventurer!"); 263 } 264 catch (JSONException e) { 265 alert("Failed to parse purchase data."); 266 e.printStackTrace(); 267 } 268 } 269 } 270 } 271 </pre> 272 <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> 273 274 <h3 id="QueryPurchases">Querying for Purchased Items</h3> 275 <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> 276 <pre> 277 Bundle ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null); 278 </pre> 279 <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> 280 <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> 281 <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. 282 <pre> 283 int response = ownedItems.getInt("RESPONSE_CODE"); 284 if (response == 0) { 285 ArrayList<String> ownedSkus = 286 ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST"); 287 ArrayList<String> purchaseDataList = 288 ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST"); 289 ArrayList<String> signatureList = 290 ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE"); 291 String continuationToken = 292 ownedItems.getString("INAPP_CONTINUATION_TOKEN"); 293 294 for (int i = 0; i < purchaseDataList.size(); ++i) { 295 String purchaseData = purchaseDataList.get(i); 296 String signature = signatureList.get(i); 297 String sku = ownedSkus.get(i); 298 299 // do something with this purchase information 300 // e.g. display the updated list of products owned by user 301 } 302 303 // if continuationToken != null, call getPurchases again 304 // and pass in the token to retrieve more items 305 } 306 307 </pre> 308 309 <h3 id="Consume">Consuming a Purchase</h3> 310 <p>You can use the In-app Billing Version 3 API to track the ownership of 311 purchased in-app products in Google Play. Once an in-app product is purchased, 312 it is considered to be "owned" and cannot be purchased from Google Play. You 313 must send a consumption request for the in-app product before Google Play makes 314 it available for purchase again.</p> 315 <p class="caution"><strong>Important</strong>: Managed in-app products are 316 consumable, but subscriptions are not.</p> 317 <p>How you use the consumption mechanism in your app is up to you. Typically, 318 you would implement consumption for in-app products with temporary benefits that 319 users may want to purchase multiple times (for example, in-game currency or 320 equipment). You would typically not want to implement consumption for in-app 321 products that are purchased once and provide a permanent effect (for example, 322 a premium upgrade).</p> 323 <p>To record a purchase consumption, send the {@code consumePurchase} method to 324 the In-app Billing service and pass in the {@code purchaseToken} String value 325 that identifies the purchase to be removed. The {@code purchaseToken} is part 326 of the data returned in the {@code INAPP_PURCHASE_DATA} String by the Google 327 Play service following a successful purchase request. In this example, you are 328 recording the consumption of a product that is identified with the 329 {@code purchaseToken} in the {@code token} variable.</p> 330 <pre> 331 int response = mService.consumePurchase(3, getPackageName(), token); 332 </pre> 333 <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> 334 <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> 335 <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> 336 337 <h3 id="Subs">Implementing Subscriptions</h3> 338 <p>Launching a purchase flow for a subscription is similar to launching the 339 purchase flow for a product, with the exception that the product type must be set 340 to "subs". The purchase result is delivered to your Activity's 341 {@link android.app.Activity#onActivityResult onActivityResult} method, exactly 342 as in the case of in-app products.</p> 343 <pre> 344 Bundle bundle = mService.getBuyIntent(3, "com.example.myapp", 345 MY_SKU, "subs", developerPayload); 346 347 PendingIntent pendingIntent = bundle.getParcelable(RESPONSE_BUY_INTENT); 348 if (bundle.getInt(RESPONSE_CODE) == BILLING_RESPONSE_RESULT_OK) { 349 // Start purchase flow (this brings up the Google Play UI). 350 // Result will be delivered through onActivityResult(). 351 startIntentSenderForResult(pendingIntent, RC_BUY, new Intent(), 352 Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0)); 353 } 354 </pre> 355 <p>To query for active subscriptions, use the {@code getPurchases} method, again 356 with the product type parameter set to "subs".</p> 357 <pre> 358 Bundle activeSubs = mService.getPurchases(3, "com.example.myapp", 359 "subs", continueToken); 360 </pre> 361 <p>The call returns a {@code Bundle} with all the active subscriptions owned by 362 the user. Once a subscription expires without renewal, it will no longer appear 363 in the returned {@code Bundle}.</p> 364 365 <h2 id="billing-security">Securing Your Application</h2> 366 367 <p>To help ensure the integrity of the transaction information that is sent to 368 your application, Google Play signs the JSON string that contains the response 369 data for a purchase order. Google Play uses the private key that is associated 370 with your application in the Developer Console to create this signature. The 371 Developer Console generates an RSA key pair for each application.<p> 372 373 <p class="note"><strong>Note:</strong>To find the public key portion of this key 374 pair, open your application's details in the Developer Console, then click on 375 <strong>Services & APIs</strong>, and look at the field titled 376 <strong>Your License Key for This Application</strong>.</p> 377 378 <p>The Base64-encoded RSA public key generated by Google Play is in binary 379 encoded, X.509 subjectPublicKeyInfo DER SEQUENCE format. It is the same public 380 key that is used with Google Play licensing.</p> 381 382 <p>When your application receives this signed response you can 383 use the public key portion of your RSA key pair to verify the signature. 384 By performing signature verification you can detect responses that have 385 been tampered with or that have been spoofed. You can perform this signature 386 verification step in your application; however, if your application connects 387 to a secure remote server then we recommend that you perform the signature 388 verification on that server.</p> 389 390 <p>For more information about best practices for security and design, see <a 391 href="{@docRoot}google/play/billing/billing_best_practices.html">Security and Design</a>.</p> 392 393 394 395 396 397 398 399 400 401