Hướng dẫn thêm in app purchase vào trong ứng dụng

  1. File .h:

#import <UIKit/UIKit.h>

#import <StoreKit/StoreKit.h>

 

#define PURCHASE_IN_GAME01 @”LapKanHittingMeSMoney01″

#define PURCHASE_IN_GAME02 @”LapKanHittingMeSMoney02″

#define PURCHASE_IN_GAME03 @”LapKanHittingMeSMoney03″

 

@interface LKLikShopViewController : UIViewController<SKPaymentTransactionObserver, SKProductsRequestDelegate>{

   NSMutableDictionary* idsToProducts;

 

   int LKMarking;

 

   // NEW FUNCTION

   SKProduct *proUpgradeProduct;

   SKProductsRequest *productsRequest;

 

   // Bonus Item in game

   int lkLikCoin;

   int lkClock;

   int lkColorStar;

   int lkGoldenBomb;

}

 

– (IBAction)actGetMoney:(id)sender;

– (IBAction)actGetCauldronMoney:(id)sender;

– (IBAction)actGetLuckyMoney:(id)sender;

– (IBAction)actOutShop:(id)sender;

 

// Display Number of Bonus Item and LikCoin

@property (strong, nonatomic) IBOutlet UILabel *lblLKCoin;

@property (strong, nonatomic) IBOutlet UILabel *lkNumClock;

@property (strong, nonatomic) IBOutlet UILabel *lkNumColorStar;

@property (strong, nonatomic) IBOutlet UILabel *lkNumGoldenBomb;

@property (strong, nonatomic) IBOutlet UILabel *ThongBao;

@end

 

* Mới bắt đầu, chúng ta cần phải định nghĩa trước những chuỗi (Purchase ID) của các sản phẩm In-App Purchase sẽ được sử dụng. Nó không chỉ giúp chúng ta có được sự tiện lợi khi sử dụng các hỗ trợ từ IDE mà còn giúp cho bạn có thể tái sử dụng những đoạn mã một cách rất dễ dàng.

– Những chuỗi này có thể được đưa vào trong một file Config riêng hoặc cho vào một file Shop như thế này để dễ dàng quản lý.

* Sau đó, tôi khai báo các biến được sử dụng trong chương trình để làm việc cho dễ.

* Những sự kiện (IBAction) trong chương trình để gửi lên server của Apple thanh toán cho lập trình viên chúng ta.

 

* Sau cùng là những control (Label) để hiển thị thông tin lên trên màn hình.

  1. File .m:

#import “LKLikShopViewController.h”

 

@interface LKLikShopViewController ()

 

@end

 

@implementation LKLikShopViewController

 

– (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

   self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

   if (self) {

       // Custom initialization

   }

   return self;

}

 

– (void)viewDidLoad

{

   [super viewDidLoad];

   idsToProducts = [NSMutableDictionary new];

   [[SKPaymentQueue defaultQueue] addTransactionObserver:self];

 

   NSSet* potentialProcucts = [NSSet setWithObjects: nil];

 

   SKProductsRequest* request = [[SKProductsRequest alloc] initWithProductIdentifiers:potentialProcucts];

   [request setDelegate:self];

   [request start];

 

   LKMarking = 0;

   [self updateShop];

}

 

-(BOOL) preparePayment{

   if([SKPaymentQueue canMakePayments]){

       [[SKPaymentQueue defaultQueue] addTransactionObserver:self];

       return YES;

   }else{

       return NO;

   }

}

 

– (void) updateShop{

   NSNumberFormatter* lkNumberFormatter = [[NSNumberFormatter alloc] init];

  1. usesGroupingSeparator = YES;
  2. groupingSeparator = @”,”;
  3. groupingSize = 3;

 

   NSUserDefaults *lkUserDefault = [NSUserDefaults standardUserDefaults];

   lkLikCoin = [[lkUserDefault objectForKey:@”LKLikCoin”] intValue];

   NSString *myCoinString = [lkNumberFormatter stringFromNumber: [NSNumber numberWithInteger: lkLikCoin]];

  1.    _lblLKCoin.text = myCoinString;

 

   lkClock = [[lkUserDefault objectForKey:@”LKClock”] intValue];

   NSString *myClockString = [lkNumberFormatter stringFromNumber: [NSNumber numberWithInteger: lkClock]];

  1.    _lkNumClock.text = myClockString;

 

 

   lkColorStar = [[lkUserDefault objectForKey:@”LKColorStar”] intValue];

   NSString *myColorStarString = [lkNumberFormatter stringFromNumber: [NSNumber numberWithInteger: lkColorStar]];

  1.    _lkNumColorStar.text = myColorStarString;

 

   lkGoldenBomb = [[lkUserDefault objectForKey:@”LKGoldenBomb”] intValue];

   NSString *myGoldenBombString = [lkNumberFormatter stringFromNumber: [NSNumber numberWithInteger: lkGoldenBomb]];

  1.    _lkNumGoldenBomb.text = myGoldenBombString;

}

 

