如何将应用内购买添加到iOS应用程序? [英] How do you add an in-app purchase to an iOS application?

查看:176
本文介绍了如何将应用内购买添加到iOS应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将应用内购买添加到iOS应用?什么是所有的细节,是否有任何示例代码?

How do you add an in-app purchase to an iOS app? What are all the details and is there any sample code?

这是针对如何在iOS应用程式中加入应用程式内购买的全部分类 >

推荐答案

获得应用内购买 > Xcode 5+中的iOS 10 (和 iOS 9,8和7 )是执行以下操作:

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


  1. 前往 itunes.connect.apple.com 并登入

  2. 点击我的应用,然后点击您要添加购买的应用

  3. 点击特征标题,然后在左侧选择应用内购买

  4. code> + 中间的图示

  5. 在本教程中,我们将添加应用内购买以删除广告, code>非耗材。如果您要向用户发送实体项目,或给他们一些他们可以多次购买的内容,则可以选择耗材

  6. 对于引用名称,输入任何你想要的(但要确保你知道它是什么)

  7. 对于产品id put tld.websitename.appname。例如,您可以使用 com.jojodmo.blix.removeads

  8. li>选择清算出售,然后选择价格层为1(99¢)。第2级将是1.99美元,第3级将是2.99美元。如果您点击查看定价矩阵,则可以查看完整列表我建议您使用第1层,因为这通常是任何人为了删除广告而支付的最多。
  9. 单击蓝色的添加语言按钮,然后输入信息。 $ 托管内容与Apple c> ,所有我们跳过的内容都将回到

  10. '

  1. Go to itunes.connect.apple.com and log in
  2. Click My Apps then click the app you want do add the purchase to
  3. Click the Features header, and then select In-App Purchases on the left
  4. Click the + icon in the middle
  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, or give them something that they can buy more than once, 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'

您的产品ID可能需要几个小时才能在 iTunesConnect ,请耐心等待。

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

现在您已经在iTunesConnect上设置了应用内购买信息,进入您的Xcode项目,然后转到应用程序管理器蓝色的页面图标在你的方法和头文件的顶部)点击你的应用程序目标(应该是第一个),然后去一般。在底部,您应该看到链接的框架和库单击小加符号并添加框架 StoreKit.framework 如果

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!

如果您使用Objective-C作为您的语言应用程序,您可以跳过这五个步骤。否则,如果您使用的是Swift,请执行以下操作:

If you are using Objective-C as the language for your app, you can skip these five steps. Otherwise, if you are using Swift, do the following:


  1. 创建一个新的 .h <转到文件> > 文件, .. Command⌘ + N )。

  1. Create a new .h (header) file by going to File > New > File... (Command ⌘ + N). This file will be referred to as "Your .h file" in the rest of the tutorial


  • 您没有将正确的应用内购买ID =http://itunesconnect.apple.com> iTunesConnect

  • 您没有等待应用内购买ID在 iTunesConnect 。从创建ID开始等待几个小时,您的问题应该解决。

  • 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.

如果第一次不能工作,不要沮丧!不要放弃!我花了我大约5个小时,这个工作,大约10个小时搜索正确的代码!如果你使用上面的代码准确,它应该工作正常。如果您有任何疑问,随时可以发表评论。

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.

我希望这有助于所有希望添加应用内购买到他们的iOS应用程序。干杯!

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

这篇关于如何将应用内购买添加到iOS应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

此文件将被称为 .h 出现提示时,点击创建桥接标头。这将是我们的桥接头文件。如果您提示,请转到步骤3.如果系统提示,请跳过步骤3直接转到步骤4.

When prompted, click Create Bridging Header. This will be our bridging header file. If you are not prompted, go to step 3. If you are prompted, skip step 3 and go directly to step 4.

在主项目文件夹中创建另一个 .h 文件,名为 Bridge.h 转到应用程序管理器(蓝色页面图标),然后在目标部分中选择您的应用程序,并单击构建设置。找到说明 Swift编译器 - 代码生成的选项,然后将 Objective-C桥接标头选项设置为 Bridge.h

Create another .h file named Bridge.h in the main project folder, Then go to the Application Manager (the blue page-like icon), then select your app in the Targets section, and click Build Settings. Find the option that says Swift Compiler - Code Generation, and then set the Objective-C Bridging Header option to Bridge.h

在您的桥接头文件中,添加 #importMyObjectiveCHeaderFile.h其中 MyObjectiveCHeaderFile 是在步骤一中创建的头文件的名称。因此,例如,如果您将头文件命名为 InAppPurchase.h ,那么您将向您的网桥添加 #importInAppPurchase.h

In your bridging header file, add the line #import "MyObjectiveCHeaderFile.h", where MyObjectiveCHeaderFile is the name of the header file that you created in step one. So, for example, if you named your header file InAppPurchase.h, you would add the line #import "InAppPurchase.h" to your bridge header file.

创建一个新的Objective-C方法( .m code>文件> > > Command⌘ + N )。将其命名为与在步骤1中创建的头文件相同。例如,如果您在步骤1中调用该文件,则会调用此新文件 InAppPurchase.m em>。在本教程的其余部分中,此文件将被称为您的 .m 文件。

