# iOS开发内购全套图文教程

语言：zh-CN
原文：[iOS开发内购全套图文教程](<https://allluckly.cn/ios%E6%94%AF%E4%BB%98/iOS%E5%BC%80%E5%8F%912015%E5%B9%B4%E6%9C%80%E6%96%B0%E5%86%85%E8%B4%AD%E6%95%99%E7%A8%8B>)
中文：[中文 HTML](<https://allluckly.cn/ios%E6%94%AF%E4%BB%98/iOS%E5%BC%80%E5%8F%912015%E5%B9%B4%E6%9C%80%E6%96%B0%E5%86%85%E8%B4%AD%E6%95%99%E7%A8%8B>)
English: [English HTML](<https://allluckly.cn/en/journal/2015-06-04-an-illustrated-guide-to-implementing-ios-in-app-purchases/>)
发布于: 2015-06-04T00:00:00+08:00
内容更新于: 2015-06-04T00:00:00+08:00
署名：[Bison](<https://allluckly.cn/about/>)

按协议填写、内购商品创建、沙盒账号配置与客户端代码展开，展示 StoreKit 商品请求、支付队列、交易状态处理及收据验证的早期完整接入过程。

原文署名 Bison，保留原发布时的内容。

**阅读前** 这是 2015–2017 年间的技术记录，本次整理未重新运行验证示例。原文发表于 2015 年，采用 SKProductsRequest、SKPaymentQueue 与 verifyReceipt 的旧式实现。

> "The beginning is the most important part of the work." Plato

==========第一部分协议=======

![1](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/%E7%AC%AC%E4%B8%80%E6%AD%A5.png>)

![2](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/%E7%AC%AC%E4%BA%8C%E6%AD%A5.jpg>)

![3](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/%E7%AC%AC%E4%B8%89%E6%AD%A5.jpg>)

![4](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/%E7%AC%AC%E5%9B%9B%E6%AD%A5.png>)

![5](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/%E7%AC%AC%E4%BA%94%E6%AD%A5.png>)

![6](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/%E7%AC%AC%E5%85%AD%E6%AD%A5.png>)

![7](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/%E7%AC%AC%E4%B8%83%E6%AD%A5.jpg>)

![8](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/%E7%AC%AC%E5%85%AB%E6%AD%A5.jpg>)

![9](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/%E7%AC%AC%E4%B9%9D%E6%AD%A5.jpg>)

![10](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/%E7%AC%AC%E5%8D%81%E6%AD%A5.png>)

CNAPS CODE 查询地址 https://e.czbank.com/CORPORBANK/query\_unionBank\_index.jsp

![11](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/%E5%8D%81%E4%B8%80%E6%AD%A5.jpg>)

![12](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/%E5%8D%81%E4%BA%8C%E6%AD%A5.jpg>)

![13](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/%E5%8D%81%E4%B8%89%E6%AD%A5.png>)

![14](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/%E5%8D%81%E5%9B%9B%E6%AD%A5.png>)

![15](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/%E5%8D%81%E4%BA%94%E6%AD%A5.jpg>)

![16](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/%E5%8D%81%E4%B8%83%E6%AD%A5.jpg>)

![17](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/%E5%8D%81%E5%85%AB%E6%AD%A5.jpg>)

![18](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/%E5%8D%81%E4%B9%9D%E6%AD%A5.png>)

![19](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/%E4%BA%8C%E5%8D%81%E6%AD%A5.png>)

=============第二部分创建内购项目============

![20](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/1.png>)

![21](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/2.png>)

![22](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/3.png>)

![23](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/4.png>)

![24](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/5.png>)

![25](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/6.png>)

![26](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/7.png>)

===========第三部分贴加内购项目测试账号==========

![27](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/%E5%88%9B%E5%BB%BA%E6%B5%8B%E8%AF%95%E8%B4%A6%E5%8F%B7.png>)

![28](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/%E6%B2%99%E7%9B%92%E6%B5%8B%E8%AF%95%E5%91%98.png>)

![29](<https://allluckly.cn/images/2015-06-04-%E5%86%85%E8%B4%AD/%E8%B4%A6%E5%8F%B7%E4%BF%A1%E6%81%AF.png>)

=============第四部分主要实现代码==========

首先导入`StoreKit.framework`库

.h文件

```css
#define kSandboxVerifyURL @"https://sandbox.itunes.apple.com/verifyReceipt" //开发阶段沙盒验证URL
#define kAppStoreVerifyURL @"https://buy.itunes.apple.com/verifyReceipt" //实际购买验证URL
#import <StoreKit/StoreKit.h>




enum{
IAP0p20=20,
IAP1p100,
IAP4p600,
IAP9p1000,
IAP24p6000,
}buyCoinsTag;





//代理
@interface RechargeVC : UIViewController <SKPaymentTransactionObserver,SKProductsRequestDelegate >



{
int buyType;
}



- (void) requestProUpgradeProductData;


-(void)RequestProductData;


-(void)buy:(int)type;


- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions;


-(void) PurchasedTransaction: (SKPaymentTransaction *)transaction;


- (void) completeTransaction: (SKPaymentTransaction *)transaction;


- (void) failedTransaction: (SKPaymentTransaction *)transaction;


-(void) paymentQueueRestoreCompletedTransactionsFinished: (SKPaymentTransaction *)transaction;


-(void) paymentQueue:(SKPaymentQueue *) paymentQueue restoreCompletedTransactionsFailedWithError:(NSError *)error;



- (void) restoreTransaction: (SKPaymentTransaction *)transaction;


-(void)provideContent:(NSString *)product;


-(void)recordTransaction:(NSString *)product;



@end
```

.m文件

```css
#import "RechargeVC.h"


//在内购项目中创的商品单号
#define ProductID_IAP0p20 @"Nada.JPYF01"//20
#define ProductID_IAP1p100 @"Nada.JPYF02" //100
#define ProductID_IAP4p600 @"Nada.JPYF03" //600
#define ProductID_IAP9p1000 @"Nada.JPYF04" //1000
#define ProductID_IAP24p6000 @"Nada.JPYF05" //6000



@interface RechargeVC ()

@end


@implementation RechargeVC


- (void)viewDidLoad {

    [super viewDidLoad];

    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    [self buy:IAP0p20];

}


-(void)buy:(int)type
{
    buyType = type;
    if ([SKPaymentQueue canMakePayments]) {
    [self RequestProductData];
    NSLog(@"允许程序内付费购买");
}
else
{
    NSLog(@"不允许程序内付费购买");
    UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:@"提示"
    message:@"您的手机没有打开程序内付费购买"
    delegate:nil cancelButtonTitle:NSLocalizedString(@"关闭",nil) otherButtonTitles:nil];

    [alerView show];


    }
}

-(void)RequestProductData
{
    NSLog(@"---------请求对应的产品信息------------");
    NSArray *product = nil;
    switch (buyType) {
        case IAP0p20:
        product=[[NSArray alloc] initWithObjects:ProductID_IAP0p20,nil];
        break;
        case IAP1p100:
        product=[[NSArray alloc] initWithObjects:ProductID_IAP1p100,nil];
        break;
        case IAP4p600:
        product=[[NSArray alloc] initWithObjects:ProductID_IAP4p600,nil];
        break;
        case IAP9p1000:
        product=[[NSArray alloc] initWithObjects:ProductID_IAP9p1000,nil];
        break;
        case IAP24p6000:
        product=[[NSArray alloc] initWithObjects:ProductID_IAP24p6000,nil];
        break;

        default:
        break;
}
    NSSet *nsset = [NSSet setWithArray:product];
    SKProductsRequest *request=[[SKProductsRequest alloc] initWithProductIdentifiers: nsset];
    request.delegate=self;
    [request start];

}

//<SKProductsRequestDelegate> 请求协议
//收到的产品信息
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{

    NSLog(@"-----------收到产品反馈信息--------------");
    NSArray *myProduct = response.products;
    NSLog(@"产品Product ID:%@",response.invalidProductIdentifiers);
    NSLog(@"产品付费数量: %d", (int)[myProduct count]);
    // populate UI
    for(SKProduct *product in myProduct){
    NSLog(@"product info");
    NSLog(@"SKProduct 描述信息%@", [product description]);
    NSLog(@"产品标题 %@" , product.localizedTitle);
    NSLog(@"产品描述信息: %@" , product.localizedDescription);
    NSLog(@"价格: %@" , product.price);
    NSLog(@"Product id: %@" , product.productIdentifier);
}
    SKPayment *payment = nil;
    switch (buyType) {
        case IAP0p20:
        payment  = [SKPayment paymentWithProductIdentifier:ProductID_IAP0p20];    //支付25
        break;
        case IAP1p100:
        payment  = [SKPayment paymentWithProductIdentifier:ProductID_IAP1p100];    //支付108
        break;
        case IAP4p600:
        payment  = [SKPayment paymentWithProductIdentifier:ProductID_IAP4p600];    //支付618
        break;
        case IAP9p1000:
        payment  = [SKPayment paymentWithProductIdentifier:ProductID_IAP9p1000];    //支付1048
        break;
        case IAP24p6000:
        payment  = [SKPayment paymentWithProductIdentifier:ProductID_IAP24p6000];    //支付5898
        break;
        default:
        break;
}
    NSLog(@"---------发送购买请求------------");
    [[SKPaymentQueue defaultQueue] addPayment:payment];

}
- (void)requestProUpgradeProductData
{
    NSLog(@"------请求升级数据---------");
    NSSet *productIdentifiers = [NSSet setWithObject:@"com.productid"];
    SKProductsRequest* productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];
    productsRequest.delegate = self;
    [productsRequest start];

}
//弹出错误信息
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    NSLog(@"-------弹出错误信息----------");
    UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert",NULL) message:[error localizedDescription]
    delegate:nil cancelButtonTitle:NSLocalizedString(@"Close",nil) otherButtonTitles:nil];
    [alerView show];

}

-(void) requestDidFinish:(SKRequest *)request
{
    NSLog(@"----------反馈信息结束--------------");

}

-(void) PurchasedTransaction: (SKPaymentTransaction *)transaction{
    NSLog(@"-----PurchasedTransaction----");
    NSArray *transactions =[[NSArray alloc] initWithObjects:transaction, nil];
    [self paymentQueue:[SKPaymentQueue defaultQueue] updatedTransactions:transactions];
}

//<SKPaymentTransactionObserver> 千万不要忘记绑定，代码如下：
//----监听购买结果
//[[SKPaymentQueue defaultQueue] addTransactionObserver:self];

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions//交易结果
{
    NSLog(@"-----paymentQueue--------");
    for (SKPaymentTransaction *transaction in transactions)
    {
        switch (transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchased:{//交易完成
            [self completeTransaction:transaction];
            NSLog(@"-----交易完成 --------");
            //购买成功后进行验证
            [self verifyPurchaseWithPaymentTransaction];

        } break;
        case SKPaymentTransactionStateFailed://交易失败
            { [self failedTransaction:transaction];
            NSLog(@"-----交易失败 --------");
            UIAlertView *alerView2 =  [[UIAlertView alloc] initWithTitle:@"提示"
            message:@"购买失败，请重新尝试购买"
            delegate:nil cancelButtonTitle:NSLocalizedString(@"关闭",nil) otherButtonTitles:nil];

            [alerView2 show];

        }break;
        case SKPaymentTransactionStateRestored://已经购买过该商品
            [self restoreTransaction:transaction];
            NSLog(@"-----已经购买过该商品 --------");
            case SKPaymentTransactionStatePurchasing:      //商品添加进列表
            NSLog(@"-----商品添加进列表 --------");
            break;
            default:
            break;
        }
    }
}

/**
*  验证购买，避免越狱软件模拟苹果请求达到非法购买问题
*
*/
-(void)verifyPurchaseWithPaymentTransaction{
    //从沙盒中获取交易凭证并且拼接成请求体数据
    NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];

    NSString *receiptString=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];//转化为base64字符串

    NSString *bodyString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", receiptString];//拼接请求数据
    NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];

    //创建请求到苹果官方进行购买验证
    NSURL *url=[NSURL URLWithString:kSandboxVerifyURL];
    NSMutableURLRequest *requestM=[NSMutableURLRequest requestWithURL:url];
    requestM.HTTPBody=bodyData;
    requestM.HTTPMethod=@"POST";
    //创建连接并发送同步请求
    NSError *error=nil;
    NSData *responseData=[NSURLConnection sendSynchronousRequest:requestM returningResponse:nil error:&error];
    if (error) {
        NSLog(@"验证购买过程中发生错误，错误信息：%@",error.localizedDescription);
        return;
    }
    NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];
    NSLog(@"%@",dic);
    if([dic[@"status"] intValue]==0){
        NSLog(@"购买成功！");
        NSDictionary *dicReceipt= dic[@"receipt"];
        /*
        PS.如果你的商品比较多的话，最好给dicReceipt[@"in_app"]按照最新时间做下排序再取firstObject，由于网络延迟难免出现延迟等现象导致当前firstObject可能并不是我们现在所买商品的凭证。
        */
        NSDictionary *dicInApp=[dicReceipt[@"in_app"] firstObject];
    
        NSString *productIdentifier= dicInApp[@"product_id"];//读取产品标识
        //如果是消耗品则记录购买数量，非消耗品则记录是否购买过
        NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
        if ([productIdentifier isEqualToString:kProductID3]) {
            int purchasedCount=[defaults integerForKey:productIdentifier];//已购买数量
            [[NSUserDefaults standardUserDefaults] setInteger:(purchasedCount+1) forKey:productIdentifier];
        }else{
            [defaults setBool:YES forKey:productIdentifier];
        }
        [self.tableView reloadData];
        //在此处对购买记录进行存储，可以存储到开发商的服务器端
    }else{
        NSLog(@"购买失败，未通过验证！");
    }
}

- (void) completeTransaction: (SKPaymentTransaction *)transaction

{
    NSLog(@"-----completeTransaction--------");
    // Your application should implement these two methods.
    NSString *product = transaction.payment.productIdentifier;
    if ([product length] > 0) {

    NSArray *tt = [product componentsSeparatedByString:@"."];
    NSString *bookid = [tt lastObject];
    if ([bookid length] > 0) {
    [self recordTransaction:bookid];
    [self provideContent:bookid];
}
}

    // Remove the transaction from the payment queue.

    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];

}

//记录交易
-(void)recordTransaction:(NSString *)product{
    NSLog(@"-----记录交易--------");
}

//处理下载内容
-(void)provideContent:(NSString *)product{
    NSLog(@"-----下载--------");
}

- (void) failedTransaction: (SKPaymentTransaction *)transaction{
    NSLog(@"失败");
    if (transaction.error.code != SKErrorPaymentCancelled)
    {

    }
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];

}
-(void) paymentQueueRestoreCompletedTransactionsFinished: (SKPaymentTransaction *)transaction{

}

- (void) restoreTransaction: (SKPaymentTransaction *)transaction
{
    NSLog(@" 交易恢复处理");

}

-(void) paymentQueue:(SKPaymentQueue *) paymentQueue restoreCompletedTransactionsFailedWithError:(NSError *)error{
    NSLog(@"-------paymentQueue----");
}

#pragma mark connection delegate
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"%@",  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    switch([(NSHTTPURLResponse *)response statusCode]) {
        case 200:
        case 206:
        break;
        case 304:
        break;
        case 400:
        break;
        case 404:
        break;
        case 416:
        break;
        case 403:
        break;
        case 401:
        case 500:
        break;
        default:
        break;
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"test");
}

-(void)dealloc
{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];//解除监听

}

@end
```

