1 page.title=Implementing In-app Billing 2 parent.title=In-app Billing 3 parent.link=index.html 4 page.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 46 concepts 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 49 following:</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 63 Language (AIDL) file that defines the interface to the In-app Billing Version 64 3 service. You will use this interface to make billing requests by invoking IPC 65 method 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 82 in Eclipse. If you are creating a new Android project from scratch, click 83 <strong>File</strong> > <strong>New</strong> > <strong>Android Application 84 Project</strong>, then follow the instructions in the <strong>New Android 85 Application</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/} 89 folder in your workspace.</li> 90 </ol> 91 </li> 92 <li>If you are developing in a non-Eclipse environment: Create the following 93 directory {@code /src/com/android/vending/billing} and copy the 94 {@code IInAppBillingService.aidl} file into this directory. Put the AIDL file 95 into 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 101 project.</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 117 your 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 127 android.content.ServiceConnection#onServiceConnected onServiceConnected} methods to get a reference to the {@code IInAppBillingService} instance after a connection has been established.</p> 128 <pre> 129 IInAppBillingService mService; 130 131 ServiceConnection 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 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, 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 150 public 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 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> 159 <pre> 160 @Override 161 public 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}, 170 see the <a href="{@docRoot}training/in-app-billing/preparing-iab-app.html">Selling In-app 171 Products</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> 180 ArrayList<String> skuList = new ArrayList<String> (); 181 skuList.add("premiumUpgrade"); 182 skuList.add("gas"); 183 Bundle querySkus = new Bundle(); 184 querySkus.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> 188 Bundle 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> 200 int response = skuDetails.getInt("RESPONSE_CODE"); 201 if (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> 219 Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(), 220 sku, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ"); 221 </pre> 222 <p> 223 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}. 224 </p> 225 <pre> 226 PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT"); 227 </pre> 228 <p> 229 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> 230 <pre> 231 startIntentSenderForResult(pendingIntent.getIntentSender(), 232 1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0), 233 Integer.valueOf(0)); 234 </pre> 235 <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> 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":"rojeslcdyyiapnqcynkjyyjh" 247 }' 248 </pre> 249 </p> 250 251 <p>Continuing from the previous example, you get the response code, purchase data, and signature from the response {@link android.content.Intent}.</p> 252 <pre> 253 @Override 254 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 255 if (requestCode == 1001) { 256 int responseCode = data.getIntExtra("RESPONSE_CODE", 0); 257 String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA"); 258 String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE"); 259 260 if (resultCode == RESULT_OK) { 261 try { 262 JSONObject jo = new JSONObject(purchaseData); 263 String sku = jo.getString("productId"); 264 alert("You have bought the " + sku + ". Excellent choice, 265 adventurer!"); 266 } 267 catch (JSONException e) { 268 alert("Failed to parse purchase data."); 269 e.printStackTrace(); 270 } 271 } 272 } 273 } 274 </pre> 275 <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> 276 277 <h3 id="QueryPurchases">Querying for Purchased Items</h3> 278 <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> 279 <pre> 280 Bundle ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null); 281 </pre> 282 <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> 283 <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> 284 <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. 285 <pre> 286 int response = ownedItems.getInt("RESPONSE_CODE"); 287 if (response == 0) { 288 ArrayList<String> ownedSkus = 289 ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST"); 290 ArrayList<String> purchaseDataList = 291 ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST"); 292 ArrayList<String> signatureList = 293 ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE"); 294 String continuationToken = 295 ownedItems.getString("INAPP_CONTINUATION_TOKEN"); 296 297 for (int i = 0; i < purchaseDataList.size(); ++i) { 298 String purchaseData = purchaseDataList.get(i); 299 String signature = signatureList.get(i); 300 String sku = ownedSkus.get(i); 301 302 // do something with this purchase information 303 // e.g. display the updated list of products owned by user 304 } 305 306 // if continuationToken != null, call getPurchases again 307 // and pass in the token to retrieve more items 308 } 309 310 </pre> 311 312 <h3 id="Consume">Consuming a Purchase</h3> 313 <p>You can use the In-app Billing Version 3 API to track the ownership of 314 purchased in-app products in Google Play. Once an in-app product is purchased, 315 it is considered to be "owned" and cannot be purchased from Google Play. You 316 must send a consumption request for the in-app product before Google Play makes 317 it available for purchase again.</p> 318 <p class="caution"><strong>Important</strong>: Managed in-app products are 319 consumable, but subscriptions are not.</p> 320 <p>How you use the consumption mechanism in your app is up to you. Typically, 321 you would implement consumption for in-app products with temporary benefits that 322 users may want to purchase multiple times (for example, in-game currency or 323 equipment). You would typically not want to implement consumption for in-app 324 products that are purchased once and provide a permanent effect (for example, 325 a premium upgrade).</p> 326 <p>To record a purchase consumption, send the {@code consumePurchase} method to 327 the In-app Billing service and pass in the {@code purchaseToken} String value 328 that identifies the purchase to be removed. The {@code purchaseToken} is part 329 of the data returned in the {@code INAPP_PURCHASE_DATA} String by the Google 330 Play service following a successful purchase request. In this example, you are 331 recording the consumption of a product that is identified with the 332 {@code purchaseToken} in the {@code token} variable.</p> 333 <pre> 334 int response = mService.consumePurchase(3, getPackageName(), token); 335 </pre> 336 <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> 337 <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> 338 <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> 339 340 <h3 id="Subs">Implementing Subscriptions</h3> 341 <p>Launching a purchase flow for a subscription is similar to launching the 342 purchase flow for a product, with the exception that the product type must be set 343 to "subs". The purchase result is delivered to your Activity's 344 {@link android.app.Activity#onActivityResult onActivityResult} method, exactly 345 as in the case of in-app products.</p> 346 <pre> 347 Bundle bundle = mService.getBuyIntent(3, "com.example.myapp", 348 MY_SKU, "subs", developerPayload); 349 350 PendingIntent pendingIntent = bundle.getParcelable(RESPONSE_BUY_INTENT); 351 if (bundle.getInt(RESPONSE_CODE) == BILLING_RESPONSE_RESULT_OK) { 352 // Start purchase flow (this brings up the Google Play UI). 353 // Result will be delivered through onActivityResult(). 354 startIntentSenderForResult(pendingIntent, RC_BUY, new Intent(), 355 Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0)); 356 } 357 </pre> 358 <p>To query for active subscriptions, use the {@code getPurchases} method, again 359 with the product type parameter set to "subs".</p> 360 <pre> 361 Bundle activeSubs = mService.getPurchases(3, "com.example.myapp", 362 "subs", continueToken); 363 </pre> 364 <p>The call returns a {@code Bundle} with all the active subscriptions owned by 365 the user. Once a subscription expires without renewal, it will no longer appear 366 in the returned {@code Bundle}.</p> 367 368 <h2 id="billing-security">Securing Your Application</h2> 369 370 <p>To help ensure the integrity of the transaction information that is sent to 371 your application, Google Play signs the JSON string that contains the response 372 data for a purchase order. Google Play uses the private key that is associated 373 with your application in the Developer Console to create this signature. The 374 Developer Console generates an RSA key pair for each application.<p> 375 376 <p class="note"><strong>Note:</strong>To find the public key portion of this key 377 pair, open your application's details in the Developer Console, then click on 378 <strong>Services & APIs</strong>, and look at the field titled 379 <strong>Your License Key for This Application</strong>.</p> 380 381 <p>The Base64-encoded RSA public key generated by Google Play is in binary 382 encoded, X.509 subjectPublicKeyInfo DER SEQUENCE format. It is the same public 383 key that is used with Google Play licensing.</p> 384 385 <p>When your application receives this signed response you can 386 use the public key portion of your RSA key pair to verify the signature. 387 By performing signature verification you can detect responses that have 388 been tampered with or that have been spoofed. You can perform this signature 389 verification step in your application; however, if your application connects 390 to a secure remote server then we recommend that you perform the signature 391 verification on that server.</p> 392 393 <p>For more information about best practices for security and design, see <a 394 href="{@docRoot}google/play/billing/billing_best_practices.html">Security and Design</a>.</p> 395 396 397 398 399 400 401 402 403 404