http://stackoverflow.com/questions/19556336/how-do-you-add-an-in-app-purchase-to-an-ios-application

The best way to get an in-app purchase working for iOS 9 (and iOS 8 and 7) in Xcode 5+ is to do the following:

  1. Go to itunes.connect.apple.com and log in
  2. Click My Apps then click the app you want do add the purchase into
  3. Click In-App Purchases header
  4. Click Create New in the top left hand corner
  5. For this tutorial, we are going to be adding an in-app purchase to remove ads, so choose non-consumable. If you were going to send a physical item to the user, you would choose consumable.
  6. For the reference name, put whatever you want (but make sure you know what it is)
  7. For product id put tld.websitename.appname.referencename this will work the best, so for example, you could use com.jojodmo.blix.removeads
  8. Choose cleared for sale and then choose price tier as 1 (99¢). Tier 2 would be $1.99, and tier 3 would be $2.99. The full list is available if you click view pricing matrix I recommend you use tier 1, because that's usually the most anyone will ever pay to remove ads.
  9. Click the blue add language button, and input the information. This will ALL be shown to the customer, so don't put anything you don't want them seeing
  10. For hosting content with Apple choose no
  11. You can leave the review notes blank FOR NOW.
  12. Skip the screenshot for review FOR NOW, everything we skip we will come back to.
  13. Click 'save'

It could take a few hours for your product ID to register in iTunesConnect, so be patient.

Now that you've set up your in-app purchase information on iTunesConnect, go into your Xcode project, and go to the application manager (blue page-like icon at the top of where your methods and header files are) click on your app under targets (should be the first one) then go to general. At the bottom, you should see linked frameworks and libraries click the little plus symbol and add the framework StoreKit.framework If you don't do this, the in-app purchase will NOT work!

Now we're going to get into the actual coding.

Add the following code into your .h file:

BOOL areAdsRemoved;-(IBAction)purchase;-(IBAction)restore;-(IBAction)tapsRemoveAds;

Next, you need to import the StoreKit framework into your .m file, as well as add SKProductsRequestDelegate and SKPaymentTransactionObserver after your @interfacedeclaration:

#import <StoreKit/StoreKit.h>//put the name of your view controller in place of MyViewController@interfaceMyViewController()<SKProductsRequestDelegate,SKPaymentTransactionObserver>@end@implementationMyViewController//the name of your view controller (same as above)//the code below will be added here@end

and now add the following into your .m file, this part gets complicated, so I suggest that you read the comments in the code:

