Setting Up In-App Purchases For IOS In Ionic 1.x

Posted By Weston Ganger

Update: This article is outdated, use this one instead

In-App purchases are a great way to implement a monetization solution for your app. For example you can provide a free version with ads and you can provide an in-app purchase to remove the the ads.

Heres how to set it up for IOS with Ionic. It should work with any Cordova or PhoneGap project with some minor implementation changes.

First install in the Cordova Purchase Plugin

yourApp.run(function($ionicPlatform, $localStorage){
  $ionicPlatform.ready(function(){
    if(window.storekit){
      storekit.init({
        debug: true, //Enable Storekit messages in console
        ready: function(){
          storekit.load(['yourAppName.adfree'], function(products, invalidIds){
            for(var i=0;i<invalidIds.length;i++){
              console.log("Error: could not load " + invalidIds[i]);
            }
          });
        },
        purchase: function(transactionId, productId, reciept){
          if(productId === "yourAppName.adfree"){
            // Replace these lines with your implementation details ex.
            $localStorage.set('adfree',true);
            AdMob.removeBanner();
            alert("Thanks!\nAds have been removed.");
          }
        },
        restore: function(transactionId, productId, transactionReciept){
          if(productId === "yourAppName.adfree"){
            // Replace these lines with your implementation details ex.
            AdMob.removeBanner();
            $localStorage.set('adfree',true);
          }
        },
        error: function(errorCode, errorMessage){
          console.log(errorCode);
          console.log(errorMessage);
        }
      })
    }
  });
});


yourApp.controller('myCtrl', function($scope){
  $scope.purchase = function(){
    if(window.storekit){
      storekit.purchase('adfree');
    }
  };

  $scope.restore = function(){
    if(window.storekit){
      storekit.restore('adfree');
    }
  };
});

The Restore function is required in-case they delete the app or clear their local storage, etc. So that they can re-get their previous purchase without paying. This is required by both app stores.

You can create a sandbox account on iTunes Connect to test your purchases. The buy window will then say [Environment: Sandbox] to show the purchases are not charged.

I will be creating another article that describes how to set it up for android.

Related External Links:

Article Topic:Software Development - Javascript

Date:December 15, 2015