IAP 漏单相关

漏单的原因

苹果应用内支付漏单的原因有很多,例如:验证阶段,app 闪退、app 断网或者网络不好、app 登录超时
根本原因在于苹果只负责收钱,而收钱之后的校验工作交给开发者自己来处理,开发者拿到凭证 receipt 后,去请求自己的服务器验证。

处理漏单的过程

  1. 用户已经付费,此时提示购买完成
  2. 开发者拿着获取的凭证 receipt 去请求自己的服务器,并且客户端记录并且本地记录这条 keytransactionID 的交易相关信息(包括订单号 paymentID , 交易号 transactionID ),另外凭证receipt 最好不要保存在客户端
  3. 服务器拿到客户端传过来的交易相关信息后,首先校验订单号是否正确,是否与用户相匹配,避免用户切换账号的问题。校验订单号通过后再去苹果服务器校验凭证,这里需要注意,在苹果审核的时候是走沙盒环境的,生产走正式环境,服务端需要先正常流程验证正式环境,当返回错误码显示环境错误的时候,走测试环境
  4. 正常情况下,校验凭证通过,客户端 finish 掉 这个 transaction,并且本地清除掉这条keytransactionID对应的交易信息,但是,当在请求服务端的时候,出现程序闪退、网络不好的时候,就校验失败了,但是用户的钱苹果已经扣掉,服务没有开通的现象,也就是漏单了,如果这时用户再次点击这个productID对应的商品,就会报此应用将免费恢复的提示,这里只能在用户下一次打开应用的时候处理漏单流程了
  5. 当用户再次启动应用程序的时候,当有未finish 掉的 transaction 时,应用程序会自动调用 方法 paymentQueue: updatedTransactions:
  6. 那我们通过什么来判断这次校验的是漏单流程还是正常流程呢?
    布尔值 isCash 是判断漏单流程的条件,如果用户是点击购买按钮进来的,isCash为YES, 那我们可以判断走正常流程,如果 isCash 为NO,我们就走漏单流程,本地读取之前保存的交易信息,再次请求服务端,校验凭证

代码

  1. .h 文件
#import 
#import 

@interface LxInAppPurchaseManager : NSObject
typedef void (^LxInAppPurchaseProductCompleteSuccessBlock)(id data);
typedef void (^LxInAppPurchaseProductCompleteFailureBlock)(id data);
/**
 订单号,服务器生成的交易编号
 */
@property(nonatomic,copy)NSString *paymentID;

/**
 是否为漏单,如果为真走正常流程,否则走漏单流程
 */
@property (nonatomic, assign)BOOL cash;

/**
 单例类

 @return 单例对象
 */
+ (instancetype)sharedManager;

/**
 点击某项内购商品的购买按钮

 @param productID  iTunes Connect 上商品的标识符
 */
- (void)payBtnPressed:(NSString *)productID completeSuccessBlock:(LxInAppPurchaseProductCompleteSuccessBlock)__successBlock
         failureBlock:(LxInAppPurchaseProductCompleteFailureBlock)__failureBlock;

/**
 开始监听
 */
- (void)startObserver;


/**
 停止监听
 */
- (void)stopObserver;

@end
  1. .m文件
#import "LxInAppPurchaseManager.h"
#import "SignServiceVerifyReceiptTask.h"
#import "LxIapRequestContent.h"
#import "LxArchiverManager.h"
@interface LxInAppPurchaseManager()
@property (nonatomic, assign)BOOL isObserver; // 程序是否添加监听
@property(nonatomic,copy)NSString *productID; // iTunes Connect上商品的标识符
@property (nonatomic, copy)NSString *transactionID;
@property (nonatomic, strong)SKProduct *product;

@property (nonatomic, copy)LxInAppPurchaseProductCompleteSuccessBlock successBlock;
@property (nonatomic, copy)LxInAppPurchaseProductCompleteFailureBlock failureBlock;
@end

@implementation LxInAppPurchaseManager
static LxInAppPurchaseManager *purchaseManager = nil;
+ (instancetype)sharedManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        purchaseManager = [[LxInAppPurchaseManager alloc] init];
    });
    return purchaseManager;
}

