iOS应用内置付费In-App Purchase 个人使用总结

移动开发 iOS
添加Storekit.Framework,编写自己的storeObsever,用于处理交易,代码如下,其中completeTransaction 和failedTransaction两个函数是自定义的用来处理交易成功与失败其它的就都是SKPaymentTransactionObserver 这个代理要求的。

上一个项目用到了In App Purchase,发现现在大家对这个挺关注的,把上次写的总结贴出来给大家看一下,希望对大家有点帮助!

一、有关如何在程序中加入In APP Purchase 的内容参考下面的连接

http://developer.apple.com/iphone/library/documentation/NetworkingInternet/Conceptual/StoreKitGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40008267-CH1-SW1

二、我的程序具体步骤

1.添加Storekit.Framework,编写自己的storeObsever,用于处理交易,代码如下,其中completeTransaction 和failedTransaction两个函数是自定义的用来处理交易成功与失败其它的就都是SKPaymentTransactionObserver 这个代理要求的。

  1. #import <Foundation/Foundation.h>  
  2. #import <StoreKit/StoreKit.h>  
  3. #import <StoreKit/SKPaymentTransaction.h>  
  4. @interface MyStoreObserver : NSObject < SKPaymentTransactionObserver > { 
  5.  
  6. - (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions;  
  7.  
  8. -(void) PurchasedTransaction: (SKPaymentTransaction *)transaction;  
  9.  
  10. - (void) completeTransaction: (SKPaymentTransaction *)transaction;  
  11.  
  12. - (void) failedTransaction: (SKPaymentTransaction *)transaction; 
  13.  
  14.  -(void) paymentQueueRestoreCompletedTransactionsFinished: (SKPaymentTransaction *)transaction; 
  15.  
  16.  -(void) paymentQueue:(SKPaymentQueue *) paymentQueue restoreCompletedTransactionsFailedWithError:(NSError *)error;  
  17. @end  
  18.  
  19. - (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions函数用来更新transactions的状态 
  20.  
  21.  - (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {  
  22.      for (SKPaymentTransaction* transaction in transactions)  {   
  23.         switch (transaction.transactionState)  {   
  24.         case SKPaymentTransactionStatePurchased:   
  25.             [self completeTransaction:transaction];   
  26.             break;   
  27.         case SKPaymentTransactionStateFailed:  
  28.              [self failedTransaction:transaction];   
  29.             break;   
  30.         case SKPaymentTransactionStateRestored:  
  31.              break;   
  32.         default:   
  33.             break;   
  34.         }   
  35.     }  
  36. }  

2.在程序中添加storeObsever,最好在applicationDidFinishLaunching中添加

  1. MyStoreObserver *tempObserver = [[MyStoreObserver alloc] init];   
  2.  
  3. self.observer = tempObserver;   
  4.  
  5. [tempObserver release]; 
  6.  
  7. [[SKPaymentQueue defaultQueue] addTransactionObserver:self.observer];  

3.发送付费请求,在相应的类中实现SKProductsRequestDelegate,别忘记定义自己产品的identifier

  1. //请求产品信息  
  2.  #define kMyFeatureIdentifier yourProductIdentifiers  (你自己的产品identifiers) 
  3. SKProductsRequest *request= [[SKProductsRequest alloc] initWithProductIdentifiers:  
  4.  [NSSet setWithObject: kMyFeatureIdentifier]];  
  5.  request.delegate = self;  
  6. [request start];   

代理方法相关代码,如果请求成功的话就可以发送付费请求

  1. #pragma mark request delegate 
  2.  //!收到产品的消息  
  3.  
  4. - (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{    
  5.     SKPayment *payment = [SKPayment paymentWithProductIdentifier:kMyFeatureIdentifier];  
  6.      [[SKPaymentQueue defaultQueue] addPayment:payment];  
  7.     [request autorelease]; 
  8.   } 
  9.  
  10. - (void)request:(SKRequest *)request didFailWithError:(NSError *)error{   
  11. UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:@"Alert" message:[error localizedDescription]  delegate:nil c 
  12.     ancelButtonTitle:NSLocalizedString(@"Close",nil)  otherButtonTitles:nil];  [alerView show]; [alerView release];  

4.接下来就是Apple自己的付费相关处理了,需要做是就是点击按钮来确定付费

5.交易完成后需要向Apple验证这次交易是否成功,要不然没成功就把产品给别人的话,那就亏了,在1中可以看到当交易成功时会调用自定义的 completeTransaction函数,在该函数中我们需要验证transactionReceipt 关于验证SKPaymentTransaction的transactionReceipt transactionReceipt是只有当 SKPaymentTransaction完成时,即transactionState 被设置为SKPaymentTransactionStatePurchased 或 SKPaymentTransactionStateRestored时才被创建,因此只有这两种状态下能去验证transactionReceipt

原始思路及具体步骤如下: 

a、从SKPaymentTranscation的实例中将transactionReceipt转化为NSString   

  1. NSString *temptransactionReceipt  = [[NSString alloc] initWithData:[mytransaction transactionReceipt] encoding:NSUTF8StringEncoding]; 

如果用NSLog的方法将其写出来显示如下,里边有很多的‘+’

  1. "signature" =  
  2.  
  3. "AZNZdoggtjbU/wMqZ4SSd3lgkxbWr+/zcV7Oez4io7f5oPMliKlQzWW4vj+FLsVyhjyyuPyTSugJ6m4Hrp+CjdAptGZg4iWExoyE6stltg0EfD8Ezggjg5q04ws74pMZ/0aRgjedua8dCMMqR7C8ZjojfOYU6LrFiK7qbUUiV+inMIIDUzCCAjugAwIBAgIIZRSRTdlYBLUwDQYJKoZIhvcNAQEFBQAwfzELMAkGA1UEBhMCVVMxEzARBgNVBAoMCkFwcGxlIEluYy4xJjAkBgNVBAsMHUFwcGxlIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MTMwMQYDVQQDDCpBcHBsZSBpVHVuZXMgU3RvcmUgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDkwNjE1MjIwNTU2WhcNMTQwNjE0MjIwNTU2WjBkMSMwIQYDVQQDDBpQdXJjaGFzZVJlY2VpcHRDZXJ0aWZpY2F0ZTEbMBkGA1UECwwSQXBwbGUgaVR1bmVzIFN0b3JlMRMwEQYDVQQKDApBcHBsZSBJbmMuMQswCQYDVQQGEwJVUzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAytGMXZy3gitJ2JMKFojSDynC/9yYezyn9HBX+u3/3VcpWE2XhcgGKYqNBA1+AewOzrKO774OsokTu4qymEx10ph8UTmsZewB0ESMHBEjF7FN6/HccsQUYC3WagrHnT12HG2Ih0OAm/ZhpWzj0HS4m813LpIyo00sewMvMNL2hkcCAwEAAaNyMHAwDAYDVR0TAQH/BAIwADAfBgNVHSMEGDAWgBQ2HejinYLSARi1MmsO10MLkVhDOjAOBgNVHQ8BAf8EBAMCB4AwHQYDVR0OBBYEFKmDg/IZSMU+ElcIFMzNo36ZXyT1MBAGCiqGSIb3Y2QGBQEEAgUAMA0GCSqGSIb3DQEBBQUAA4IBAQARpJs+O2Y3gL8gHdASkrfZHFpwINd1VcB5VF5LkVpnFz63zylA/3cGIDG91b/d5NIwZjkVt4Bgvd62o/mCbzCsWiNfSKTJVFK1D78BDQoSO2oHTuQuz1BR7xzNHxQZ90zUS6ZX9SC8N3g3A1jEtAyDhZNB+CRBBXLwZdnBUeBsT9QLpjvTnekZcGTnU08zfCjGF3eBJEu9eP6WgexK1xMSp72kEOmYbn6yTi3D4YrcYx4Q3n/57VBP2en8qXWeP5oHDsLTGzLRsWdoB3VxJLrF2ivL8JS8zqC0qyac452pN6xunRuzyyfpaqzQL12BzFEe44xna2byektSbtquA5LNAAAAAA==""purchase-info" = "ewoJIml0ZW0taWQiID0gIjMzMDU5OTg4MCI7Cgkib3JpZ2luYWwtdHJhbnNhY3Rpb24taWQiID0gIjEwMDAwMDAwMDAwOTEyNTgiOwoJInB1cmNoYXNlLWRhdGUiID0gIjIwMDktMTAtMTQgMDY6MDY6NTQgRXRjL0dNVCI7CgkicHJvZHVjdC1pZCIgPSAiY29tLnNlbnNreS5jbmFtZXNpZ3B1cmNoYXNlY29uc3VtYWJsZSI7CgkidHJhbnNhY3Rpb24taWQiID0gIjEwMDAwMDAwMDAwOTEyNTgiOwoJInF1YW50aXR5IiA9ICIxIjsKCSJvcmlnaW5hbC1wdXJjaGFzZS1kYXRlIiA9ICIyMDA5LTEwLTE0IDA2OjA2OjU0IEV0Yy9HTVQiOwoJImJpZCIgPSAiY29tLnNlbnNreS5jc2lnbmF0dXJlYXBwIjsKCSJidnJzIiA9ICIxLjAiOwp9""pod" = "100""signing-status" = "0";}     

b、然后通过Post的方法将其提交给服务器,在这里只是将transactionReceipt传给服务器,验证由服务器完成。代码如下,

  1. NSString *requestStirng =[NSString stringWithFormat: @"receipt_data=%@",temptransactioReceipt];   
  2. requestStirng = [requestStirng stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  
  3.  NSData *postData = [NSData dataWithBytes:[requestStirng UTF8String] length:[requestStirng length]];  
  4. NSMutableURLRequest *connectionRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[kURL          stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]; 
  5. [connectionRequest setHTTPMethod:@"POST"];   
  6. [connectionRequest setTimeoutInterval:120.0];  
  7. [connectionRequest setCachePolicy:NSURLRequestUseProtocolCachePolicy];  
  8. [connectionRequest setHTTPBody:postData];   

出现的错误,服务器用传过去的receipt_data向Apple验证,通不过,但将用NSLog的方法在后台写出的 temptransactionreceipt向Apple验证能通过  错误原因  对比发现通过URL传给服务器的字符串不能很好的完成urlEncode,在里边出现的+不能自动进行编码转化,因为在Objective-C 中不能将NSString 真正的实现URL encode , 

解决方法可参考下面的地址  

http://simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/

但当我用上面地址给出的方法进行编码后仍不能解决该问题,原因不明 

解决办法:

在将transactionReceipt转化成的NSString传给服务器之前先进行转化,将里边的+转换为%2B , 将步骤a中的代码改为

  1. NSString *temptransactionReceipt  = [[NSString alloc] initWithData:[mytransaction transactionReceipt] encoding:NSUTF8StringEncoding];  
  2.  
  3.  temptransactionReceipt =  [temptransactionReceipt stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];   

6.服务器端验证相关代码 其中XML为自定义的一个类,getHeader所做的工作就是把receipt数据Post给Apple然后得到返回的结果返回 

  1. $url = "https://buy.itunes.apple.com/verifyReceipt";/ $receipt = json_encode(array("receipt-data" => base64_encode($receipt_data)));      
  2. $response_json = $Xml->getHeader($url, $receipt);     
  3.  $response = json_decode($response_json['content'], true); 
  4. getHeader的代码如下  public function getHeader($url, $data)         {  
  5.                    $ch = curl_init();  
  6.                     $timeout = 300; // set to zero for no timeout   
  7.                  curl_setopt($ch, CURLOPT_URL, $url);  
  8.          //       curl_setopt($ch, CURLOPT_ENCODING, 'gzip');  
  9.                   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); //post到https  
  10.                   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
  11.                    curl_setopt($ch, CURLOPT_POST, true);  
  12.                   curl_setopt($ch, CURLOPT_POSTFIELDS, $data);   
  13.                  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);   
  14.                  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);//跟随页面的跳转 
  15.          //       curl_setopt($ch, CURLOPT_HEADER, true);  
  16.                   curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);  
  17.                    $handles = curl_exec($ch);  
  18.                   $header = curl_getinfo($ch); 
  19.                    curl_close($ch);  
  20.                   $header['content'] = $handles;  
  21.                   return $header;  
  22.         }  

把自己写的测试的例子传上来供大家参考下

下载Demo例子源码下载地址:http://down.51cto.com/data/611901

责任编辑:闫佳明 来源: cocoachina
相关推荐

2013-09-09 13:57:27

iOS应用内置付费In-App Purc

2013-09-09 16:11:16

iOS应用内置付费IAP总结

2013-09-05 15:12:09

iOS应用内置付费In-App Purc

2013-09-09 15:05:12

iOS应用内置付费IAP完全攻略

2013-09-09 15:49:44

iOS应用内置付费IAP设置总结

2013-09-09 16:37:48

iOS应用添加内置收费In App Purc

2013-09-09 17:23:29

iOS应用内置付费IAP

2013-08-06 15:10:18

iOS免费应用移动应用市场移动应用盈利

2013-04-12 15:53:39

2011-12-29 15:28:37

App CookeriOS应用

2011-11-16 15:47:04

AdobeAIRiOS应用

2012-11-20 10:22:34

App Store应用商店

2014-12-30 11:37:38

bmobapp

2010-11-04 09:57:38

In App PurcAndroid 2.3Android

2011-11-16 15:08:30

AdobeAIRiOS应用

2011-06-01 14:50:55

iOS谷歌

2013-05-17 10:19:17

2012-01-05 09:19:25

iOSApp应用

2011-12-30 22:06:42

App

2017-07-24 16:27:58

前端移动端布局
点赞
收藏

51CTO技术栈公众号