– (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {

   if ([response.products count] > 0) {

SKProduct  * product = [response.products  objectAtIndex : 0 ];

       SKPayment  * payment = [ SKPayment  paymentWithProduct : product];

       [[ SKPaymentQueue  defaultQueue ]  addPayment : payment];

}else{

       if([self respondsToSelector:@selector(PurchaseCompleted:)]){

           [self performSelector:@selector(PurchaseCompleted:) withObject:[[NSString alloc] initWithFormat:@”Error”]];

       }

}

}

 

#pragma mark –

#pragma mark SKProductsRequestDelegate methods

– (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions{

   BOOL gotit = false;

   for (SKPaymentTransaction* transaction in transactions){

       if (transaction.transactionState == SKPaymentTransactionStatePurchased)// || transaction.transactionState == SKPaymentTransactionStateRestored)

       {

           NSString* productIdentifier = transaction.payment.productIdentifier;

 

           if ([productIdentifier.description isEqual: PURCHASE_IN_GAME01] && gotit == false){

               NSUserDefaults *lkUserDefault = [NSUserDefaults standardUserDefaults];

               lkLikCoin = [[lkUserDefault objectForKey:@”LKLikCoin”] intValue];

               lkLikCoin += 10000;

               [lkUserDefault setInteger:lkLikCoin forKey:@”LKLikCoin”];

 

               NSString *thongBaoX = @”You got 10.000 Lik Coin!!”;

  1.                _ThongBao.text = thongBaoX;

               gotit = true;

 

           } else if ([productIdentifier.description isEqual: PURCHASE_IN_GAME02]&& gotit == false){

               NSUserDefaults *lkUserDefault = [NSUserDefaults standardUserDefaults];

               lkLikCoin = [[lkUserDefault objectForKey:@”LKLikCoin”] intValue];

               lkLikCoin += 65000;

               [lkUserDefault setInteger:lkLikCoin forKey:@”LKLikCoin”];

 

               NSString *thongBaoX = @”You got 65.000 Lik Coin!!”;

  1.                _ThongBao.text = thongBaoX;

               gotit = true;

 

           } else if ([productIdentifier.description isEqual: PURCHASE_IN_GAME03]&& gotit == false){

               NSUserDefaults *lkUserDefault = [NSUserDefaults standardUserDefaults];

               lkLikCoin = [[lkUserDefault objectForKey:@”LKLikCoin”] intValue];

               lkLikCoin += 150000;

               [lkUserDefault setInteger:lkLikCoin forKey:@”LKLikCoin”];

 

               NSString *thongBaoX = @”You got 150.000 Lik Coin!!”;

  1.                _ThongBao.text = thongBaoX;

               gotit = true;

           }

 

           [queue finishTransaction:transaction];

           [self updateShop];

       }

   }

}

 

-(void) finishTransaction: (SKPaymentTransaction *) transaction withSuccess:(BOOL)success{

 

}

 

– (void)completeTransaction:(SKPaymentTransaction *)transaction {

   [self updateShop];

}

 

– (void)restoreTransaction:(SKPaymentTransaction *)transaction {

   NSLog(@”restoreTransaction…”);

 

   [self validateReceiptForTransaction:transaction];

   [[SKPaymentQueue defaultQueue] finishTransaction:transaction];

}

 

– (void)failedTransaction:(SKPaymentTransaction *)transaction {

   NSLog(@”failedTransaction…”);

   if (transaction.error.code != SKErrorPaymentCancelled)

   {

       NSLog(@”Transaction error: %@”, transaction.error.localizedDescription);

       UIAlertView *myalert = [[UIAlertView alloc] initWithTitle:@”Transaction fail Notice” message:@”Unable to do this transaction” delegate:nil cancelButtonTitle:@”Okie” otherButtonTitles:nil];

       [myalert show];

   }

 

   [[SKPaymentQueue defaultQueue] finishTransaction: transaction];

}

 

– (void)didReceiveMemoryWarning

{

   [super didReceiveMemoryWarning];

}

 

– (IBAction)actGetMoney:(id)sender {

   SKProductsRequest* request = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject: PURCHASE_IN_GAME01]];

  1. delegate = self;

   [request start];

}

 

– (IBAction)actGetCauldronMoney:(id)sender {

   SKProductsRequest* request = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject: PURCHASE_IN_GAME02]];

  1. delegate = self;

   [request start];

}

 

– (IBAction)actGetLuckyMoney:(id)sender {

   SKProductsRequest* request = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject: PURCHASE_IN_GAME03]];

  1. delegate = self;

   [request start];

}

 

– (IBAction)actOutShop:(id)sender {

   [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];

}

 

-(void) PurchaseCompleted{

 

}

@end

Tagged: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: