蘋果內購 (無力吐槽,暫時先這樣),說說它里面的關鍵步驟.
- 添加收款
銀行卡
和商品
:http://www.lxweimin.com/p/1e6b1152afc6 - 創建沙盒 測試賬號 : http://www.lxweimin.com/p/143b410ff09a
- 代碼部分
大致 方向是
product_id
=>Payment
=>喚起蘋果支付
通過 主要是 `SKPaymentTransactionObserver`(觀察支付狀態) 和
`SKProductsRequestDelegate` (通過商品id去蘋果服務器獲取商品信息)
為了方便的開發 我自己封裝了 ApplePay
#import "ApplePay.h"
//沙盒測試環境驗證
#define ApplePayWithSandBoxUrl @"https://sandbox.itunes.apple.com/verifyReceipt"
//正式環境驗證
#define ApplePayWithAppStoreUrl @"https://buy.itunes.apple.com/verifyReceipt"
@interface ZLApplePay () <SKPaymentTransactionObserver,SKProductsRequestDelegate>
@property (nonatomic,copy) NSString * currentProductId;
//@property (nonatomic,strong) NSDictionary * mapDic;//product_id -> 金額的映射
@property (nonatomic,weak) id <ZLApplePayDelegate> delegate;
@end
@implementation ZLApplePay
LEE_SINGLE_M //單例
- (void)dealloc {
[self removeObserver];
}
- (instancetype)init {
if (self = [super init]) {
[self addObserver];
}
return self;
}
- (void)addObserver {
[self removeObserver];
//添加一個交易隊列觀察者
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}
- (void)removeObserver {
//添加一個交易隊列觀察者
[[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
#pragma mark - private
/**
* 驗證購買,避免越獄軟件模擬蘋果請求達到非法購買問題
暫時不做
*
*/
-(void)verifyPurchase {
//從沙盒中獲取交易憑證并且拼接成請求體數據
NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];
NSString *receiptString=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];//轉化為base64字符串
NSString *bodyString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", receiptString];//拼接請求數據
NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
//創建請求到蘋果官方進行購買驗證
NSURL *url=[NSURL URLWithString:ApplePayWithSandBoxUrl];
NSMutableURLRequest *requestM=[NSMutableURLRequest requestWithURL:url];
requestM.HTTPBody=bodyData;
requestM.HTTPMethod=@"POST";
NSURLSessionDataTask *task= [[NSURLSession sharedSession] dataTaskWithRequest:requestM completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"驗證購買過程中發生錯誤,錯誤信息:%@",error.localizedDescription);
return;
}
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",dic);
if([dic[@"status"] intValue]==0){
NSLog(@"購買成功!");
}else{
NSLog(@"購買失敗,未通過驗證!");
}
}];
[task resume];
}
//完成購買
- (void)completeTransaction:(SKPaymentTransaction *)transaction {
[ZLToast dismiss];
if ([self.delegate respondsToSelector:@selector(zlApplePaySuccessWithProductId:completeTransaction:)]) {
[self.delegate zlApplePaySuccessWithProductId:self.currentProductId completeTransaction:transaction];
} else {
[self finishTransaction:transaction];
}
}
//購買失敗
- (void)failedTransaction:(SKPaymentTransaction *)transaction {
[ZLToast dismiss];
if(transaction.error.code != SKErrorPaymentCancelled) {
NSString * msg = [NSString stringWithFormat:@"購買失敗 :%@",transaction.error.localizedDescription];
[ZLToast showHint:msg];
} else {
NSString * msg = [NSString stringWithFormat:@"用戶取消交易"];
[ZLToast showHint:msg];
}
[self finishTransaction:transaction];
}
// 恢復已經購買的產品
- (void)restoreTransaction:(SKPaymentTransaction *)transaction {
[ZLToast dismiss];
[self finishTransaction:transaction];
}
- (void)otherTransaction:(SKPaymentTransaction *)transaction {
[ZLToast dismiss];
[ZLToast showHint:@"支付掛起,請聯系官方客服!"];
[self finishTransaction:transaction];
}
#pragma mark - SKPaymentTransactionObserver (觀察者監聽購買狀態的變化)
- (void)paymentQueue:(SKPaymentQueue *)queue
updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
for (SKPaymentTransaction *tran in transactions) {
if (SKPaymentTransactionStatePurchasing == tran.transactionState) {
[ZLToast showWithStatus:@"正在進行內購中,請不要離開."];
} else if (SKPaymentTransactionStatePurchased == tran.transactionState) {
[self completeTransaction:tran];
} else if (SKPaymentTransactionStateRestored == tran.transactionState) {
[self restoreTransaction:tran];
} else if (SKPaymentTransactionStateFailed == tran.transactionState) {
[self failedTransaction:tran];
} else {
[self otherTransaction:tran];
}
}
}
#pragma mark - SKProductsRequestDelegate (請求的代理)
// Sent immediately before -requestDidFinish:
- (void)productsRequest:(SKProductsRequest *)request
didReceiveResponse:(SKProductsResponse *)response {
//接收商品信息
NSArray *product = response.products;
if ([product count] == 0) {
return;
}
// SKProduct對象包含了在App Store上注冊的商品的本地化信息。
SKProduct *currentProduct = nil;
for (SKProduct *pro in product) {
if ([pro.productIdentifier isEqualToString:self.currentProductId]) {
currentProduct = pro;
}
}
if (!currentProduct) {
return;
}
//創建一個支付對象,并放到隊列中
SKMutablePayment * payment = [SKMutablePayment paymentWithProduct:currentProduct];
// //設置購買的數量
// payment.quantity = 1;
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
NSString * errorMsg = [NSString stringWithFormat:@"支付請求錯誤:%@",error.localizedDescription];
[ZLToast showHint:errorMsg];
[ZLToast dismiss];
}
- (void)requestDidFinish:(SKRequest *)request {
NSLog(@"支付請求成功=>開始調取ApplePay");
}
#pragma mark - public
- (void)startPayWithProductId:(NSString *)productId
delegate:(id <ZLApplePayDelegate>)delegate {
//判斷是否可進行支付
if ([SKPaymentQueue canMakePayments]) {
if (productId.length == 0) {
[ZLToast showHint:@"傳入的productId 是空的"];
return;
}
self.currentProductId = productId;
self.delegate = delegate;
SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObjects:productId, nil]];
request.delegate = self;
[request start];
[ZLToast showWithStatus:@"正在發起支付"];
} else {
[ZLToast showHint:@"不允許程序內付費"];
}
}
- (void)finishTransaction:(SKPaymentTransaction *)transaction {
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
@end