{"id":29581,"date":"2017-02-02T11:10:27","date_gmt":"2017-02-02T19:10:27","guid":{"rendered":"https:\/\/blog.xamarin.com\/?p=29581"},"modified":"2019-03-25T19:40:56","modified_gmt":"2019-03-26T03:40:56","slug":"integrating-in-app-purchases-in-mobile-apps","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/xamarin\/integrating-in-app-purchases-in-mobile-apps\/","title":{"rendered":"Integrating In-App Purchases in Mobile Apps"},"content":{"rendered":"<p>\t\t\t\t<img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/icon_128.png\" alt=\"icon_128\" width=\"128\" height=\"128\" class=\"alignright size-full wp-image-29622\" \/>Developers often need to integrate monetization to generate revenue when developing mobile apps. There are several ways to monetize apps, but at some point you may want to introduce In-App Purchases, or IAPs, into your app. IAPs can be used in several ways that could apply to your apps, such as adding features, removing ads, or buying in-game currency. Let&#8217;s take an in-depth look at IAPs and how to add them to mobile apps.<\/p>\n<h2>Types of In-App Purchases<\/h2>\n<p>As I mentioned above, there are several types of IAPs that can be used for iOS and Android that may apply to your mobile application. Here&#8217;s a quick overview:<\/p>\n<ul>\n<li><b>Consumable<\/b>: Items that are used up over the course of the application&#8217;s life and can be purchased multiple times. Examples are in-game currency, extra health, and one-time services such as transcription.<\/li>\n<li><b>Non-Consumable<\/b>: Items that the user owns indefinitely and can only be purchased once. Examples are books, game levels, and additional app functionality.<\/li>\n<li><b>Subscriptions<\/b>: A recurring purchase that can be auto-renewable or non-renewable that occur or expire after a set amount of time (usually in month chunks).<\/li>\n<\/ul>\n<p>I&#8217;ll focus on the most common type, Non-Consumable, in this blog post.<\/p>\n<h2>Getting Started<\/h2>\n<p>Before we can start implementing code, we have to make sure our apps are set up properly to start accepting purchases. Each platform handles this differently, but I&#8217;ll cover the basics. I highly recommend following the full documentation on In-App Purchases for <a href=\"https:\/\/developer.xamarin.com\/guides\/ios\/application_fundamentals\/in-app_purchasing\/\" target=\"_blank\">iOS<\/a> and <a href=\"https:\/\/github.com\/jamesmontemagno\/InAppBillingPlugin\" target=\"_blank\">Android<\/a> for more information.<\/p>\n<p>You must first ensure that your application is set up in both iTunes Connect and the Google Play Developer Console.<\/p>\n<h3>iOS Setup<\/h3>\n<p>Any application that wants to use In-App Purchases require a unique app identifier (no wildcards allowed) for the provision profile and will set the IAP functionality automatically. Once the app has been created, we can head to the <b>Features<\/b> section, create a new IAP, and select &#8220;Non-Consumable.&#8221; We&#8217;ll then fill in additional information, such as the Product ID (a unique identifier we will use in code), price, and description of the product.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/IAP1.png\" alt=\"IAP\" width=\"850\" height=\"717\" class=\"aligncenter size-full wp-image-29792\" \/><\/p>\n<p>Once this IAP has been set up, we&#8217;re ready to start integrating.<\/p>\n<h3>Android Setup<\/h3>\n<p>Android is a bit more complex, as we can&#8217;t add a new IAP for our application until we publish a version of our application that contains the <code>com.android.vending.BILLING<\/code> permission. We can add this by inserting the following:<\/p>\n<pre><code><\/code><\/pre>\n<p>&#8230;line between the&#8230;<\/p>\n<pre><code>...<\/code><\/pre>\n<p>&#8230;in the <code>AndroidManifest.xml<\/code>.<\/p>\n<p>The app can then be published in the Alpha or Beta channel in the Google Developer Console, and a new IAP can be added under the &#8220;In-App Purchase&#8221; section for the application. It&#8217;s important to create the IAP as a managed product.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/IAPAndroid.png\" alt=\"IAPAndroid\" width=\"600\" class=\"aligncenter size-full wp-image-29616\" \/><\/p>\n<p>We&#8217;ll then be taken to a page where the details for the IAP are filled in. We must save the IAP and set it to <code>Active<\/code> or it won&#8217;t work when we implement code.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/IAPAndroid2.png\" alt=\"IAPAndroid2\" class=\"sligncenter size-full\" \/><\/p>\n<h2>Making Purchases<\/h2>\n<p>With the applications set up, we&#8217;re now able to integrate code. Each platform has a different mechanism for handling purchases, but they each do similar things, which is why I worked with <a href=\"http:\/\/twitter.com\/redth\" target=\"_blank\">Jon Dick<\/a> from our components team to create a new plugin for Xamarin that we call <a href=\"http:\/\/github.com\/jamesmontemagno\/InAppBillingPlugin\" target=\"_blank\">In-App Billing Plugin for Xamarin and Windows<\/a>, which simplifies the entire purchase process. The Plugin handles purchases, subscriptions, consumption, and product information from a cross-platform API; if you need custom flows, I highly recommend reading through full documentation on In-App Purchases for <a href=\"https:\/\/developer.xamarin.com\/guides\/ios\/application_fundamentals\/in-app_purchasing\/\" target=\"_blank\">iOS<\/a> and <a href=\"https:\/\/github.com\/jamesmontemagno\/InAppBillingPlugin\" target=\"_blank\">Android<\/a>.<\/p>\n<p>To get started, we&#8217;ll install the In-App Billing Plugin (Plugin.InAppBilling) in all of our projects, including our portable class library and mobile app projects:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/AddNuGet.png\" alt=\"AddNuGet\" width=\"847\" class=\"aligncenter size-full\" \/><\/p>\n<h3>Additional Android Setup<\/h3>\n<p>Android requires just a little bit more set up. We&#8217;ll add the following code in the Activity that will be making the purchase call or the MainActivity (for Xamarin.Forms):<\/p>\n<pre><code>\r\nprotected override void OnActivityResult(int requestCode, Result resultCode, Intent data)\r\n{\r\n    base.OnActivityResult(requestCode, resultCode, data);\r\n    InAppBillingImplementation.HandleActivityResult(requestCode, resultCode, data);\r\n}\r\n<\/code><\/pre>\n<p>Now, in our app code or shared code, we can go ahead and make the purchase with just a few simple calls to connect to the billing service and attempt to make the purchase:<\/p>\n<pre><code>\r\ntry\r\n{\r\n    var productId = \"mysku\";\r\n\r\n    var connected = await CrossInAppBilling.Current.ConnectAsync();\r\n\r\n    if (!connected)\r\n    {\r\n        \/\/Couldn't connect to billing, could be offline, alert user\r\n        return;\r\n    }\r\n\r\n    \/\/try to purchase item\r\n    var purchase = await CrossInAppBilling.Current.PurchaseAsync(productId, ItemType.InAppPurchase, \"apppayload\");\r\n    if(purchase == null)\r\n    {\r\n        \/\/Not purchased, alert the user\r\n    }\r\n    else\r\n    {\r\n        \/\/Purchased, save this information\r\n        var id = purchase.Id;\r\n        var token = purchase.PurchaseToken;\r\n        var state = purchase.State;\r\n    }\r\n}\r\ncatch (Exception ex)\r\n{\r\n    \/\/Something bad has occurred, alert user\r\n}\r\nfinally\r\n{\r\n    \/\/Disconnect, it is okay if we never connected\r\n    await CrossInAppBilling.Current.DisconnectAsync();\r\n}\r\n<\/code><\/pre>\n<p>And that&#8217;s it! At this point we could store this information in our application settings or report it to our backend services on a successful purchase. To test this new code, we&#8217;ll need to run it on a physical device built and signed with the provisioning profile, or keystore, for the application.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/inappdone.png\" alt=\"inappdone\" width=\"300\" height=\"534\" class=\"aligncenter size-full wp-image-29623\" \/><\/p>\n<h2>Learn More<\/h2>\n<p>There&#8217;s a lot more to IAPs, including consumption and product information that are exposed in the In-App Billing Plugins APIs. You can find out more about this in the README file on the <a href=\"https:\/\/github.com\/jamesmontemagno\/InAppBillingPlugin\" target=\"_blank\">GitHub project<\/a>. That same documentation will walk you through a full setup, testing, and trouble shooting guide to integrating In-App Purchases.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Developers often need to integrate monetization to generate revenue when developing mobile apps. There are several ways to monetize apps, but at some point you may want to introduce In-App Purchases, or IAPs, into your app. IAPs can be used in several ways that could apply to your apps, such as adding features, removing ads, or buying in-game currency. Let&#8217;s take an in-depth look at IAPs and how to add them to mobile apps.<\/p>\n","protected":false},"author":544,"featured_media":41044,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[313,2,556,303],"tags":[5,1373,6,1374,4,16],"class_list":["post-29581","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-android","category-developers","category-integrations","category-ios","tag-android","tag-in-app-purchase","tag-ios","tag-plugins","tag-xamarin-platform","tag-xamarin-forms"],"acf":[],"blog_post_summary":"<p>Developers often need to integrate monetization to generate revenue when developing mobile apps. There are several ways to monetize apps, but at some point you may want to introduce In-App Purchases, or IAPs, into your app. IAPs can be used in several ways that could apply to your apps, such as adding features, removing ads, or buying in-game currency. Let&#8217;s take an in-depth look at IAPs and how to add them to mobile apps.<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/29581","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/users\/544"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/comments?post=29581"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/29581\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media\/41044"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media?parent=29581"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/categories?post=29581"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/tags?post=29581"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}