學而時習之,不亦悅乎,大家好,我是張杰。
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,謝謝