【iOS開發必收藏】詳解iOS應用程序內使用IAP/StoreKit付費、沙盒(SandBox)測試、建立測試帳號流程!

 Himi  原創, 歡迎轉載,轉載請在明顯處註明! 謝謝。node

             原文地址:http://blog.csdn.net/xiaominghimi/article/details/6937097網絡


       終於在11月公司的遊戲即將上線了,那麼對於iOS遊戲來講當今都是內置道具收費屬於主流,那麼咱們的遊戲也是內置收費,因此Himi這裏分享給你們關於內置應用收費以及申請測試帳號進行測試購買的經驗;app

      在應用內嵌入付費代碼這一快Himi能夠直接將代碼分享給你們,因此咱們來講一些主要流程,畢竟沒有接觸過這一塊的童鞋確定至關頭疼 =。  =框架

     OK,步入總體,若是你想在iOS裏內嵌收費,那麼分爲如下幾步:ide

            

             【提示:如下建立App部份內容,你不用非要等項目能打包了纔開始作,能夠隨時而且隨便的建立個測試項目便可,由於嵌入付費並不要求上傳App的ipa包的!!】          測試

 

     第一步:你須要在iTunesConnect中建立個新的App,而後爲這個App設置一些產品(付費道具)等;網站

     OK,這裏Himi稍微解釋下,iTunesConnect是蘋果提供的一個平臺,主要提供AP發佈和管理App的,最重要的功能是建立管理項目信息,項目付費產品(道具)管理、付費的測試帳號、提交App等等,這裏就簡單介紹這麼多,關於產品一詞在此咱們能夠理解成遊戲道具便可;在蘋果看來全部付費都屬於產品 =。 =千萬不要糾結字眼哦~this

    OK,打開iTunesConnect網站:https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa (注意:企業級的用戶必須使用公司主開發者帳號登錄纔可!)spa

    成功登錄後的頁面以下:.net


              

              這裏大概說下重要的一些項:

             Contracts, Tax, and Banking   : 管理銀行帳號、聯繫人以及稅等等;這裏要根據提示完成對應的信息填寫!必定要詳細填寫喔~

             Manage Users :管理用戶的,好比主帳號以及測試付費的(測試App)帳號;

             Manage Your Applictions:管理應用程序的,你全部發布的應用和每一個應用的狀態都在這裏面;


     下面咱們新建一個App項目,你們放心,咱們這裏建立的是不會直接提交給App審覈的,因此放心建立,只要控制好App的狀態不要是待審覈狀態便可,不過即便你不當心將項目提交了,也沒事,直接更改App狀態便可了;

     選擇Manage Your Applictions選項,而後新建一個項目:【Add New App】,根據提示來填寫吧,這裏就不細緻說明了~

     建立好一個App以後,在點擊Manage Your Applictions後的界面應該以下:

     

    這裏你將看到本身建立的App,點擊你建立的App項目,這裏Himi建立的項目名字叫」ProjectForBuyTest「,點擊你的App進入以下界面:



    

  (注意:這裏的Bundle ID必定要跟你的項目中的info.plist中的Bundle ID保證一致!!!!)

     這裏能夠管理你的項目的信息、狀態、是否嵌入GameCenter等等選項,那麼本章咱們重點介紹如何使用IAp沙盒測試程序內付費,因此這裏咱們點擊右上角的」Manage In-App Purchases「選項進入建立產品(遊戲道具)界面以下:



      上圖中的下方看到Himi建立過的四個產品(道具)了,你能夠點擊」Create New「選項新建一個產品(付費道具),點擊新建以下界面:


  

   上圖中Himi沒有截圖出全部的選項,這裏大概介紹下,這個界面是選擇你的消費道具的種類,種類說明以下:

   類型選擇有四種選擇:

   1.Consumable(消耗品): 每次下載都須要付費;

   2.Non-consumable(非消耗品): 僅需付費一次;

   3.Auto-Renewable Subscriptions:自動訂閱;

   4.Free Subscription:免費訂閱

   最下方是你沙盒測試的截圖,暫且無論便可;

   這裏Himi選擇Consumable選項,好比不少遊戲都是購買金幣啦這樣子就能夠選擇這個;而後出現以下界面:



   Reference Name: 付費產品(道具的)參考名稱

   Product ID(產品ID): 你產品的惟一id。一般格式是 com.xx.yy,但它能夠是任何形式,不要求以程序的App ID做爲前綴。

   Add Language: 添加產品名稱與描述語言;

   Price Tier:選擇價格,這裏你選擇價格後,會出現如上圖最下方的價格對照表

   Screenshot(截屏): 展現你產品的截屏。(這個直接無視,測試App務必要管這個的)


  Product ID(產品ID)能夠建立多個,好比我想遊戲中分爲0.99$ 、1.99$等道具那就建立對應多個產品ID

  咱們填寫好了」Reference Name「與」Product ID「以及」Price Tier「後,點擊」Add Language「選項而後出現以下界面:

            


  上圖中的選項:

      Language:語言

      Displayed Name(顯示名稱): 用戶看到的產品名稱。

      Description(描述): 對產品進行描述。

  

  Ok,一路 Save保存回到」Manage In-App Purchases「界面中會看到咱們新建的產品(道具)以下:

 


  你們能夠看到新建的產品(道具)ID:這裏Himi建立的產品ID是com.himi.wahaha ,這裏要記住這個產品ID哦~

 

