1page.title=Implementing In-app Billing <span style="font-size:16px;">(IAB Version 3)</span>
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-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       </ol>
20    </li>
21  </ol>
22  <h2>Reference</h2>
23  <ol>
24    <li><a href="{@docRoot}google/play/billing/billing_reference.html">In-app Billing
25    Reference (V3)</a></li>
26  </ol>
27  <h2>Related Samples</h2>
28  <ol>
29    <li><a href="{@docRoot}training/in-app-billing/preparing-iab-app.html#GetSample">Sample Application (V3)</a></li>
30  </ol>
31  <h2>See also</h2>
32  <ol>
33    <li><a href="{@docRoot}training/in-app-billing/index.html">Selling In-app Products</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 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>
39
40<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>
41
42<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 concepts that will make it easier for you to implement In-app Billing.</p>
43
44<p>To implement In-app Billing in your application, you need to do the following:</p>
45<ol>
46  <li>Add the In-app Billing library to your project.</li>
47  <li>Update your {@code AndroidManifest.xml} file.</li>
48  <li>Create a {@code ServiceConnection} and bind it to {@code IInAppBillingService}.</li>
49  <li>Send In-app Billing requests from your application to {@code IInAppBillingService}.</li>
50  <li>Handle In-app Billing responses from Google Play.</li>
51</ol>
52
53<h2 id="billing-add-aidl">Adding the AIDL file to your project</h2>
54
55<p>The {@code TriviaDriva} sample application contains an Android Interface Definition Language (AIDL) file which defines the interface to Google Play's In-app Billing service. When you add this file to your project, the Android build environment creates an interface file (<code>IIAppBillingService.java</code>). You can then use this interface to make billing requests by invoking IPC method calls.</p>
56
57<p>To add the In-app Billing Version 3 library to your project:</p>
58<ol>
59<li>Copy the {@code IInAppBillingService.aidl} file to your Android project.
60  <ul>
61  <li>If you are using Eclipse: Import the {@code IInAppBillingService.aidl} file into your {@code /src} directory. Eclipse automatically generates the interface file when you build your project.</li>
62  <li>If you are developing in a non-Eclipse environment: Create the following directory {@code /src/com/android/vending/billing} and copy the {@code IInAppBillingService.aidl} file into this directory. Put the AIDL file into your project and use the Ant tool to build your project so that the
63<code>IInAppBillingService.java</code> file gets generated.</li>
64  </ul>
65</li>
66<li>Build your application. You should see a generated file named {@code IInAppBillingService.java} in the {@code /gen} directory of your project.</li>
67</ol>
68
69
70<h2 id="billing-permission">Updating Your Application's Manifest</h2>
71
72<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>
73
74<p>To give your app the necessary permission, add this line in your {@code Android.xml} manifest file:</p>
75<pre>
76&lt;uses-permission android:name="com.android.vending.BILLING" /&gt;
77</pre>
78
79<h2 id="billing-service">Creating a ServiceConnection</h2>
80
81<p>Your application must have a {@link android.content.ServiceConnection} to facilitate messaging between
82your application and Google Play. At a minimum, your application must do the following:</p>
83
84<ul>
85  <li>Bind to {@code IInAppBillingService}.
86  <li>Send billing requests (as IPC method calls) to the Google Play application.</li>
87  <li>Handle the synchronous response messages that are returned with each billing request.</li>
88</ul>
89
90<h3>Binding to IInAppBillingService</h3>
91<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
92android.content.ServiceConnection#onServiceConnected onServiceConnected} methods to get a reference to the {@code IInAppBillingService} instance after a connection has been established.</p>
93<pre>
94IInAppBillingService mService;
95
96ServiceConnection mServiceConn = new ServiceConnection() {
97   &#64;Override
98   public void onServiceDisconnected(ComponentName name) {
99       mService = null;
100   }
101
102   &#64;Override
103   public void onServiceConnected(ComponentName name, 
104      IBinder service) {
105       mService = IInAppBillingService.Stub.asInterface(service);
106   }
107};
108</pre>
109
110<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.</p>
111<pre>
112&#64;Override
113public void onCreate(Bundle savedInstanceState) {    
114    super.onCreate(savedInstanceState);
115    setContentView(R.layout.activity_main);        
116    bindService(new 
117        Intent("com.android.vending.billing.InAppBillingService.BIND"),
118                mServiceConn, Context.BIND_AUTO_CREATE);
119</pre>
120<p>You can now use the mService reference to communicate with the Google Play service.</p>
121<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>
122<pre>
123&#64;Override
124public void onDestroy() {
125    super.onDestroy();
126    if (mServiceConn != null) {
127        unbindService(mServiceConn);
128    }	
129}
130</pre>
131
132<p>For a complete implementation of a service connection that binds to the {@code IInAppBillingService},
133see the <a href="{@docRoot}training/in-app-billing/preparing-iab-app.html">Selling In-app
134Products</a> training class and associated sample.</p>
135
136<h2 id="billing-requests">Making In-app Billing Requests</h2>
137<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.
138</p>
139
140<h3 id="QueryDetails">Querying for Items Available for Purchase</h3>
141<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>
142<pre>
143ArrayList<String> skuList = new ArrayList<String>();
144skuList.add("premiumUpgrade");
145skuList.add("gas");
146Bundle querySkus = new Bundle();
147querySkus.putStringArrayList(âITEM_ID_LISTâ, skuList);
148</pre>
149<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>
150<pre>
151Bundle skuDetails = mService.getSkuDetails(3, 
152   getPackageName(), "inapp", querySkus);
153</pre>
154<p>If the request is successful, the returned {@link android.os.Bundle}has a response code of {@code BILLING_RESPONSE_RESULT_OK} (0).</p>
155<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>
156
157<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>  
158
159<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>
160
161<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>
162<pre>
163int response = skuDetails.getInt("RESPONSE_CODE");
164if (response == 0) {
165   ArrayList<String> responseList 
166      = skuDetails.getStringArrayList("DETAILS_LIST");
167   
168   for (String thisResponse : responseList) {
169      JSONObject object = new JSONObject(thisResponse);
170      String sku = object.getString("productId");
171      String price = object.getString("price");
172      if (sku.equals("premiumUpgrade")) mPremiumUpgradePrice = price;
173      else if (sku.equals("gas")) mGasPrice = price;
174   }
175}
176</pre>
177
178<h3 id="Purchase">Purchasing an Item</h3>
179<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â), 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>
180
181<pre>
182Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(),
183   sku, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");
184</pre>
185<p>
186If 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}.
187</p>
188<pre>
189PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
190</pre>
191<p>
192To 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>
193<pre>
194startIntentSenderForResult(pendingIntent.getIntentSender(),
195   1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0),
196   Integer.valueOf(0));
197</pre>
198<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> 
199
200<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:
201<pre>
202'{ 
203   "orderId":"12999763169054705758.1371079406387615", 
204   "packageName":"com.example.app",
205   "productId":"exampleSku",
206   "purchaseTime":1345678900000,
207   "purchaseState":0,
208   "developerPayload":"bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ",
209   "purchaseToken":"rojeslcdyyiapnqcynkjyyjh"
210 }'
211</pre>
212</p>
213
214<p>Continuing from the previous example, you get the response code, purchase data, and signature from the response {@link android.content.Intent}.</p>
215<pre>
216&#64;Override
217protected void onActivityResult(int requestCode, int resultCode, Intent data) {	
218   if (requestCode == 1001) {    	
219      int responseCode = data.getIntExtra("RESPONSE_CODE", 0);
220      String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
221      String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");
222        
223      if (resultCode == RESULT_OK) {
224         try {
225            JSONObject jo = new JSONObject(purchaseData);
226            String sku = jo.getString("productId");
227            alert("You have bought the " + sku + ". Excellent choice, 
228               adventurer!");
229          }
230          catch (JSONException e) {
231             alert("Failed to parse purchase data.");
232             e.printStackTrace();
233          }
234      }
235   }
236}
237</pre>
238<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>
239
240<h3 id="QueryPurchases">Querying for Purchased Items</h3>
241<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â).</p>
242<pre>
243Bundle ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);
244</pre>
245<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>
246<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>
247<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.
248<pre>
249int response = ownedItems.getInt("RESPONSE_CODE");
250if (response == 0) {
251   ArrayList<String> ownedSkus = 
252      ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
253   ArrayList<String> purchaseDataList = 
254      ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
255   ArrayList<String> signatureList = 
256      ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE");
257   String continuationToken = 
258      ownedItems.getString("INAPP_CONTINUATION_TOKEN");
259   
260   for (int i = 0; i < purchaseDataList.size(); ++i) {
261      String purchaseData = purchaseDataList.get(i);
262      String signature = signatureList.get(i);
263      String sku = ownedSkus.get(i);
264  
265      // do something with this purchase information
266      // e.g. display the updated list of products owned by user
267   } 
268
269   // if continuationToken != null, call getPurchases again 
270   // and pass in the token to retrieve more items
271}
272
273</pre>
274
275<h3 id="Consume">Consuming a Purchase</h3>
276<p>You can use the In-app Billing Version 3 API to track the ownership of purchased items in Google Play. Once an item is purchased, it is considered to be "owned" and cannot be purchased from Google Play. You must send a consumption request for the item before Google Play makes it available for purchase again. All managed in-app products are consumable.  How you use the consumption mechanism in your app is up to you. Typically, you would implement consumption for products with temporary benefits that users may want to purchase multiple times (for example, in-game currency or equipment). You would typically not want to implement consumption for products that are purchased once and provide a permanent effect (for example, a premium upgrade).</p>
277<p>To record a purchase consumption, send the {@code consumePurchase} method to the In-app Billing service and pass in the {@code purchaseToken} String value that identifies the purchase to be removed. The {@code purchaseToken} is part of the data returned in the {@code INAPP_PURCHASE_DATA} String by the Google Play service following a successful purchase request. In this example, you are recording the consumption of a product that is identified with the {@code purchaseToken} in the {@code token} variable.</p>
278<pre>
279int response = mService.consumePurchase(3, getPackageName(), token);
280</pre>
281<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>
282<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>
283<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>
284
285
286
287
288
289
290
291
292
293
294