Introduction to In App Purchase in iOS 7 with The Help of StoreKit

Introduction to In App  Purchase

In App purchase is used to sell our products or items inside our applications. Basically in App purchase is consist of many types, they are Consumable, Non-Consumable, Auto-Renewable Subscriptions, Free Subscriptions,Non-Renewing Subscriptions. All major terms are self explanatory. To know more about the in app purchase please take a look at the below image, so you can get a clear cut idea.

In App Purchase Types

 

So let’s get started how we can implement the In App purchase in iOS7 with the help of StoreKit framework.

Major Steps Involved in In App Purchase 

1. Create a sample project with Unique Apple ID (com.example.appname) in the itunes connect .

2. Do a code signing with developer.apple.com for the Unique Bundle ID and get the provisioning profile from iOS Dev Center .

3. Upload the new application to the apple server. you can get more idea about how to add a new app from here

4. Next we need to add new product for In App purchase by clicking the Manage In-App Purchase of our application.

5.Please check the Bank account information of the developer account, then only the in app purchase will work. (sandbox too)

6.Next we need to add test users to test the in app purchase. You can see Manage Users in itunnes connect.

7. So next we need to prepare the sample application and its UI.

8.Now going to Create a single View based application, with the uinque bundle id.

single view based application

 

9. Next we need to prepare the UI for in App purchase .

In app purchase interface

 

 

10. Now hook it up the corresponding outlets respect to the Product title, Product Description, Product Price. Also wire up with the purchase button.

11. Next we need to add the StoreKit.framework to the project.

Adding Store kit  for in App purchase

 

 

12. Add the following code in SSViewController

 

#import 
#import 

@interface SSViewController : UIViewController {
    SKProductsRequest *productRequest;
    NSArray *validProductsInStore;
    UIActivityIndicatorView *activityIndicator;
    IBOutlet UILabel *productTitle;
    IBOutlet UILabel *productDescription;
    IBOutlet UILabel *productPrice;
    IBOutlet UIButton *purchaseButton;
}
- (void)getAvailableProducts;
- (BOOL)canMakePurchase;
- (void)purchaseProduct:(SKProduct*)product;
- (IBAction)purchase:(id)sender;

@end

13. Next we need to update the SSViewController.m

@interface SSViewController ()

@end

@implementation SSViewController
#define INAPP_PRODUCT_ID @"com.safilsunny.inapp.testproduct"

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Adding activity indicator
    activityIndicator = [[UIActivityIndicatorView alloc]
                             initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activityIndicator.center = self.view.center;
    [activityIndicator hidesWhenStopped];
    [self.view addSubview:activityIndicator];
    [activityIndicator startAnimating];
    //Hide purchase button initially
    purchaseButton.hidden = YES;
    [self getAvailableProducts];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)getAvailableProducts{
    NSSet *productIdentifiers = [NSSet
                                 setWithObjects:INAPP_PRODUCT_ID,nil];
    productRequest = [[SKProductsRequest alloc]
                       initWithProductIdentifiers:productIdentifiers];
    productRequest.delegate = self;
    [productRequest start];
}

- (BOOL)canMakePurchase
{
    return [SKPaymentQueue canMakePayments];
}
- (void)purchaseProduct:(SKProduct*)product{
    if ([self canMakePurchase]) {
        SKPayment *payment = [SKPayment paymentWithProduct:product];
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }
    else{
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:
                                  @"Purchases are disabled in your device" message:nil delegate:
                                  self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [alertView show];
    }
}
-(IBAction)purchase:(id)sender{
    [self purchaseProduct:[validProductsInStore objectAtIndex:0]];
    purchaseButton.enabled = NO;
}

#pragma mark StoreKit Delegate

-(void)paymentQueue:(SKPaymentQueue *)queue
updatedTransactions:(NSArray *)transactions {
    for (SKPaymentTransaction *transaction in transactions) {
        switch (transaction.transactionState) {
            case SKPaymentTransactionStatePurchasing:
                NSLog(@"Purchasing Product From Store!");
                break;
            case SKPaymentTransactionStatePurchased:
                if ([transaction.payment.productIdentifier
                     isEqualToString:INAPP_PRODUCT_ID]) {
                    NSLog(@"Product Purchased From Store!");
                    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:
                                              @"Purchase is completed succesfully" message:nil delegate:
                                              self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
                    [alertView show];
                }
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                break;
            case SKPaymentTransactionStateRestored:
                NSLog(@"Restored ");
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                break;
            case SKPaymentTransactionStateFailed:
                NSLog(@"Purchase failed ");
                break;
            default:
                break;
        }
    }
}

-(void)productsRequest:(SKProductsRequest *)request
    didReceiveResponse:(SKProductsResponse *)response
{
    SKProduct *validProduct = nil;
    int count = [response.products count];
    if (count>0) {
        validProductsInStore = response.products;
        validProduct = [response.products objectAtIndex:0];
        if ([validProduct.productIdentifier
             isEqualToString:INAPP_PRODUCT_ID]) {
            [productTitle setText:[NSString stringWithFormat:
                                        @"Product Title: %@",validProduct.localizedTitle]];
            [productDescription setText:[NSString stringWithFormat:
                                              @"Product Desc: %@",validProduct.localizedDescription]];
            [productPrice setText:[NSString stringWithFormat:
                                        @"Product Price: %@",validProduct.price]];
        }
    } else {
        UIAlertView *tmp = [[UIAlertView alloc]
                            initWithTitle:@"Not Available"
                            message:@"No products to purchase"
                            delegate:self
                            cancelButtonTitle:nil
                            otherButtonTitles:@"Ok", nil];
        [tmp show];
    }    
    [activityIndicator stopAnimating];
    purchaseButton.hidden = NO;
}

@end

Important Information 

Don’t forget to update the INAPP_PRODUCT_ID  with the correct product item id, that you prepared for in app purchase in the itunes connect.

Now just run the application.

Run In App purchase app

 

after running the application, you have to click on the purchase button, (Don’t forget to add the test user account in the apptore account manager) . For the first time it will ask for the username and password for the In App Purchase , please provide your test account username and password.

Confirm the In App Purchase

 

Next you have to Confirm the In App Purchase for that just click on By button in the alert. So it will started purchasing, you can check the log in the console . Ones the purchase is done it will through up an alert,

In App Purchase confirm screen

 

Thats it. you are done with In App Purchase  in iOS.

17 Comments

  1. Raj October 9, 2013
  2. Guest October 9, 2013
  3. safilsunny October 9, 2013
  4. Albert November 26, 2013
  5. safilsunny November 28, 2013
  6. safilsunny November 28, 2013
    • kiran December 4, 2013
      • safilsunny December 4, 2013
        • kiran December 5, 2013
  7. Samson November 29, 2013
  8. Albert December 2, 2013
    • zoneman December 9, 2013
  9. Ruchika gupta December 4, 2013
    • safilsunny December 4, 2013
      • Ruchika gupta December 5, 2013
  10. zoneman December 9, 2013
  11. Mohammad Komeili April 10, 2014

Leave a Reply

Your email address will not be published. Required fields are marked *