• 苹果内购买笔记


    苹果内购买包括4种类型:1.消耗性;  2.非消耗性;3.自动续订订阅;4.非续订订阅.

    首先需要有一个itunesconnect上协议、税务和银行业务模块中有银行卡绑定同时遵守了各种苹果协议的开发帐号;(具体如何申请填写网上百度一堆)

    然后代码前记得添加协议

    <SKPaymentTransactionObserver,SKProductsRequestDelegate,SKRequestDelegate>

    //购买点击
    -(void)payBtnClick
    {
        //购买
            if ([SKPaymentQueue canMakePayments]) {
                [self requestProductData:ProductId];
    
            } else {
                NSLog(@"用户禁止应用内付费购买.");
    
            }
    }
    //恢复点击
    -(void)restoreClick
    {
        [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
    }
    
    //请求商品
    - (void)requestProductData:(NSString *)type{
        NSLog(@"----------请求对应的产品信息---------");
        NSArray *product = [[NSArray alloc] initWithObjects:type, nil];
        NSSet *nsset = [NSSet setWithArray:product];
        SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
        request.delegate = self;
        [request start];
    
    }
    
    - (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    
        NSLog(@"----------收到产品反馈消息-------------");
        NSArray *product = response.products;
    
        if(product.count == 0){
            NSLog(@"------没有商品,商品个数为%ld--------",product.count);
            return;
        }
    
        SKProduct *p = nil;
        for (SKProduct *pro in product) {
    
            if([pro.productIdentifier isEqualToString:ProductId]){
                p = pro;
            }
        }
    
        SKPayment *payment = [SKPayment paymentWithProduct:p];
    
        NSLog(@"发送购买请求");
    
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    
    }
    
    
    - (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions//交易结果
    {
    
        NSLog(@"paymentQueue");
        for (SKPaymentTransaction *transaction in transactions)
        {
    
            switch (transaction.transactionState)
            {
                case SKPaymentTransactionStateRestored://已经购买过该商品,恢复商品
                    [self restoreTransaction:transaction];
                    NSLog(@"-----已经购买过该商品 恢复商品--------");
                    //                [[XTool shareAppHandle]showWait:NO];
                    break;
                case SKPaymentTransactionStatePurchased://交易完成
                    [self completeTransaction:transaction];
                    NSLog(@"-----交易完成 --------");
                    break;
                case SKPaymentTransactionStateFailed://交易失败
                    [self failedTransaction:transaction];
                    NSLog(@"-----交易失败 --------");
                    [[XTool shareAppHandle]showPaiXuWait:NO];
                    break;
                case SKPaymentTransactionStatePurchasing:      //商品添加进列表
                    NSLog(@"-----商品添加进列表 --------");
                    break;
                case SKPaymentTransactionStateDeferred:
                    break;
                default:
                    break;
            }
        }
    
    }
    
    //完成恢复
    - (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue
    {
        NSLog(@"paymentQueueRestoreCompletedTransactionsFinished");
    
        NSLog(@"%@",[queue description]);
    
        NSLog(@"-----完成恢复--------");
    
    }
    
    
    - (void) restoreTransaction: (SKPaymentTransaction *)transaction
    {
        NSLog(@" 交易恢复处理");
        NSLog(@"-----恢复成功--------");
      
        NSData *iapData = transaction.transactionReceipt;
    
    
        // 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];
            }
        }
    
        NSString *results = [[NSString alloc]initWithBytes:[iapData bytes] length:[iapData length] encoding:NSUTF8StringEncoding];
    
        {
               /* 恢复交易信息发送给服务器代码*/
        }
        [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    }
            
    
    //记录交易
    -(void)recordTransaction:(NSString *)product{
        NSLog(@"-----记录交易--------");
    }
    
    //处理下载内容
    -(void)provideContent:(NSString *)product{
        NSLog(@"-----下载--------");
    }
    
    
    -(void) PurchasedTransaction: (SKPaymentTransaction *)transaction{
        NSLog(@"-----PurchasedTransaction----");
        NSArray *transactions =[[NSArray alloc] initWithObjects:transaction, nil];
        [self paymentQueue:[SKPaymentQueue defaultQueue] updatedTransactions:transactions];
        [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    }
    
    - (void) completeTransaction: (SKPaymentTransaction *)transaction
    
    {
        NSLog(@"-----购买成功--------");
    
        NSData *iapData = transaction.transactionReceipt;
    
    
        // 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];
            }
        }
    
        NSString *results = [[NSString alloc]initWithBytes:[iapData bytes] length:[iapData length] encoding:NSUTF8StringEncoding];
        NSLog(@"%@",results);
    
        {
                /*购买信息发送给服务器*/
        }
        [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    
    }    
    
    
    - (void) failedTransaction: (SKPaymentTransaction *)transaction{
     
        if (transaction.error.code != SKErrorPaymentCancelled)
        {
        }
        [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    
    
    }
    
    
    
    - (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
        
        NSLog(@" 购买失败");
    }
    
    -(void) paymentQueue:(SKPaymentQueue *) paymentQueue restoreCompletedTransactionsFailedWithError:(NSError *)error{
        NSLog(@"-------paymentQueue----");
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
        NSLog(@"%ld",(long)[(NSHTTPURLResponse *)response statusCode]);
        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) requestDidFinish:(SKRequest *)request
    {
        NSLog(@"-----反馈信息结束-------");
    
    }
    
    
    - (BOOL)verify:(SKPaymentTransaction *)transaction
    {
        return YES;
    }
    

    购买所需基本代码如上;

    1.消耗型

    宏定义(或者从服务器都行,看需求)获取个购买产品的ID(itunesconnect上申请的产品ID),将上面代码中

    ProductId替换成购买产品的ID

    然后将返回信息发送给服务器进行处理

    然后服务器端和苹果进行购买验证,确认购买成功后,返回给客户端购买产品成功

    客户端显示相应购买内容。

    2.非消耗型

    同消耗型,唯一区别是重复购买,苹果会提示你不能重复购买。跟客户端及服务器没啥关系。

    3.自动续订订阅

    购买流程同消耗型,多了个恢复购买,同时在显示时一定要有提醒用户当前订阅为自动续订的文字说明,否则苹果审核可能被拒

    恢复流程时,用户点击恢复购买后,执行

    restoreClick方法

    进行恢复流程正常的话会执行(不正常,就需要检查产品申请的内容;沙盒测试帐号问题;等等前面步骤是否有错)

    restoreTransaction方法

    在获取到用户购买信息后客户端传给服务器,服务器端和苹果进行数据验证,验证无误后返回给客户端相应用户应该恢复的产品内容,客户端进行展示。

    4.非续订订阅

    购买流程同消耗型;

    恢复流程需要进入页面后点击恢复时执行

    restoreClick方法

    同时执行如下代码进行用户购买记录数据获取,不断获取直到获取到或者用户取消恢复为止。

        NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[[NSBundle mainBundle] appStoreReceiptURL]];
        NSError *error = nil;
        NSData *iapData  = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:&error];
            NSString *transactionReceiptString = [iapData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    

     如果获取到说明用户已经输入了AppleID,并进行了恢复操作;

    此时将获取到的用户购买记录及当前恢复产品ID发送给服务器,服务器和苹果进行购买确认。如果已经购买此产品,则向客户端返回恢复成功信息。客户端展示相应需要恢复展示的内容。

    用户购买记录数据获取还有另一种方法

    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receipt = [NSData dataWithContentsOfURL:receiptURL];

    两种都可以获取,获取的都是全部购买记录,获取后才能进行本地验证或服务器验证

    注意:

        NSData *iapData = transaction.transactionReceipt; 

    上面这句也能获取到购买记录,但是获取的是部分购买记录,而且在iOS7.0已经废除 不建议使用了

    补充:

    本地验证方法:

    //本地验证购买信息
    -(void)validetingReceiptsWith:(NSData *)receipt
    {
        // Create the JSON object that describes the request
        NSError *error;
        NSDictionary *requestContents = @{
                                          @"receipt-data": [receipt base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed],
                                          @"password":@"app专用共享密钥"
                                          };
        NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestContents
                                                              options:0
                                                                error:&error];
        
        if (!requestData) { /* ... Handle error ... */ }
        
        // Create a POST request with the receipt data.
        NSString *urlstr = @"https://sandbox.itunes.apple.com/verifyReceipt";//用测试账号测试的时候
    //    NSString *urlstr = @"https://buy.itunes.apple.com/verifyReceipt";//用生产环境时候
        
        NSURL *storeURL = [NSURL URLWithString:urlstr];
        NSMutableURLRequest *storeRequest = [NSMutableURLRequest requestWithURL:storeURL];
        [storeRequest setHTTPMethod:@"POST"];
        [storeRequest setHTTPBody:requestData];
        
        // Make a connection to the iTunes Store on a background queue.
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        [NSURLConnection sendAsynchronousRequest:storeRequest queue:queue
                               completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                                   if (connectionError) {
                                       /* ... Handle error ... */
                                   } else {
                                       NSError *error;
                                       NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
                                       NSLog(@"jsonResponse :%@",jsonResponse);
                                       if (!jsonResponse) { /* ... Handle error ...*/ }
                                       /* ... Send a response back to the device ... */
                                   }
                               }];
    
    }
    

    如果有 App专用密钥,需要本地验证时添加@"password"如上代码,才能收到验证返回,验证成功如下

    然后即可进行本地处理。非续订订阅需要恢复需要本地服务器处理,自动续订不需要。

  • 相关阅读:
    HDU 1698 Just a Hook (区间更新+延迟标记)
    HDU 1754 I Hate It 线段树
    HDU 1847 Good Luck in CET-4 Everybody! (sg函数)
    博弈汇总
    Codeforces cf 713A Sonya and Queries
    hihoCoder 1082 : 然而沼跃鱼早就看穿了一切
    hihoCoder 1298 : 数论五·欧拉函数
    hdu 5821 Ball
    hdu 5818 Joint Stacks(栈的模拟)
    hdu 5802 Windows 10
  • 原文地址:https://www.cnblogs.com/Ganggang888/p/7264682.html
Copyright © 2020-2023  润新知