Purchasing an Item
To start a purchase request from your app, call the 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 developerPayload
String. The developerPayload
String is used to specify any additional arguments that you want Google Play to send back along with the purchase information.
Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(), sku, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");
If the request is successful, the returned Bundle
has a response code of BILLING_RESPONSE_RESULT_OK
(0) and aPendingIntent
that you can use to start the purchase flow. To see all the possible response codes from Google Play, see In-app Billing Reference. Next, extract a PendingIntent
from the response Bundle
with key BUY_INTENT
.
PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
To complete the purchase transaction, call the startIntentSenderForResult
method and use the PendingIntent
that you created. In this example, you are using an arbitrary value of 1001 for the request code.
startIntentSenderForResult(pendingIntent.getIntentSender(), 1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
Google Plays sends a response to your PendingIntent
to the onActivityResult
method of your application. TheonActivityResult
method will have a result code of Activity.RESULT_OK
(1) or Activity.RESULT_CANCELED
(0). To see the types of order information that is returned in the response Intent
, see In-app Billing Reference.
The purchase data for the order is a String in JSON format that is mapped to the INAPP_PURCHASE_DATA
key in the response Intent
, for example:
'{
"orderId":"12999763169054705758.1371079406387615",
"packageName":"com.example.app",
"productId":"exampleSku",
"purchaseTime":1345678900000,
"purchaseState":0,
"developerPayload":"bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ",
"purchaseToken":"rojeslcdyyiapnqcynkjyyjh"
}'
Continuing from the previous example, you get the response code, purchase data, and signature from the response Intent
.
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1001) { int responseCode = data.getIntExtra("RESPONSE_CODE", 0); String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA"); String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE"); if (resultCode == RESULT_OK) { try { JSONObject jo = new JSONObject(purchaseData); String sku = jo.getString("productId"); alert("You have bought the " + sku + ". Excellent choice, adventurer!"); } catch (JSONException e) { alert("Failed to parse purchase data."); e.printStackTrace(); } } } }