- (void)payBtnPressed:(NSString *)productID completeSuccessBlock:(LxInAppPurchaseProductCompleteSuccessBlock)__successBlock
         failureBlock:(LxInAppPurchaseProductCompleteFailureBlock)__failureBlock{
    self.successBlock = __successBlock;
    self.failureBlock = __failureBlock;

    self.productID = productID;
    if (!self.productID) {
        [MBProgressHUD wyp_error:@"商品标识符不能为空" block:nil];
        return;
    }

    // 判断用户是否允许应用内付费
    if ([SKPaymentQueue canMakePayments]){
        SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:productID]];
        request.delegate = self;
        [request start];
    }else
        [MBProgressHUD wyp_error:@"用户不允许内购" block:nil];
}

#pragma mark - 监听内购

// 开始监听内购
- (void)startObserver {
    // isObserver 程序是否添加监听
    if (!self.isObserver) {
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
        NSLog(@"//----------------------------- 开始监听内购 ------------------------------//");
        self.isObserver = YES;
    }
}

// 移除监听内购
- (void)stopObserver {
    if (self.isObserver) {
        [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
        NSLog(@"//----------------------------- 移除监听内购 ------------------------------//");
        self.isObserver = NO;
    }
}

#pragma mark - SKProductsRequestDelegate

// 检索成功后的回调,从 App Store 获取产品列表信息请求的响应
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    NSArray *products = response.products;
    if (products.count != 0) {
        for (SKProduct *_product in products) {
            if ([_product.productIdentifier isEqualToString:self.productID]) {
                self.product = _product;
            }
        }
        SKMutablePayment *payment = [SKMutablePayment paymentWithProduct:self.product];
        // 服务器的交易编号,也就是订单号 paymentID
        payment.applicationUsername = self.paymentID;
        // 发起购买
        NSLog(@"//----------------------------- 发起购买 ------------------------------//");
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }else{
        [MBProgressHUD wyp_error:@"无法获取商品" block:nil];
    }
}

#pragma mark - SKRequestDelegate

// 检索失败后的回调
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
    [MBProgressHUD wyp_error:@"请求苹果服务器失败" block:nil];
}

// 检索结束
- (void)requestDidFinish:(SKRequest *)request{
    NSLog(@"//----------------------------- 苹果反馈信息结束 ------------------------------//");
}

#pragma mark -

// 当用户购买的操作有结果时,就会触发下面的回调函数
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
    for (SKPaymentTransaction *transaction in transactions) {
        self.transactionID = transaction.transactionIdentifier;
        switch (transaction.transactionState) {
            case SKPaymentTransactionStatePurchased: // 交易成功
                [self purchasedTransaction:transaction];
                break;
            case SKPaymentTransactionStateFailed: // 交易失败
                [self failedTransaction:transaction];
                break;
            case SKPaymentTransactionStateRestored: // 已经购买过该商品,消耗型不支持恢复,TODU
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                break;
            case SKPaymentTransactionStatePurchasing: // 已经在商品列表中
                NSLog(@"//----------------------------- 等待支付 ------------------------------//");
                break;
            case SKPaymentTransactionStateDeferred: // 最终状态未确定
                NSLog(@"//----------------------------- 最终状态未确定 ------------------------------//");
                break;
            default:
                break;
        }
    }
}

// 恢复购买
- (void)restoredTransation:(SKPaymentTransaction *)transaction{
    [MBProgressHUD wyp_error:@"" block:^{
        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    }];
}

// 付款失败后,结束交易
- (void)failedTransaction:(SKPaymentTransaction *)transaction{
    NSString *detail = @"";
    switch (transaction.error.code) {
        case SKErrorUnknown:
            NSLog(@"SKErrorUnknown");
            detail = @"未知的错误";
            break;

        case SKErrorClientInvalid:
            NSLog(@"SKErrorClientInvalid");
            detail = @"当前苹果账户无法购买商品(如有疑问,可以询问苹果客服)";
            break;

        case SKErrorPaymentCancelled:
            NSLog(@"SKErrorPaymentCancelled");
            detail = @"购买已取消";
            break;

        case SKErrorPaymentInvalid:
            NSLog(@"SKErrorPaymentInvalid");
            detail = @"购买无效(如有疑问,可以询问苹果客服)";
            break;

        case SKErrorPaymentNotAllowed:
            NSLog(@"SKErrorPaymentNotAllowed");
            detail = @"当前苹果设备无法购买商品(如有疑问,可以询问苹果客服)";
            break;

        case SKErrorStoreProductNotAvailable:
            NSLog(@"SKErrorStoreProductNotAvailable");
            detail = @"当前商品不可用";
            break;

        default:
            NSLog(@"No Match Found for error");
            detail = @"未知的错误";
            break;
    }

    [MBProgressHUD wyp_error:detail block:^{
        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
        NSLog(@"//----------------------------- 购买失败 ------------------------------//");
        NSLog(@"//----------------------------- 交易失败订单号开始 ------------------------------//");
        NSLog(@"transaction.payment.applicationUsername:%@",transaction.payment.applicationUsername);
        NSLog(@"//----------------------------- 交易失败订单号结束 ------------------------------//");
    }];
}