第二步:申請測試帳號,利用沙盒測試模擬AppStore購買道具流程!

  回到itunesconnect主頁中,選擇「Manage Users」而後選擇「Test User」,而後出現的界面以下圖:


    這裏Himi已經建立了兩個測試帳號了,點擊界面中的 「Add New User」進行建立便可;記住帳號和密碼哈,記不住就刪掉從新建 娃哈哈~(切記:不能用於真正的AppStore中使用此帳號,不只不能用,並且一旦AppStore發現後果你懂得~) 


   第三步:在項目中申請購買產品代碼以及監聽;

         這裏關於購買的代碼部分呢,我都有備註的,Himi這裏就不詳細講解了,Himi只是在代碼後介紹幾點值得注意的地方:

 

 這裏Himi是新建的一個Cocos2d的項目,而後給出HelloWorldLayer.h以及HelloWorldLayer.m的所有代碼,全部購買代碼也全在裏面也對應有Himi的註釋!

          HelloWorldLayer.h

view plain  

  1. //  

  2. //  HelloWorldLayer.h  

  3. //  buytest  

  4. //  

  5. //  Created by 華明 李 on 11-10-29.  

  6. //  Copyright Himi 2011年. All rights reserved.  

  7. //  

  8.   

  9.   

  10. // When you import this file, you import all the cocos2d classes  

  11. #import "cocos2d.h"  

  12. #import <UIKit/UIKit.h>  

  13.   

  14. #import <StoreKit/StoreKit.h>  

  15. enum{  

  16.      IAP0p99=10,  

  17.      IAP1p99,  

  18.      IAP4p99,  

  19.      IAP9p99,   

  20.      IAP24p99,  

  21. }buyCoinsTag;   

  22.   

  23. @interface HelloWorldLayer : CCLayer<SKProductsRequestDelegate,SKPaymentTransactionObserver>  

  24. {  

  25.     int buyType;  

  26. }  

  27.   

  28. +(CCScene *) scene;    

  29. - (void) requestProUpgradeProductData;  

  30. -(void)RequestProductData;  

  31. -(bool)CanMakePay;                               

  32. -(void)buy:(int)type;   

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

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

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

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

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

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

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

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

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

  42. @end  

     
             HelloWorldLayer.m

