iOS蘋果內(nèi)購詳細步驟

學而時習之,不亦悅乎,大家好,我是張杰。

iOS開發(fā)支付模塊分為兩個部分:

1、調(diào)取外部支付,例如支付寶、微信、銀聯(lián)等。

2、蘋果內(nèi)購。

什么是蘋果內(nèi)購呢?從技術(shù)層面來說就是走蘋果自己的支付模式,例如現(xiàn)在的愛奇藝APP里面購買會員,QQ斗地主里面的充值QB等。有圖便于理解:

11563767294_.pic.jpg

其中圖標、價格、詳情等都需要到https://developer.apple.com里面去設置。具體下面會講到。

下面我們分兩塊來講:

1、代碼

2、設置

一、內(nèi)購所需要寫的代碼是非常少的,主要難點在設置部分。

1、引入頭文件
#import<StoreKit/StoreKit.h>
2、設置代理
@interface AppDelegate ()<WXApiDelegate,SKProductsRequestDelegate,SKPaymentTransactionObserver>
3、開啟內(nèi)購檢測
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
4、設置內(nèi)購點擊事件
-(void)buy:(NSString *)buyID{
self.productId = buyID;
if ([SKPaymentQueue canMakePayments]) {
    [self requestProductData:self.productId];
}else{
    NSLog(@"不允許程序內(nèi)付費");
    [MBProgressHUD showGameAQHUDAddto:self.window text:@"不允許程序內(nèi)付費"];
}
}
5、請求商品,獲取商品信息,以及代理
-(void)requestProductData:(NSString *)productId{
NSLog(@"--------請求對應的產(chǎn)品信息------------");
[MBProgressHUD showGameAQHUDAddto:self.window text:@"請求對應的產(chǎn)品信息"];
NSSet *nsset = [NSSet setWithObjects:productId, nil];
_request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
_request.delegate = self;
[_request start];
}

-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
NSLog(@"-------收到產(chǎn)品反饋消息----------");
[MBProgressHUD showGameAQHUDAddto:self.window text:@"收到產(chǎn)品反饋消息"];
NSArray *product = response.products;
if ([product count] == 0) {
    NSLog(@"-----沒有商品-------");
    [MBProgressHUD showGameAQHUDAddto:self.window text:@"沒有商品"];
    return;
}

NSLog(@"productID:%@",response.invalidProductIdentifiers);
NSLog(@"產(chǎn)品付費數(shù)量:%lu",(unsigned long)product.count);
//     [MBProgressHUD showGameAQHUDAddto:self.window text:@"產(chǎn)品付費數(shù)量"];
//    [MBProgressHUD showGameAQHUDAddto:self.window text:[NSString stringWithFormat:@"productID:%@",response.invalidProductIdentifiers]];
SKProduct *prod = nil;
for (SKProduct *pro in product) {
    NSLog(@"%@",pro.description);
    NSLog(@"%@",pro.localizedTitle);
    NSLog(@"%@",pro.localizedDescription);
    NSLog(@"%@",pro.price);
    NSLog(@"%@",pro.productIdentifier);
    
    if ([pro.productIdentifier isEqualToString:self.productId]) {
        prod = pro;
    }
}
if (prod != nil) {
    SKPayment *payment = [SKPayment paymentWithProduct:prod];
    NSLog(@"-------發(fā)送購買請求-------");
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}
}

-(void)request:(SKRequest *)request didFailWithError:(NSError *)error{
NSLog(@"購買失敗");
}

- (void)requestDidFinish:(SKRequest *)request{
NSLog(@"反饋信息結(jié)束");
}
6、沙盒測試環(huán)境驗證以及正式環(huán)境
//沙盒測試環(huán)境驗證
#define SANDBOX @"https://sandbox.itunes.apple.com/verifyReceipt"
//正式環(huán)境驗證
#define AppStore @"https://buy.itunes.apple.com/verifyReceipt"
/**
 *  驗證購買,避免越獄軟件模擬蘋果請求達到非法購買問題
 *
 */
-(void)verifyPurchaseWithPaymentTransaction{
//從沙盒中獲取交易憑證并且拼接成請求體數(shù)據(jù)
NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];
NSString *receiptString=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];//轉(zhuǎn)化為base64字符串
NSString *bodyString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", receiptString];//拼接請求數(shù)據(jù)
NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
//創(chuàng)建請求到蘋果官方進行購買驗證
NSURL *url=[NSURL URLWithString:AppStore];
NSMutableURLRequest *requestM=[NSMutableURLRequest requestWithURL:url];
requestM.HTTPBody=bodyData;
requestM.HTTPMethod=@"POST";
//創(chuàng)建連接并發(fā)送同步請求
NSError *error=nil;
NSData *responseData=[NSURLConnection sendSynchronousRequest:requestM returningResponse:nil error:&error];
if (error) {
    NSLog(@"驗證購買過程中發(fā)生錯誤,錯誤信息:%@",error.localizedDescription);
    return;
}
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",dic);
if([dic[@"status"] intValue]==0){
    NSLog(@"購買成功!");
    NSDictionary *dicReceipt= dic[@"receipt"];
    NSDictionary *dicInApp=[dicReceipt[@"in_app"] firstObject];
    NSString *productIdentifier= dicInApp[@"product_id"];//讀取產(chǎn)品標識
    [MBProgressHUD showGameAQHUDAddto:self.window text:@"購買成功!"];
//        [MBProgressHUD showGameAQHUDAddto:self.window text:[NSString stringWithFormat:@"購買成功--%@",dicInApp[@"product_id"]]];
    //如果是消耗品則記錄購買數(shù)量,非消耗品則記錄是否購買過
//        NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
//        if ([productIdentifier isEqualToString:@"123"]) {
//            int purchasedCount=[defaults integerForKey:productIdentifier];//已購買數(shù)量
//            [[NSUserDefaults standardUserDefaults] setInteger:(purchasedCount+1) forKey:productIdentifier];
//        }else{
//            [defaults setBool:YES forKey:productIdentifier];
//        }
//        //在此處對購買記錄進行存儲,可以存儲到開發(fā)商的服務器端
    
    if ([productIdentifier isEqualToString:@"111111"]) {
        [self chongzhi:@"50"];
    }else if ([productIdentifier isEqualToString:@"22222"]) {
        [self chongzhi:@"108"];
    }else if ([productIdentifier isEqualToString:@"33333"]) {
        [self chongzhi:@"158"];
    }else if ([productIdentifier isEqualToString:@"44444"]) {
        [self chongzhi:@"208"];
    }
}else if([dic[@"status"] intValue]==21007){
    [self verifyPurchaseWithPaymentTransactionSANDBOX];
}else{
    NSLog(@"購買失敗,未通過驗證!");
}
}

