IOS 蘋果支付

蘋果內購 (無力吐槽,暫時先這樣),說說它里面的關鍵步驟.

大致 方向是 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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 2月18日凌晨五點,支付寶和微信支付迎來了新的競爭對手——蘋果支付Apple Pay正式在中國上線。中國成為全球第...
    vivi要學習閱讀 497評論 0 0
  • 蘋果支付 參考文章鏈接: (1)http://mobile.51cto.com/iphone-389249.htm...
    7a7e4037f473閱讀 642評論 0 0
  • 詠梧院 自癸巳入梧院,四載有余,崢嶸歲...
    清源無塵閱讀 386評論 0 0
  • 1 暑假快要來了,學生黨的心早飛到家門口去了,蠢蠢欲動著的,一點兒心思呀,也不放在學習上。 宿舍里的姑涼們也不例外...
    懵芽閱讀 406評論 2 1
  • snagit 亮點 > all in one 的截圖模式 截取窗口 , 也可以矩形截取同樣也成為槽點矩形需要拖動選...
    南不圖閱讀 1,087評論 0 1