// 付款成功后,请求服务端
- (void)purchasedTransaction:(SKPaymentTransaction *)transaction{
    NSLog(@"//----------------------------- 交易成功订单号开始 ------------------------------//");
    NSLog(@"transaction.payment.applicationUsername:%@",transaction.payment.applicationUsername);
    NSLog(@"//----------------------------- 交易成功订单号结束 ------------------------------//");

    NSLog(@"//----------------------------- 购买成功验证订单 ------------------------------//");
    NSLog(@"//----------------------------- 获得凭证receipt ------------------------------//");

    // 获取凭证
    NSData *data = [NSData dataWithContentsOfURL:[[NSBundle mainBundle] appStoreReceiptURL]];
    NSString *receipt = [data base64EncodedStringWithOptions:0];
    NSLog(@"//----------------------------- receipt 开始 ------------------------------//");
    NSLog(@"receipt(base64String):%@",receipt);
    NSLog(@"//----------------------------- receipt 结束 ------------------------------//");
    if (!receipt) {
        [MBProgressHUD wyp_error:@"获取凭证失败" block:^{
            return;
        }];
    }

    if (self.cash) {
        NSLog(@"//----------------------------- 处理正常流程 ------------------------------//");
        NSMutableDictionary *requestContent = [NSMutableDictionary dictionary];
        [requestContent setValue:receipt forKey:@"receiptData"];
        [requestContent setValue:self.transactionID forKey:@"transactionId"];
        [requestContent setValue:self.paymentID forKey:@"paymentId"];

        //把这个信息存起到本地
        LxIapRequestContent *iapRequestContent = [LxIapRequestContent instanceWithDic:requestContent error:nil];
        [[LxArchiverManager shareManager] saveArchiverData:iapRequestContent andKey:transaction.transactionIdentifier];

        self.cash = NO;
        [self tellServerBuySuccessWithTradeInfo:requestContent transaction:transaction];
    }else{
        NSLog(@"//----------------------------- 处理漏单流程 ------------------------------//");
        //从本地读取交易信息
        LxIapRequestContent *iapRequestContent = [[LxArchiverManager shareManager] queryArchiverDataWithKey:transaction.transactionIdentifier];
        NSMutableDictionary *requestContent = [NSMutableDictionary dictionary];
        [requestContent setValue:receipt forKey:@"receiptData"];
        [requestContent setValue:iapRequestContent.transactionId forKey:@"transactionId"];
        [requestContent setValue:iapRequestContent.paymentId forKey:@"paymentId"];
        [self tellServerBuySuccessWithTradeInfo:requestContent transaction:transaction];
    }
}

#pragma mark - 请求服务端,记录交易

// 验证交易
- (void)tellServerBuySuccessWithTradeInfo:(NSMutableDictionary *)tradeInfo transaction:(SKPaymentTransaction *)transaction{
    [SignServiceVerifyReceiptTask startWithDic:tradeInfo success:^(NSDictionary *__data, id __task) {
        [[LxArchiverManager shareManager] clearArchiverDataWithKey:transaction.transactionIdentifier];
        BOOL result = [[__data objectForKey:@"payResult"] boolValue];
        NSString *msg = [__data objectForKey:@"message"];
        if(!result){
            [MBProgressHUD wyp_error:msg block:^{
                NSLog(@"//----------------------------- 验证失败,购买结束 ------------------------------//");
                if (self.failureBlock) {
                    self.failureBlock(__data);
                }
                return ;
            }];
        }else{
            [MBProgressHUD wyp_success:msg block:^{
                NSLog(@"//----------------------------- 验证成功,购买结束 ------------------------------//");
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                if (self.successBlock) {
                    self.successBlock(__data);
                }
            }];
        }
    } failure:^(id __data, id __task) {
        [MBProgressHUD wyp_error:@"验证失败,购买结束" block:^{
            NSLog(@"//----------------------------- 验证失败,订单结束 ------------------------------//");
            if (self.failureBlock) {
                self.failureBlock(__data);
            }
        }];
    }];
}

@end

如有问题,欢迎留言讨论

你可能感兴趣的:(IAP 漏单相关)