-(void)verifyPurchaseWithPaymentTransactionSANDBOX{
//從沙盒中獲取交易憑證并且拼接成請求體數(shù)據(jù)
NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];
NSString *receiptString=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];//轉(zhuǎn)化為base64字符串
NSString *bodyString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", receiptString];//拼接請求數(shù)據(jù)
NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
//創(chuàng)建請求到蘋果官方進行購買驗證
NSURL *url=[NSURL URLWithString:SANDBOX];
NSMutableURLRequest *requestM=[NSMutableURLRequest requestWithURL:url];
requestM.HTTPBody=bodyData;
requestM.HTTPMethod=@"POST";
//創(chuàng)建連接并發(fā)送同步請求
NSError *error=nil;
NSData *responseData=[NSURLConnection sendSynchronousRequest:requestM returningResponse:nil error:&error];
if (error) {
    NSLog(@"驗證購買過程中發(fā)生錯誤,錯誤信息:%@",error.localizedDescription);
    return;
}
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",dic);
if([dic[@"status"] intValue]==0){
    NSLog(@"購買成功!");
    NSDictionary *dicReceipt= dic[@"receipt"];
    NSDictionary *dicInApp=[dicReceipt[@"in_app"] firstObject];
    NSString *productIdentifier= dicInApp[@"product_id"];//讀取產(chǎn)品標識
    [MBProgressHUD showGameAQHUDAddto:self.window text:@"購買成功!"];
    [MBProgressHUD showGameAQHUDAddto:self.window text:[NSString stringWithFormat:@"購買成功--%@",dicInApp[@"product_id"]]];
    //如果是消耗品則記錄購買數(shù)量,非消耗品則記錄是否購買過
    //        NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    //        if ([productIdentifier isEqualToString:@"123"]) {
    //            int purchasedCount=[defaults integerForKey:productIdentifier];//已購買數(shù)量
    //            [[NSUserDefaults standardUserDefaults] setInteger:(purchasedCount+1) forKey:productIdentifier];
    //        }else{
    //            [defaults setBool:YES forKey:productIdentifier];
    //        }
    //        //在此處對購買記錄進行存儲,可以存儲到開發(fā)商的服務器端
    
    if ([productIdentifier isEqualToString:@"111111"]) {
        [self chongzhi:@"50"];
    }else if ([productIdentifier isEqualToString:@"22222"]) {
        [self chongzhi:@"108"];
    }else if ([productIdentifier isEqualToString:@"33333"]) {
        [self chongzhi:@"158"];
    }else if ([productIdentifier isEqualToString:@"44444"]) {
        [self chongzhi:@"208"];
    }
}else if([dic[@"status"] intValue]==21007){
    
}else{
    NSLog(@"購買失敗,未通過驗證!");
}
}

代碼部分已經(jīng)結(jié)束。僅僅看代碼已經(jīng)能懂60%了。剩余不懂得看完設置就差不多了。

設置部分

設置部分需要做的是:
1、稅務等填寫。
2、沙河賬號申請。
3、商品和價格設置。
4、Appstore顯示。

由于做的時候設置部分沒有截圖,下面提供兩個補充文檔:

http://m.itdecent.cn/p/bded03fdbec9

http://m.itdecent.cn/p/ebdeea271352

如果有錯誤或者還有其他問題,可以聯(lián)系我:zhangjieiossky@163.com,謝謝

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

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

  • 一、設置協(xié)議等相關(guān) 1.點擊協(xié)議、稅務和銀行業(yè)務。 2.點擊 Request Contracts 下面的 Requ...
    樊二哈閱讀 16,726評論 5 15
  • 每天進步一點點點點點點點點點點點點點點點點點點點點點點點點點點點點點點~~從開始只能寫幾句話、模仿別人的觀點,到現(xiàn)...
    一個帥氣的名字呀閱讀 19,461評論 4 31
  • 最近上架公司的一個關(guān)于兒童英語視頻的App,因為內(nèi)購問題,卡了很久,現(xiàn)在把我的這些經(jīng)歷整理出來,分享給大家。 蘋果...
    XiaoWhite閱讀 5,202評論 0 6
  • 肩膀在疼 脖子也在疼 上周去按摩店 按摩師傅說:頭疼嗎 還好,我答 好長時間沒來了吧 嗯,最近疼的厲害才又來了 就...
    呆丫閱讀 248評論 0 6
  • 知識廣度 主要表現(xiàn)在對行業(yè)的了解,對領域的了解。從宏觀的角度來看,作為一個開發(fā)人員,我每天的工作最多的是在計算機前...
    清水蘆葦閱讀 375評論 0 0

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