Apple內(nèi)購沙盒測(cè)試程序

1.導(dǎo)入頭文件<StoreKit/StoreKit.h>

#import <StoreKit/StoreKit.h> 

2.將所有內(nèi)購產(chǎn)品的ID放進(jìn)一個(gè)數(shù)組productArr

#define Product1  @"product1" //產(chǎn)品ID
#define Product2  @"product2"
#define Product3  @"product3"
#define Product4  @"product4"
#define Product5  @"product5"
#define Product6  @"product6"

3.加入?yún)f(xié)議

@interface ViewController ()
<
SKPaymentTransactionObserver,
SKProductsRequestDelegate
>
@property (nonatomic, assign) NSInteger selectedProduct;//選擇購買的產(chǎn)品在數(shù)組中的序號(hào)
@end

@implementation ViewController{
    NSArray *productArr; //存放產(chǎn)品ID
}

4.添加一個(gè)購買按鈕

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
   [ button setTitle: @"點(diǎn)擊購買"forState:UIControlStateNormal];
    [button addTarget:self action:@selector(startPayClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];

    //添加一個(gè)交易隊(duì)列觀察者
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    productArr = @[Product1,Product2,Product3,Product4,Product5,Product6];
    
}

pragma mark - Event response 購買按鈕點(diǎn)擊事件

-(void)startPayClick:(UIButton *)button{
    
    self.selectedProduct = 1;//購買第一個(gè)產(chǎn)品

    //判斷是否可進(jìn)行支付
    if ([SKPaymentQueue canMakePayments]) {
        NSLog(@"----------允許程序內(nèi)付費(fèi)--------");
        [self requestProductData:productArr[self.selectedProduct]];
    } else {
        NSLog(@"不允許程序內(nèi)付費(fèi)");
    }
    
}

pragma mark ---內(nèi)購測(cè)試