Create a new Objective-C Methods (.m) file by going to File > New > File... (Command ⌘ + N). Name it the same as the header file you created in step 1. For example, if you called the file in step 1 InAppPurchase.h, you would call this new file InAppPurchase.m. This file will be referred to as "Your .m file" in the rest of the tutorial.

现在我们要进入实际的编码。将以下代码添加到 .h 文件中:

Now we're going to get into the actual coding. Add the following code into your .h file:

BOOL areAdsRemoved;

- (IBAction)restore;
- (IBAction)tapsRemoveAds;

接下来,您需要导入 StoreKit 框架到您的 .m 文件中,以及添加 SKProductsRequestDelegate SKPaymentTransactionObserver @interface 声明后:$ c>

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

#import <StoreKit/StoreKit.h>

//put the name of your view controller in place of MyViewController
@interface MyViewController() <SKProductsRequestDelegate, SKPaymentTransactionObserver>

@end

@implementation MyViewController //the name of your view controller (same as above)
  //the code below will be added here
@end

现在将以下内容添加到您的 .m 文件,这部分变得复杂,因此我建议您阅读代码中的注释:

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 product

        SKProductsRequest *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];
    }
    else if(!validProduct){
        NSLog(@"No products available");
        //this is called if your product id is not valid, this shouldn't be called unless that happens.
    }
}

- (void)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] addTransactionObserver:self];
    [[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 purchase
            NSLog(@"Transaction state -> Restored");

            //if you have more than one in-app purchase product,
            //you restore the correct product for the identifier.
            //For example, you could use
            //if(productID == kRemoveAdsProductIdentifier)
            //to get the product identifier for the
            //restored purchases, you can use
            //
            //NSString *productID = transaction.payment.productIdentifier;
            [self doRemoveAds];
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
            break;
        }
    }   
}

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions{
    for(SKPaymentTransaction *transaction in transactions){
        switch(transaction.transactionState){
            case SKPaymentTransactionStatePurchasing: NSLog(@"Transaction state -> Purchasing");
                //called when the user is in the process of purchasing, do not add any of your own code here.
                break;
            case SKPaymentTransactionStatePurchased:
            //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;
            case SKPaymentTransactionStateRestored:
                NSLog(@"Transaction state -> Restored");
                //add the same code as you did from SKPaymentTransactionStatePurchased here
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                break;
            case SKPaymentTransactionStateFailed:
                //called when the transaction does not finish
                if(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];
}

现在,在 viewDidLoad 方法,您将要添加以下代码:

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 purchase

if(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
}

现在你已经添加了所有代码,进入你的 .xib storyboard 文件,并添加两个按钮,一个说购买,另一个说恢复。将 tapsRemoveAds IBAction 挂接到刚刚创建的购买按钮, / code> IBAction 到恢复按钮。 restore 操作将检查用户是否先前购买了应用内购买,如果用户还没有购买应用内购买,则可以免费提供应用内购买。

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.

接下来,进入 iTunesConnect ,然后点击用户和角色,然后点击 Sandbox Testers 标题,然后点击左侧的 + 符号它说 Testers 。你可以随意放入名字的姓名,电子邮件不必是真实的 - 你只需要能够记住它。输入密码(您必须记住),并填写其余的信息。我建议您让出生日期一个日期,使用户18岁或以上。 App Store Territory HAS 在正确的国家/地区。接下来,退出现有的iTunes帐户(您可以在本教程后重新登录)。

Next, go into iTunesConnect, and click Users and Roles then click the Sandbox Testers header, 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).

现在,在iOS设备上运行应用程序在模拟器上,购买将始终错误,您 HAVE TO 在您的iOS设备上运行它。应用程式运行后,点击购买按钮。当系统提示您登录iTunes帐户时,以我们刚创建的测试用户身份登录。接下来,当它要求您确认购买99¢或任何您设置的价格层,采取屏幕快照这是你将用于您的 iTunesConnect上的截图。现在取消付款。

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.

现在,转到 iTunesConnect ,然后转到我的应用程序> 您在> / code>。然后点击您的应用内购买,并点击应用内购买详情下的编辑。完成后,将您刚才在iPhone上拍摄的照片导入到计算机中,并将其作为屏幕截图上传以供审核,然后在审核注释中,将您的测试用户电子邮件和密码。这将有助于苹果在审核过程中。

Now, go to iTunesConnect, then go to My Apps > the app you have the In-app purchase on > In-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.

完成此操作后,返回到您的iOS设备上的应用程序,仍然以测试用户帐户登录,单击购买按钮。这一次,请确认付款不要担心,这不会向您的帐户收取任何金额,测试用户帐户免费获得所有应用内购买。确认付款后,确保发生了什么当用户购买你的产品实际发生。如果没有,那么这将是你的 doRemoveAds 方法的一个错误。再次,我建议使用更改背景为蓝色测试应用程序内购买,但这不应该是你实际的应用程序内购买。如果一切工作,你很好去!

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 you're good to go! Just make sure to include the in-app purchase in your new binary when you upload it to iTunesConnect!

已记录: 未提供产品

这可能意味着三件事:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