//If you have more than one in-app purchase, you can define both of//of them here. So, for example, you could define both kRemoveAdsProductIdentifier//and kBuyCurrencyProductIdentifier with their respective product ids////for this example, we will only use one product#define kRemoveAdsProductIdentifier @"put your product id (the one that we just made in iTunesConnect) in here"-(IBAction)tapsRemoveAds{NSLog(@"User requests to remove ads");if([SKPaymentQueue canMakePayments]){NSLog(@"User can make payments");//If you have more than one in-app purchase, and would like//to have the user purchase a different product, simply define //another function and replace kRemoveAdsProductIdentifier with //the identifier for the other productSKProductsRequest*productsRequest =[[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:kRemoveAdsProductIdentifier]];
        productsRequest.delegate= self;[productsRequest start];}else{NSLog(@"User cannot make payments due to parental controls");//this is called the user cannot make payments, most likely due to parental controls}}-(void)productsRequest:(SKProductsRequest*)request didReceiveResponse:(SKProductsResponse*)response{SKProduct*validProduct = nil;int count =[response.products count];if(count >0){
        validProduct =[response.products objectAtIndex:0];NSLog(@"Products Available!");[self purchase:validProduct];}elseif(!validProduct){NSLog(@"No products available");//this is called if your product id is not valid, this shouldn't be called unless that happens.}}-(IBAction)purchase:(SKProduct*)product{SKPayment*payment =[SKPayment paymentWithProduct:product];[[SKPaymentQueue defaultQueue] addTransactionObserver:self];[[SKPaymentQueue defaultQueue] addPayment:payment];}-(IBAction) restore{//this is called when the user restores purchases, you should hook this up to a button[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];}-(void) paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue*)queue{NSLog(@"received restored transactions: %i",queue.transactions.count);for(SKPaymentTransaction*transaction in queue.transactions){if(transaction.transactionState ==SKPaymentTransactionStateRestored){//called when the user successfully restores a purchaseNSLog(@"Transaction state -> Restored");[self doRemoveAds];[[SKPaymentQueue defaultQueue] finishTransaction:transaction];break;}}}-(void)paymentQueue:(SKPaymentQueue*)queue updatedTransactions:(NSArray*)transactions{for(SKPaymentTransaction*transaction in transactions){switch(transaction.transactionState){caseSKPaymentTransactionStatePurchasing:NSLog(@"Transaction state -> Purchasing");//called when the user is in the process of purchasing, do not add any of your own code here.break;caseSKPaymentTransactionStatePurchased://this is called when the user has successfully purchased the package (Cha-Ching!)[self doRemoveAds];//you can add your code for what you want to happen when the user buys the purchase here, for this tutorial we use removing ads[[SKPaymentQueue defaultQueue] finishTransaction:transaction];NSLog(@"Transaction state -> Purchased");break;caseSKPaymentTransactionStateRestored:NSLog(@"Transaction state -> Restored");//add the same code as you did from SKPaymentTransactionStatePurchased here[[SKPaymentQueue defaultQueue] finishTransaction:transaction];break;caseSKPaymentTransactionStateFailed://called when the transaction does not finishif(transaction.error.code ==SKErrorPaymentCancelled){NSLog(@"Transaction state -> Cancelled");//the user cancelled the payment ;(}[[SKPaymentQueue defaultQueue] finishTransaction:transaction];break;}}}

Now you want to add your code for what will happen when the user finishes the transaction, for this tutorial, we use removing adds, you will have to add your own code for what happens when the banner view loads.

-(void)doRemoveAds{ADBannerView*banner;[banner setAlpha:0];
    areAdsRemoved = YES;
    removeAdsButton.hidden = YES;
    removeAdsButton.enabled = NO;[[NSUserDefaults standardUserDefaults] setBool:areAdsRemoved forKey:@"areAdsRemoved"];//use NSUserDefaults so that you can load whether or not they bought it//it would be better to use KeyChain access, or something more secure//to store the user data, because NSUserDefaults can be changed.//You're average downloader won't be able to change it very easily, but//it's still best to use something more secure than NSUserDefaults.//For the purpose of this tutorial, though, we're going to use NSUserDefaults[[NSUserDefaults standardUserDefaults] synchronize];}

If you don't have ads in your application, you can use any other thing that you want. For example, we could make the color of the background blue. To do this we would want to use:

-(void)doRemoveAds{[self.view setBackgroundColor:[UIColor blueColor]];
    areAdsRemoved = YES
    //set the bool for whether or not they purchased it to YES, you could use your own boolean here, but you would have to declare it in your .h file[[NSUserDefaults standardUserDefaults] setBool:areAdsRemoved forKey:@"areAdsRemoved"];//use NSUserDefaults so that you can load wether or not they bought it[[NSUserDefaults standardUserDefaults] synchronize];}

Now, somewhere in your viewDidLoad method, you're going to want to add the following code:

areAdsRemoved =[[NSUserDefaults standardUserDefaults] boolForKey:@"areAdsRemoved"];[[NSUserDefaults standardUserDefaults] synchronize];//this will load wether or not they bought the in-app purchaseif(areAdsRemoved){[self.view setBackgroundColor:[UIColor blueColor]];//if they did buy it, set the background to blue, if your using the code above to set the background to blue, if your removing ads, your going to have to make your own code here}

Now that you have added all the code, go into your .xib or storyboard file, and add two buttons, one saying purchase, and the other saying restore. Hook up the tapsRemoveAds IBAction to the purchase button that you just made, and the restore IBAction to the restore button. The restore action will check if the user has previously purchased the in-app purchase, and give them the in-app purchase for free if they do not already have it.

Next, go into iTunesConnect, and click Users and Roles then click the Sandbox Testersheader, and then click the + symbol on the left where it says Testers. You can just put in random things for the first and last name, and the e-mail does not have to be real - you just have to be able to remember it. Put in a password (which you will have to remember) and fill in the rest of the info. I would recommend that you make the Date of Birth a date that would make the user 18 or older. App Store Territory HAS to be in the correct country. Next, log out of your existing iTunes account (you can log back in after this tutorial).

Now, run your application on your iOS device, if you try running it on the simulator, the purchase will always error, you HAVE TO run it on your iOS device. Once the app is running, tap the purchase button. When you are prompted to log into your iTunes account, log in as the test user that we just created. Next,when it asks you to confirm the purchase of 99¢ or whatever you set the price tier too, TAKE A SCREEN SNAPSHOT OF IT this is what your going to use for your screenshot for review on iTunesConnect. Now cancel the payment.

Now, go to iTunesConnect, then go to My Apps > the app you have the In-app purchase onIn-App Purchases. Then click your in-app purchase and click edit under the in-app purchase details. Once you've done that, import the photo that you just took on your iPhone into your computer, and upload that as the screenshot for review, then, in review notes, put your TEST USER e-mail and password. This will help apple in the review process.

After you have done this, go back onto the application on your iOS device, still logged in as the test user account, and click the purchase button. This time, confirm the payment Don't worry, this will NOT charge your account ANY money, test user accounts get all in-app purchases for free After you have confirmed the payment, make sure that what happens when the user buys your product actually happens. If it doesn't, then thats going to be an error with your doRemoveAds method. Again, I recommend using changing the background to blue for testing the in-app purchase, this should not be your actual in-app purchase though. If everything works and your good to go! Just make sure to include the in-app purchase in your new binary when you upload it to iTunesConnect!


Here are some common errors:

Logged: No Products Available

This could mean three things:

  • You didn't put the correct in-app purchase ID in your code (for the identifier kRemoveAdsProductIdentifier in the above code
  • You didn't clear your in-app purchase for sale on iTunesConnect
  • You didn't wait for the in-app purchase ID to be registered in iTunesConnect. Wait a couple hours from creating the ID, and your problem should be resolved.

If it doesn't work the first time, don't get frustrated! Don't give up! It took me about 5 hours straight before I could get this working, and about 10 hours searching for the right code! If you use the code above exactly, it should work fine. Feel free to comment if you have any questions at all.

I hope this helps to all of those hoping to add an in-app purchase to their iOS application. Cheers!

arrow
arrow
    全站熱搜

    pcwiki 發表在 痞客邦 留言(0) 人氣()