- (void)requestProductData:(NSString *)type {
    //根據(jù)商品ID查找商品信息
    NSArray *product = [[NSArray alloc] initWithObjects:type, nil];
    NSSet *nsset = [NSSet setWithArray:product];
    //創(chuàng)建SKProductsRequest對(duì)象,用想要出售的商品的標(biāo)識(shí)來初始化, 然后附加上對(duì)應(yīng)的委托對(duì)象。
    //該請(qǐng)求的響應(yīng)包含了可用商品的本地化信息。
    
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
    request.delegate = self;
    [request start];
}
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    NSLog(@"-----------收到產(chǎn)品反饋信息--------------");
    NSArray *product = response.products;
    NSLog(@"產(chǎn)品Product ID:%@",response.invalidProductIdentifiers);
    NSLog(@"產(chǎn)品付費(fèi)數(shù)量: %ld", [product count]);
    if ([product count] == 0) {
        return;
    }
    // SKProduct對(duì)象包含了在App Store上注冊(cè)的商品的本地化信息。
    SKProduct *storeProduct = nil;
    for (SKProduct *pro in product) {
        
        NSLog(@"product info");
        NSLog(@"SKProduct 描述信息%@", [pro description]);
        NSLog(@"產(chǎn)品標(biāo)題 %@" , pro.localizedTitle);
        NSLog(@"產(chǎn)品描述信息: %@" , pro.localizedDescription);
        NSLog(@"價(jià)格: %@" , pro.price);
        NSLog(@"Product id: %@" , pro.productIdentifier);
        if ([pro.productIdentifier isEqualToString:productArr[self.selectedProduct]]) {
            storeProduct = pro;
        }
    }  
    SKPayment *payment = [SKPayment paymentWithProduct:storeProduct];
    NSLog(@"--------發(fā)送購買請(qǐng)求---------");
    [[SKPaymentQueue defaultQueue ] addPayment:payment];
}
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
    NSLog(@"請(qǐng)求商品失敗%@", error);
    
}
- (void)requestDidFinish:(SKRequest *)request {
    NSLog(@"反饋信息結(jié)束調(diào)用 "); 
}
-(void) paymentQueue:(SKPaymentQueue *) paymentQueue restoreCompletedTransactionsFailedWithError:(NSError *)error{
    NSLog(@"-------paymentQueue----");
}
//監(jiān)聽購買結(jié)果
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transaction {
    
    for (SKPaymentTransaction *tran in transaction) {
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:
                NSLog(@"-----交易完成 --------");
                [self completeTransaction:tran];
                [[SKPaymentQueue defaultQueue]finishTransaction:tran];
                break;
            case SKPaymentTransactionStatePurchasing:
                NSLog(@"商品加入列表");
                break;
            case SKPaymentTransactionStateRestored:
                [self restoreTransaction:tran];
                NSLog(@"-----已經(jīng)購買過該商品 --------");
                [[SKPaymentQueue defaultQueue]finishTransaction:tran];
                break;
            case SKPaymentTransactionStateFailed:
                NSLog(@"交易失敗");
                [self failedTransaction:tran];
                break;
            default:
                break;
        }
    }
}
//交易結(jié)束
- (void)completeTransaction:(SKPaymentTransaction *)transaction {
    NSLog(@"交易結(jié)束!!!!!!!!!!!!!!!");
    // appStoreReceiptURL iOS7.0增加的,購買交易完成后,會(huì)將憑據(jù)存放在該地址
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    // 獲取到購買憑據(jù)
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
    
    NSString *encodeStr = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    //購買完成向后臺(tái)發(fā)送receipt-data,后臺(tái)校驗(yàn)發(fā)送部分略
    NSString *sendString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", encodeStr];

    //??沙盒測(cè)試時(shí)用
     NSString * str = [[NSString alloc]initWithData:transaction.transactionReceipt encoding:NSUTF8StringEncoding];
     NSString *environment=[self environmentForReceipt:str];
     NSURL *StoreURL=nil;
     if ([environment isEqualToString:@"environment=Sandbox"]) {
         StoreURL= [[NSURL alloc] initWithString: @"https://sandbox.itunes.apple.com/verifyReceipt"];
     }
     else{
         StoreURL= [[NSURL alloc] initWithString: @"https://buy.itunes.apple.com/verifyReceipt"];
     }
//或者不用判斷沙盒環(huán)境,直接用NSURL *StoreURL= [[NSURL alloc] initWithString: @"https://sandbox.itunes.apple.com/verifyReceipt"];

    /*??提交審核時(shí)用,將沙盒測(cè)試部分(171-183行)去掉,不然審核通過后內(nèi)購有問題
    NSURL *StoreURL= [[NSURL alloc] initWithString: @"https://buy.itunes.apple.com/verifyReceipt"];
    */

    //這個(gè)二進(jìn)制數(shù)據(jù)由服務(wù)器進(jìn)行驗(yàn)證;zl
    NSData *postData = [NSData dataWithBytes:[sendString UTF8String] length:[sendString length]];
    
    NSMutableURLRequest *connectionRequest = [NSMutableURLRequest requestWithURL:StoreURL];
    
    [connectionRequest setHTTPMethod:@"POST"];
    [connectionRequest setTimeoutInterval:50.0];//120.0---50.0zl
    [connectionRequest setCachePolicy:NSURLRequestUseProtocolCachePolicy];
    [connectionRequest setHTTPBody:postData];
    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];
        }
    }
    
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
//記錄交易
-(void)recordTransaction:(NSString *)product{
    NSLog(@"-----記錄交易--------");
}
//處理下載內(nèi)容
-(void)provideContent:(NSString *)product{
    NSLog(@"-----下載--------");
}
- (void) failedTransaction: (SKPaymentTransaction *)transaction{
    NSLog(@"失敗");
    //此處最好提示用戶,讓用戶重新購買或者……(UE)
    if (transaction.error.code != SKErrorPaymentCancelled)
    {
    }
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];   
}
- (void)restoreTransaction:(SKPaymentTransaction *)transaction {
    // 恢復(fù)已經(jīng)購買的產(chǎn)品
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
//收據(jù)的環(huán)境判斷;
-(NSString * )environmentForReceipt:(NSString * )str
{
    str= [str stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
    
    str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    str = [str stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    
    str=[str stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    str=[str stringByReplacingOccurrencesOfString:@"\"" withString:@""];
    
    NSArray * arr=[str componentsSeparatedByString:@";"];
    
    //存儲(chǔ)收據(jù)環(huán)境的變量
    NSString * environment=arr[2];
    return environment;
}    

源代碼見https://github.com/hubangguo/applePay

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一.總說內(nèi)購的內(nèi)容 協(xié)議、稅務(wù)和銀行業(yè)務(wù) 信息填寫 內(nèi)購商品的添加 添加沙盒測(cè)試賬號(hào) 內(nèi)購代碼的具體實(shí)現(xiàn) 內(nèi)購的注...
    默默_David閱讀 3,885評(píng)論 0 6
  • 最近在更新版本,發(fā)現(xiàn)好多用戶來進(jìn)行應(yīng)用內(nèi)的服務(wù)退款,理由頻多,但是還不能確定用戶是否支付成功,所以看了一下蘋果內(nèi)購...
    李筱野閱讀 2,561評(píng)論 0 2
  • 所謂內(nèi)購就是在App內(nèi)購買商品,如在游戲App中的購買道具、皮膚等;在電商App中的購買衣食住行的各種商品,如淘寶...
    ShineYangGod閱讀 1,903評(píng)論 0 0
  • 之前做過游戲SDK,所以當(dāng)時(shí)寫了一個(gè)內(nèi)購的類,覺得還可以吧。直接看代碼 #import#import#import...
    master_huang閱讀 937評(píng)論 0 0
  • 前段時(shí)間與人分享了讀書心得,發(fā)覺有對(duì)讀書需求的人很有幫助。 在變化這么快的社會(huì),看書學(xué)習(xí)已經(jīng)變成為了一個(gè)剛需。 但...
    斑點(diǎn)魚閱讀 316評(píng)論 0 1

友情鏈接更多精彩內(nèi)容