view plain  

  1. //  

  2. //  IapLayer.m  

  3. //  

  4. //  Created by Himi on 11-5-25.  

  5. //  Copyright 2011年 李華明 . All rights reserved.  

  6. //  

  7.   

  8. #import "HelloWorldLayer.h"   

  9. #define ProductID_IAP0p99 @"com.buytest.one"//$0.99    

  10. #define ProductID_IAP1p99 @"com.buytest.two" //$1.99   

  11. #define ProductID_IAP4p99 @"com.buytest.three" //$4.99    

  12. #define ProductID_IAP9p99 @"com.buytest.four" //$19.99    

  13. #define ProductID_IAP24p99 @"com.buytest.five" //$24.99    

  14.   

  15. @implementation HelloWorldLayer  

  16. +(CCScene *) scene  

  17. {  

  18.     CCScene *scene = [CCScene node];  

  19.     HelloWorldLayer *layer = [HelloWorldLayer node];  

  20.     [scene addChild: layer];  

  21.     return scene;  

  22. }  

  23. -(id)init  

  24. {  

  25.     if ((self = [super init])) {  

  26.         CGSize size = [[CCDirector sharedDirector] winSize];  

  27.         CCSprite *iap_bg  = [CCSprite spriteWithFile:@"Icon.png"];    

  28.         [iap_bg setPosition:ccp(size.width/2,size.height/2)];  

  29.         [self addChild:iap_bg z:0];  

  30.         //---------------------  

  31.         //----監聽購買結果  

  32.         [[SKPaymentQueue defaultQueue] addTransactionObserver:self];  

  33.         //申請購買  

  34.         /* 

  35.          enum{ 

  36.          IAP0p99=10, 

  37.          IAP1p99, 

  38.          IAP4p99, 

  39.          IAP9p99, 

  40.          IAP24p99, 

  41.          }buyCoinsTag; 

  42.          */  

  43.         [self buy:IAP24p99];  

  44.     }  

  45.     return self;  

  46. }  

  47.   

  48. -(void)buy:(int)type  

  49. {   

  50.     buyType = type;    

  51.     if ([SKPaymentQueue canMakePayments]) {  

  52.         //[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];  

  53.         [self RequestProductData];    

  54.         CCLOG(@"容許程序內付費購買");  

  55.     }  

  56.     else  

  57.     {  

  58.         CCLOG(@"不容許程序內付費購買");   

  59.         UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:@"Alert"   

  60.                                                             message:@"You can‘t purchase in app store(Himi說你沒容許應用程序內購買)"                                                          

  61.                                                            delegate:nil cancelButtonTitle:NSLocalizedString(@"Close(關閉)",nil) otherButtonTitles:nil];  

  62.           

  63.         [alerView show];  

  64.         [alerView release];  

  65.           

  66.     }   

  67. }  

  68.    

  69. -(bool)CanMakePay  

  70. {  

  71.     return [SKPaymentQueue canMakePayments];  

  72. }  

  73.   

  74. -(void)RequestProductData  

  75. {  

  76.     CCLOG(@"---------請求對應的產品信息------------");  

  77.     NSArray *product = nil;  

  78.     switch (buyType) {  

  79.         case IAP0p99:  

  80.             product=[[NSArray alloc] initWithObjects:ProductID_IAP0p99,nil];  

  81.             break;  

  82.         case IAP1p99:  

  83.             product=[[NSArray alloc] initWithObjects:ProductID_IAP1p99,nil];  

  84.             break;  

  85.         case IAP4p99:  

  86.             product=[[NSArray alloc] initWithObjects:ProductID_IAP4p99,nil];  

  87.             break;  

  88.         case IAP9p99:  

  89.             product=[[NSArray alloc] initWithObjects:ProductID_IAP9p99,nil];  

  90.             break;  

  91.         case IAP24p99:  

  92.             product=[[NSArray alloc] initWithObjects:ProductID_IAP24p99,nil];  

  93.             break;  

  94.               

  95.         default:  

  96.             break;  

  97.     }  

  98.     NSSet *nsset = [NSSet setWithArray:product];  

  99.     SKProductsRequest *request=[[SKProductsRequest alloc] initWithProductIdentifiers: nsset];  

  100.     request.delegate=self;  

  101.     [request start];  

  102.     [product release];  

  103. }  

  104. //<SKProductsRequestDelegate> 請求協議  

  105. //收到的產品信息  

  106. - (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{  

  107.       

  108.     NSLog(@"-----------收到產品反饋信息--------------");  

  109.     NSArray *myProduct = response.products;  

  110.     NSLog(@"產品Product ID:%@",response.invalidProductIdentifiers);  

  111.     NSLog(@"產品付費數量: %d", [myProduct count]);  

  112.     // populate UI   

  113.     for(SKProduct *product in myProduct){  

  114.         NSLog(@"product info");  

  115.         NSLog(@"SKProduct 描述信息%@", [product description]);     

  116.         NSLog(@"產品標題 %@" , product.localizedTitle);  

  117.         NSLog(@"產品描述信息: %@" , product.localizedDescription);  

  118.         NSLog(@"價格: %@" , product.price);  

  119.         NSLog(@"Product id: %@" , product.productIdentifier);   

  120.     }   

  121.     SKPayment *payment = nil;   

  122.     switch (buyType) {  

  123.         case IAP0p99:  

  124.             payment  = [SKPayment paymentWithProductIdentifier:ProductID_IAP0p99];    //支付$0.99  

  125.             break;  

  126.         case IAP1p99:  

  127.             payment  = [SKPayment paymentWithProductIdentifier:ProductID_IAP1p99];    //支付$1.99  

  128.             break;  

  129.         case IAP4p99:  

  130.             payment  = [SKPayment paymentWithProductIdentifier:ProductID_IAP4p99];    //支付$9.99  

  131.             break;  

  132.         case IAP9p99:  

  133.             payment  = [SKPayment paymentWithProductIdentifier:ProductID_IAP9p99];    //支付$19.99  

  134.             break;  

  135.         case IAP24p99:  

  136.             payment  = [SKPayment paymentWithProductIdentifier:ProductID_IAP24p99];    //支付$29.99  

  137.             break;  

  138.         default:  

  139.             break;  

  140.     }  

  141.     CCLOG(@"---------發送購買請求------------");  

  142.     [[SKPaymentQueue defaultQueue] addPayment:payment];    

  143.     [request autorelease];   

  144.       

  145. }  

  146. - (void)requestProUpgradeProductData  

  147. {  

  148.     CCLOG(@"------請求升級數據---------");  

  149.     NSSet *productIdentifiers = [NSSet setWithObject:@"com.productid"];  

  150.     SKProductsRequest* productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];  

  151.     productsRequest.delegate = self;  

  152.     [productsRequest start];   

  153.       

  154. }  

  155. //彈出錯誤信息  

  156. - (void)request:(SKRequest *)request didFailWithError:(NSError *)error{  

  157.     CCLOG(@"-------彈出錯誤信息----------");  

  158.     UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert",NULL) message:[error localizedDescription]  

  159.                                                        delegate:nil cancelButtonTitle:NSLocalizedString(@"Close",nil) otherButtonTitles:nil];  

  160.     [alerView show];  

  161.     [alerView release];  

  162. }  

  163.   

  164. -(void) requestDidFinish:(SKRequest *)request   

  165. {  

  166.     NSLog(@"----------反饋信息結束--------------");  

  167.       

  168. }  

  169.    

  170. -(void) PurchasedTransaction: (SKPaymentTransaction *)transaction{  

  171.     CCLOG(@"-----PurchasedTransaction----");  

  172.     NSArray *transactions =[[NSArray alloc] initWithObjects:transaction, nil];  

  173.     [self paymentQueue:[SKPaymentQueue defaultQueue] updatedTransactions:transactions];  

  174.     [transactions release];  

  175. }   

  176.   

  177. //<SKPaymentTransactionObserver> 千萬不要忘記綁定,代碼以下:  

  178. //----監聽購買結果  

  179. //[[SKPaymentQueue defaultQueue] addTransactionObserver:self];  

  180.   

  181. - (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions//交易結果  

  182. {  

  183.     CCLOG(@"-----paymentQueue--------");  

  184.     for (SKPaymentTransaction *transaction in transactions)  

  185.     {  

  186.         switch (transaction.transactionState)  

  187.         {   

  188.             case SKPaymentTransactionStatePurchased://交易完成   

  189.                 [self completeTransaction:transaction];  

  190.                 CCLOG(@"-----交易完成 --------");  

  191.                 CCLOG(@"不容許程序內付費購買");   

  192.                 UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:@"Alert"   

  193.                                                                     message:@"Himi說你購買成功啦~娃哈哈"                                                        

  194.                                                                    delegate:nil cancelButtonTitle:NSLocalizedString(@"Close(關閉)",nil) otherButtonTitles:nil];  

  195.                   

  196.                 [alerView show];  

  197.                 [alerView release];   

  198.                 break;   

  199.             case SKPaymentTransactionStateFailed://交易失敗   

  200.                 [self failedTransaction:transaction];  

  201.                  CCLOG(@"-----交易失敗 --------");  

  202.                 UIAlertView *alerView2 =  [[UIAlertView alloc] initWithTitle:@"Alert"   

  203.                                                                     message:@"Himi說你購買失敗,請從新嘗試購買~"                                                        

  204.                                                                    delegate:nil cancelButtonTitle:NSLocalizedString(@"Close(關閉)",nil) otherButtonTitles:nil];  

  205.                   

  206.                 [alerView2 show];  

  207.                 [alerView2 release];  

  208.                 break;   

  209.             case SKPaymentTransactionStateRestored://已經購買過該商品   

  210.                 [self restoreTransaction:transaction];  

  211.                  CCLOG(@"-----已經購買過該商品 --------");  

  212.             case SKPaymentTransactionStatePurchasing:      //商品添加進列表  

  213.                  CCLOG(@"-----商品添加進列表 --------");  

  214.                 break;  

  215.             default:  

  216.                 break;  

  217.         }  

  218.     }  

  219. }  

  220. - (void) completeTransaction: (SKPaymentTransaction *)transaction  

  221.   

  222. {  

  223.     CCLOG(@"-----completeTransaction--------");  

  224.     // Your application should implement these two methods.  

  225.     NSString *product = transaction.payment.productIdentifier;  

  226.     if ([product length] > 0) {  

  227.           

  228.         NSArray *tt = [product componentsSeparatedByString:@"."];  

  229.         NSString *bookid = [tt lastObject];  

  230.         if ([bookid length] > 0) {  

  231.             [self recordTransaction:bookid];  

  232.             [self provideContent:bookid];  

  233.         }  

  234.     }  

  235.       

  236.     // Remove the transaction from the payment queue.  

  237.       

  238.     [[SKPaymentQueue defaultQueue] finishTransaction: transaction];  

  239.       

  240. }  

  241.   

  242. //記錄交易  

  243. -(void)recordTransaction:(NSString *)product{  

  244.     CCLOG(@"-----記錄交易--------");  

  245. }  

  246.   

  247. //處理下載內容  

  248. -(void)provideContent:(NSString *)product{  

  249.     CCLOG(@"-----下載--------");   

  250. }  

  251.   

  252. - (void) failedTransaction: (SKPaymentTransaction *)transaction{  

  253.     NSLog(@"失敗");  

  254.     if (transaction.error.code != SKErrorPaymentCancelled)  

  255.     {  

  256.     }  

  257.     [[SKPaymentQueue defaultQueue] finishTransaction: transaction];  

  258.       

  259.       

  260. }  

  261. -(void) paymentQueueRestoreCompletedTransactionsFinished: (SKPaymentTransaction *)transaction{  

  262.       

  263. }  

  264.   

  265. - (void) restoreTransaction: (SKPaymentTransaction *)transaction  

  266.   

  267. {  

  268.     NSLog(@" 交易恢復處理");  

  269.       

  270. }  

  271.   

  272. -(void) paymentQueue:(SKPaymentQueue *) paymentQueue restoreCompletedTransactionsFailedWithError:(NSError *)error{  

  273.     CCLOG(@"-------paymentQueue----");  

  274. }  

  275.   

  276.   

  277. #pragma mark connection delegate  

  278. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data  

  279. {  

  280.     NSLog(@"%@",  [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]);   

  281. }  

  282. - (void)connectionDidFinishLoading:(NSURLConnection *)connection{  

  283.       

  284. }  

  285.   

  286. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{  

  287.     switch([(NSHTTPURLResponse *)response statusCode]) {  

  288.         case 200:  

  289.         case 206:  

  290.             break;  

  291.         case 304:   

  292.             break;  

  293.         case 400:   

  294.             break;    

  295.         case 404:  

  296.             break;  

  297.         case 416:  

  298.             break;  

  299.         case 403:  

  300.             break;  

  301.         case 401:  

  302.         case 500:  

  303.             break;  

  304.         default:  

  305.             break;  

  306.     }          

  307. }  

  308.   

  309. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {  

  310.     NSLog(@"test");  

  311. }  

  312.   

  313. -(void)dealloc  

  314. {  

  315.     [super dealloc];  

  316. }   

  317. @end  



    代碼註釋的至關清楚了,沒有什麼可解釋的,這裏說幾點值得注意的地方:

1.添加對應對應代碼時不要忘記,添加框架 StoreKit.framework,如何添加框架請看個人博文【iOS-Cocos2d遊戲開發之十四】音頻/音效/視頻播放(利用Cocos2D-iPhone-Extensions嵌入Cocos2d進行視頻播放!)

2. 越獄機器沒法沙盒測試!模擬器的話,Himi用4.3模擬器不能夠,由於提示沒有開啓程序內付費- -(我都沒看到模擬器有store的選項,so~);可是使用iOS5的模擬器能夠測試沙盒,可是執行的順序會有些問題,可是還沒真機的童鞋可使用,建議一切以真機實測爲準

3. 千萬不要忘記在iTunesConnect中建立App Bundle ID必定要跟你的項目中的info.plist中的Bundle ID保證一致!!!!

4. 以上代碼中你須要修改的就是我在HelloWorldLayer.m類中的宏定義的Product ID(產品ID),例如Himi剛纔新建了一個產品ID是「com.himi.wahaha"


而後我運行項目截圖以下以及運行控制檯打印的信息以下:


點擊Buy以後運行截圖以及打印信息:


輸入測試帳號密碼後以及打印信息:



                害羞這裏Himi最後一張截圖是沒有購買成功,這裏Himi是故意截圖出來的,緣由就是想告訴童鞋們:

 若是你的產品信息可以正常獲得,可是始終沒法成功的話,不要着急,由於你的產品要進入iTunes Connect,而且Apple準備好沙箱環境須要一些時間。Himi以前遇到過,而後在過了段時間後我沒有修改任何一行代碼,但產品ID變爲有效並能成功購買。=。 =鬱悶ing~~ 其實要使產品發佈到Apple的網絡系統是須要一段時間的,so~這裏別太着急!


    好了,寫了這麼多了,咳咳、Himi繼續忙了,作iOS的童鞋們我想此篇將成爲你必須收藏的一篇哦~嘿嘿!

相關文章
相關標籤/搜索