Friday 18 April 2014

Example Program - In App Purchase

.h File
#import <UIKit/UIKit.h>
#import <StoreKit/StoreKit.h>

@interface inapp_purchase : UIViewController<SKPaymentTransactionObserver,SKProductsRequestDelegate>
{
    IBOutlet UILabel *iTitle;
    IBOutlet UILabel *idescription;
    IBOutlet UILabel *iPrice;
    IBOutlet UILabel *ipricelabel;
    
    IBOutlet UIButton *ibuy;
    IBOutlet UIButton *irestore;
    
    IBOutlet UIActivityIndicatorView *loader;
}
@end

.m File
#import "inapp_purchase.h"
@interface inapp_purchase ()
{
    SKProductsRequest *_productsRequest;
    NSArray *_products;
    NSNumberFormatter *_priceFormatter;
    SKProduct *proUpgradeProduct;
}
@end

@implementation inapp_purchase

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    
    _priceFormatter = [[NSNumberFormatter alloc] init];
    [_priceFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [_priceFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    
    _products = nil;
    
    [loader startAnimating];
    
    [self requestProUpgradeProductData];
}

- (void)requestProUpgradeProductData
{
    NSSet *productIdentifiers = [NSSet setWithObject:@"com.ashuss.WedPlanPremium" ];
    _productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];
    _productsRequest.delegate = self;
    [_productsRequest start];
    
    // we will release the request object in the delegate callback
}

#pragma mark -
#pragma mark SKProductsRequestDelegate methods
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    NSArray *products = response.products;
    proUpgradeProduct = [products count] == 1 ? [[products firstObject] retain] : nil;
    _products = products;
    if (proUpgradeProduct)
    {
        iTitle.text = proUpgradeProduct.localizedTitle;
        [_priceFormatter setLocale:proUpgradeProduct.priceLocale];
        iPrice.text = [_priceFormatter stringFromNumber:proUpgradeProduct.price];
        idescription.text = proUpgradeProduct.localizedDescription;
        
        ipricelabel.hidden = NO;
        ibuy.hidden = NO;
        irestore.hidden = NO;
        
        [loader stopAnimating];
        
        NSLog(@"Product title: %@" , proUpgradeProduct.localizedTitle);
        NSLog(@"Product description: %@" , proUpgradeProduct.localizedDescription);
        NSLog(@"Product price: %@" , proUpgradeProduct.price);
        NSLog(@"Product id: %@" , proUpgradeProduct.productIdentifier);
    }
    
    for (NSString *invalidProductId in response.invalidProductIdentifiers)
    {
        NSLog(@"Invalid product id: %@" , invalidProductId);
    }
    
    // finally release the reqest we alloc/init’ed in requestProUpgradeProductData
    [_productsRequest release];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"kInAppPurchaseManagerProductsFetchedNotification" object:self userInfo:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
    SKProduct * product = (SKProduct *) _products[0];
    iTitle.text = product.localizedTitle;
    [_priceFormatter setLocale:product.priceLocale];
    iPrice.text = [_priceFormatter stringFromNumber:product.price];
    idescription.text = product.description;
}

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
    for (SKPaymentTransaction *transaction in transactions)
    {
        switch (transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchased:
                [self completeTransaction:transaction];
                break;
            case SKPaymentTransactionStateFailed:
                [self failedTransaction:transaction];
                break;
            case SKPaymentTransactionStateRestored:
                [self restoreTransaction:transaction];
            default:
                break;
        }
    }
}

- (void) completeTransaction: (SKPaymentTransaction *)transaction{
    NSLog(@"Transaction Completed");
    // You can create a method to record the transaction.
    //[self recordTransaction: transaction];
    
    // You should make the update to your app based on what was purchased and inform user.
    [self provideContent: transaction.payment.productIdentifier];
    
    // Finally, remove the transaction from the payment queue.
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    
}

-(void)provideContent: (NSString *)productIdentifier
{
    if ([productIdentifier isEqualToString:@"com.ashuss.WedPlanPremium"])
    {
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:productIdentifier];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"InAppPurchase" object:productIdentifier userInfo:nil];
        //do your stup because purchase completeded
        single.ads_removed = YES;
        [self dismissModalViewControllerAnimated:YES];
    }
    else
    {
        NSLog(@"Failed");
    }
}

- (void) restoreTransaction: (SKPaymentTransaction *)transaction
{
    NSLog(@"Transaction Restored");
    // You can create a method to record the transaction.
    // [self recordTransaction: transaction];
    
    // You should make the update to your app based on what was purchased and inform user.
    [self provideContent: transaction.payment.productIdentifier];
    
    // Finally, remove the transaction from the payment queue.
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

- (void) failedTransaction: (SKPaymentTransaction *)transaction
{
    //[activityIndicator stopAnimating];
    if (transaction.error.code != SKErrorPaymentCancelled)
    {
        // Display an error here.
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Purchase Unsuccessful"
                                                        message:@"Your purchase failed. Please try again."
                                                       delegate:self
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
    
    // Finally, remove the transaction from the payment queue.
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

-(IBAction)done:(id)sender
{
    [self dismissModalViewControllerAnimated:YES];
}

-(IBAction)Buy:(id)sender
{
    SKPayment *newPayment = [SKPayment paymentWithProduct:proUpgradeProduct];
    [[SKPaymentQueue defaultQueue] addPayment:newPayment];
}

-(IBAction)Restore:(id)sender
{
    [[SKPaymentQueue defaultQueue]restoreCompletedTransactions];
}

No comments: