{"id":24960,"date":"2015-08-06T13:17:01","date_gmt":"2015-08-06T07:47:01","guid":{"rendered":"http:\/\/www.tothenew.com\/blog\/?p=24960"},"modified":"2024-01-02T17:48:48","modified_gmt":"2024-01-02T12:18:48","slug":"inapppurchase-in-android","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/inapppurchase-in-android\/","title":{"rendered":"InAppPurchase in Android"},"content":{"rendered":"<p><strong>InAppPurchase,\u00a0<\/strong>as the name suggests is for purchasing items from within the application i.e., it allows you to put a price tag on your products and sell them in the market using your Android application.<\/p>\n<p>Integration of InAppPurchase in android can be achieved in few steps as follows:<\/p>\n<p>1.\u00a0 The very first you need to do is install Google Play billing library in SDK, check if your SDK has \u00a0billing package, open SDK manager-&gt;extras-&gt;Google Play Billing. If it&#8217;s not installed, then check it and click install.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-25218\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/08\/Screenshot-from-2015-08-04-141738.png\" alt=\"Screenshot from 2015-08-04 14:17:38\" width=\"667\" height=\"365\" \/><\/p>\n<p>2.\u00a0 After Installation, inside SDK-&gt;Extras-&gt;Google-&gt;play_billing folder resides a file i.e., IInAppBillingService.aidl that needs to include with the project that require Google Play billing support. Also there is a sample application present at path samples\/TrivialDrive\/src\/com\/example\/android\/trivialdrivesample\/util which consists of classes inside Util folder which will ease the Integration of billing into the application.<\/p>\n<p>3.\u00a0 To get support of inAppBilling you must have following permission in Manifest file.<\/p>\n<p>[sourcecode language=&#8221;java&#8221;]<br \/>\n&lt;uses-permission android:name=&quot;com.android.vending.BILLING&quot;\/&gt;<br \/>\n[\/sourcecode]<\/p>\n<p style=\"text-align: left;\">4.\u00a0 Next Step is to add IInAppBillingService.aidl to the project.<br \/>\nCreate a new aidl Folder inside src , inside folder create a package com.android.vending.billing and place IInAppBillingService.aidl here.<\/p>\n<p style=\"text-align: left;\"><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-25222\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/08\/Screenshot-from-2015-08-06-121734.png\" alt=\"Screenshot from 2015-08-06 12:17:34\" width=\"426\" height=\"572\" \/><\/p>\n<p style=\"text-align: left;\">5.\u00a0 After that go to path SDK\/Extras\/google\/play_billing\/samples\/TrivialDrive\/src\/com\/example\/android\/trivialdrivesample\/util and copy all nine files and Create a new Package inside project-&gt;src-&gt;java-&gt;inappbilling\/util and place all nine files there.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-25220\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/08\/Screenshot-from-2015-08-06-120701.png\" alt=\"Screenshot from 2015-08-06 12:07:01\" width=\"420\" height=\"626\" \/><\/p>\n<p>6.\u00a0 Now to start the Billing service you need an unique public licence key. To obtain public license key you need to register your application within the Google Play Developer Console. Visit http:\/\/play.google.com\/apps\/publish.<\/p>\n<p>7.\u00a0 On the home page of Google developer console click Add new application, choose language, enter title and then click upload Apk.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-25229\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/08\/Screenshot-from-2015-08-06-122539.png\" alt=\"Screenshot from 2015-08-06 12:25:39\" width=\"612\" height=\"349\" \/><\/p>\n<p>8.\u00a0 After the application has been registered, click on Services &amp; APIs section to display the Base64-encoded public licence key for the application.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-25230\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/08\/Screenshot-from-2015-08-06-122840.png\" alt=\"Screenshot from 2015-08-06 12:28:40\" width=\"1287\" height=\"546\" \/><\/p>\n<p>9.\u00a0 After having the licence key, create a new BillingActivity extends Activity and initialize billing process as follows:<\/p>\n<p>[sourcecode language=&#8221;java&#8221;]<\/p>\n<p>public class InAppBillingActivity extends Activity{<\/p>\n<p>    Button mButtonBuy;<br \/>\n    private static final String TAG =<br \/>\n            &quot;com.sampleproject.inappbilling&quot;;<br \/>\n    IabHelper mHelper;<br \/>\n    static final String ITEM_SKU = &quot;product_id&quot;;<br \/>\n    IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener;<br \/>\n    IabHelper.OnConsumeFinishedListener mConsumeFinishedListener;<\/p>\n<p>    @Override<br \/>\n    protected void onCreate(Bundle savedInstanceState) {<br \/>\n        super.onCreate(savedInstanceState);<br \/>\n        setContentView(R.layout.activity_in_app_billing);<br \/>\n        mButtonBuy = (Button) findViewById(R.id.button_buy);<br \/>\n        mButtonBuy.setEnabled(true);<br \/>\n        String base64EncodedPublicKey = &quot;PUT YOUR LICENCE KEY HERE&quot;;<\/p>\n<p>        mHelper = new IabHelper(this, base64EncodedPublicKey);<br \/>\n        mHelper.startSetup(new<br \/>\n                                   IabHelper.OnIabSetupFinishedListener() {<br \/>\n                                       public void onIabSetupFinished(IabResult result) {<br \/>\n                                           if (!result.isSuccess()) {<br \/>\n                                               Log.d(TAG, &quot;Billing setup failed&quot; +<br \/>\n                                                       result);<br \/>\n                                           } else {<br \/>\n                                               Log.d(TAG, &quot;Billing is ok&quot;);<br \/>\n                                           }<br \/>\n                                       }<br \/>\n                                   });<\/p>\n<p>    }<br \/>\n}<\/p>\n<p>[\/sourcecode]<\/p>\n<p>10.\u00a0 Run your app on physical Android device (Not on emulator) and make sure that you are getting &#8220;Billing setup ok&#8221; message on logcat. After that, create products on Google developer console, which needs to sell within the application as follows:<\/p>\n<p>11.\u00a0 To create Products, you need to upload a signed apk of your app. So generate a signed apk of your app from Android studio and upload it in alpha or beta testing.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-25231\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/08\/Screenshot-from-2015-08-06-123203.png\" alt=\"Screenshot from 2015-08-06 12:32:03\" width=\"1115\" height=\"524\" \/><br \/>\n12.\u00a0 Now Select option InAPP products and click Add new Product and it will ask you &#8211; What\u00a0 type of product would you like to add? (Managed or subscription).<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-25232\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/08\/Screenshot-from-2015-08-06-123510.png\" alt=\"Screenshot from 2015-08-06 12:35:10\" width=\"601\" height=\"402\" \/><\/p>\n<ul>\n<li>Managed are the items that can be purchased only once per user account on Google Play. Google Play permanently stores the transaction information for each item on a per-user basis.<\/li>\n<li>Subscriptions let you sell content, services or features in your app with automated, recurring billing.<\/li>\n<\/ul>\n<p>13.\u00a0 Give it a product id and continue to fill the details of your product. Save and activate.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-25233\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/08\/Screenshot-from-2015-08-06-123650.png\" alt=\"Screenshot from 2015-08-06 12:36:50\" width=\"1219\" height=\"492\" \/><\/p>\n<p>14. \u00a0 Now place a buy button inside activity_billing.xml as<\/p>\n<p>[sourcecode language=&#8221;java&#8221;]<\/p>\n<p>&lt;Button<br \/>\nandroid:layout_width=&quot;wrap_content&quot;<br \/>\nandroid:layout_height=&quot;wrap_content&quot;<br \/>\nandroid:text=&quot;@string\/buy_string&quot;<br \/>\nandroid:id=&quot;@+id\/buyButton&quot;<br \/>\nandroid:layout_centerVertical=&quot;true&quot;<br \/>\nandroid:layout_centerHorizontal=&quot;true&quot;<br \/>\nandroid:onClick=&quot;buyClick&quot;\/&gt;;<\/p>\n<p> [\/sourcecode]<\/p>\n<p>15.\u00a0 Click of button will call buyClick() and buyclick will have :<\/p>\n<p>[sourcecode language=&#8221;java&#8221;]<br \/>\npublic void buyClick(View view) {<br \/>\nmHelper.launchPurchaseFlow(this, PRODUCT_ID, 10001,<br \/>\nmPurchaseFinishedListener, &quot;mypurchasetoken&quot;);<br \/>\n}<br \/>\n  [\/sourcecode]<\/p>\n<p>it will have five parameters i.e<\/p>\n<ul>\n<li>The first argument is the calling <code>Activity<\/code>.<\/li>\n<li>The second argument is the product ID (also called its SKU) of the item to purchase.<\/li>\n<li>The third argument is a request code value. This value can be any positive integer. Google Play returns this request code to the calling <code>Activity<\/code>\u2019s <code>onActivityResult<\/code> along with the purchase response.<\/li>\n<li>The fourth argument is a listener that is notified when the purchase operation has completed and handles the purchase response from Google Play.<\/li>\n<li>Last is the token for the identification of the product.<\/li>\n<\/ul>\n<p>This will launch the purchase flow with the entered product_id and after finishing it will invoke the purchsedFinishedlistener.i.e:<\/p>\n<p>[sourcecode language=&#8221;java&#8221;]<\/p>\n<p>IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener<br \/>\n= new IabHelper.OnIabPurchaseFinishedListener() {<br \/>\npublic void onIabPurchaseFinished(IabResult result,<br \/>\nPurchase purchase)<br \/>\n{<br \/>\nif (result.isFailure()) {<br \/>\n\/\/ Handle error<br \/>\nreturn;<br \/>\n}<br \/>\nelse if (purchase.getSku().equals(ITEM_SKU)) {<br \/>\nconsumeItem();<br \/>\nbuyButton.setEnabled(false);<br \/>\n}<\/p>\n<p>}<br \/>\n};<\/p>\n<p>  [\/sourcecode]<\/p>\n<p>The purchase finished listener checks the success of the purchase, it also matches the SKU(Product_Id) of the purchased item with the one specified in the purchase request. On success, you should consume the purchase to allow the user to buy it again.<\/p>\n<p>If the purchase is successful it will invoke method consumeItem() which will be like:<\/p>\n<p>[sourcecode language=&#8221;java&#8221;]<br \/>\npublic void consumeItem() {<br \/>\nmHelper.queryInventoryAsync(mReceivedInventoryListener);<br \/>\n}<\/p>\n<p>IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener<br \/>\n= new IabHelper.QueryInventoryFinishedListener() {<br \/>\npublic void onQueryInventoryFinished(IabResult result,<br \/>\nInventory inventory) {<\/p>\n<p>if (result.isFailure()) {<br \/>\n\/\/ Handle failure<br \/>\n} else {<br \/>\nmHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),<br \/>\nmConsumeFinishedListener);<br \/>\n}<br \/>\n}<br \/>\n};<\/p>\n<p>  [\/sourcecode]<\/p>\n<p>Now method consumeItem() will query the billing system to make sure that the purchase has been made. if it&#8217;s successful then it will call the queryInventoryAsync() method of the mHelper object. ReceivedInventoryListener is notified when the query operation has completed and handles the query response. It is safe to make this call from your main thread.<\/p>\n<p>If the item has been purchased, the listener will consume the item via a call to the consumeAsync() method of the mHelper object.<\/p>\n<p>On finished consumption, it will invoke the consumeFinishedListener:<\/p>\n<p>[sourcecode language=&#8221;java&#8221;]<\/p>\n<p>IabHelper.OnConsumeFinishedListener mConsumeFinishedListener =<br \/>\nnew IabHelper.OnConsumeFinishedListener() {<br \/>\npublic void onConsumeFinished(Purchase purchase,<br \/>\nIabResult result) {<\/p>\n<p>if (result.isSuccess()) {<br \/>\nsuccess message<br \/>\n} else {<br \/>\n\/\/ handle error<br \/>\n}<br \/>\n}<br \/>\n};<br \/>\n  [\/sourcecode]<\/p>\n<p>16.\u00a0 So this will be the flow. Now open Security.java file present at path src\/main\/java\/InappBilling\/util to check whether the purchase is made from valid signature key, which is returned from the Google Play billing server and modify the verifyPurchase() as follows:<\/p>\n<p>[sourcecode language=&#8221;java&#8221;]<br \/>\npublic static boolean verifyPurchase(String base64PublicKey,<br \/>\nString signedData, String signature) {<br \/>\nif (TextUtils.isEmpty(signedData) ||<br \/>\nTextUtils.isEmpty(base64PublicKey) ||<br \/>\nTextUtils.isEmpty(signature)) {<br \/>\nLog.e(TAG, &quot;Purchase verification failed: missing data.&quot;);<br \/>\nif (BuildConfig.DEBUG) {<br \/>\nreturn true;<br \/>\n}<br \/>\nreturn false;<br \/>\n}<\/p>\n<p>PublicKey key = Security.generatePublicKey(base64PublicKey);<br \/>\nreturn Security.verify(key, signedData, signature);<br \/>\n}<\/p>\n<p>  [\/sourcecode]<\/p>\n<p>This will ensure that when the application is running in debug mode the method does not report an error if the signature is missing when a static response SKU purchase is verified. By checking for debug mode in this code, we ensure that this security check will function as intended when the application is built in release mode.<\/p>\n<p>17.\u00a0 Now Go back to Google Developer console and select APK section.<br \/>\nFor testing the flow, click Manage list of testers. This will ask for Google community. So create a Google Plus community and share the link of app with the community members.<\/p>\n<p><strong>Note<\/strong>: For more details, visit http:\/\/developer.android.com\/google\/play\/billing\/billing_overview.html<\/p>\n<p><span id=\"hs-cta-wrapper-1bf6c096-779b-423a-8642-4bab9532eb73\" class=\"hs-cta-wrapper\"><span id=\"hs-cta-1bf6c096-779b-423a-8642-4bab9532eb73\" class=\"hs-cta-node hs-cta-1bf6c096-779b-423a-8642-4bab9532eb73\"><a href=\"http:\/\/cta-redirect.hubspot.com\/cta\/redirect\/481864\/1bf6c096-779b-423a-8642-4bab9532eb73\"><img decoding=\"async\" id=\"hs-cta-img-1bf6c096-779b-423a-8642-4bab9532eb73\" class=\"hs-cta-img aligncenter\" style=\"border-width: 0px;\" src=\"https:\/\/no-cache.hubspot.com\/cta\/default\/481864\/1bf6c096-779b-423a-8642-4bab9532eb73.png\" alt=\"Secure Coding in Android\" \/><\/a><\/span><\/span><br \/>\n<!-- end HubSpot Call-to-Action Code --><\/p>\n","protected":false},"excerpt":{"rendered":"<p>InAppPurchase,\u00a0as the name suggests is for purchasing items from within the application i.e., it allows you to put a price tag on your products and sell them in the market using your Android application. Integration of InAppPurchase in android can be achieved in few steps as follows: 1.\u00a0 The very first you need to do [&hellip;]<\/p>\n","protected":false},"author":684,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":3},"categories":[518,1772],"tags":[2182,2183],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/24960"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/684"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=24960"}],"version-history":[{"count":1,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/24960\/revisions"}],"predecessor-version":[{"id":59888,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/24960\/revisions\/59888"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=24960"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=24960"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=24960"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}