iOS开发内购(In-App Purchase)总结

流程梳理

内购思维导图

一、内购类型介绍

iap.png

这四种内购,使用过消耗型商品以及自动续期订阅类型,接入方式以及验证方式基本一致,自动续订要关注的点有点多,其中免费试用期,用户取消订阅,以及恢复订阅(自动续订苹果强制要求有恢复按钮)。

二、内购流程

1.创建商品
内购商品信息.png
内购设置信息.png
内购审核样式.png
2.App Store Connect用户和访问沙盒右边添加沙盒测试人员
沙盒测试账号.png
3.协议、税务和银行业务(需要在测试之前填写,不然唤起支付的回调里拿不到内购商品信息
协议、税务和银行业务.png

协议状态.png

银行信息.png

税务.png
4.代码调试

步骤如下:

  • 获取商品列表,从app内读取或者从自己服务器读取;
  • 用户选择了商品,唤起支付请求,收到购买完成的回调;
  • 购买流程结束后,向服务器发起验证凭证,以及发放虚拟商品(验证时开发阶段需要用沙盒环境,苹果推荐使用App Store环境,当返回21007时再进行沙盒环境验证);
  • 服务端认证分为4步
    • 接受iOS端发来的购买凭证;
    • 判断凭证是否已存在或验证过,然后存储该凭证;
    • 将该凭证发送都苹果的服务器验证,并将验证结果返回给客户端;(考虑到网络异常情况,服务器的验证应该是一个可恢复的队列,如果网络失败了,应该进行重试。 简单来说就是将该购买凭证用Base64编码,然后POST给苹果的验证服务器,苹果将验证结果以JSON形式返回
#import "OpenMemberManager.h"
#import 

#define kMoonGuardianMemberOfMonth @"com.plw.moonGuardian_vip_month"
#define kMoonGuardianMemberOfQuarter @"com.plw.moonGuardian_vip_quarter"
#define kMoonGuardianMemberOfYear @"com.plw.moonGuardian_vip_year"
#define IAPshareSecret @"946af2dda1874a8fbd1dc5beec78fe48"
#define SandboxVerifyReceipt @"https://sandbox.itunes.apple.com/verifyReceipt"
#define AppstoreVerifyReceipt @"https://buy.itunes.apple.com/verifyReceipt"

@interface OpenMemberManager ()

@property (nonatomic, strong) SKProductsRequest *request;
@property (nonatomic, copy) NSString * productID;       // 订阅商品ID
@property (nonatomic, strong) MBProgressHUD *hudProgress;

@property (nonatomic, assign) IAPType iapType;          // 当前购买类型
@property (nonatomic, copy) void(^Subscribe)(void);     // 内购回调
@property (nonatomic, assign) BOOL verifyVip;           // 是否开始验证
@property (nonatomic, assign) BOOL isSubscribing;       // 正在进行订阅操作
@property (nonatomic, assign) BOOL isRestoring;         // 正在进行还原操作

@end

@implementation OpenMemberManager

+ (instancetype)sharedInstance {
    static OpenMemberManager * manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[OpenMemberManager alloc] init];
        [manager startPaymentConfig];
    });
    return manager;
}

- (void)startPaymentConfig {
    self.verifyVip = NO;
    self.isSubscribing = NO;
    self.isRestoring = NO;
    //一定要 开启内购检测
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    
    [[[UIApplication sharedApplication] keyWindow] addSubview:self.hudProgress];
}

// 恢复方法
- (void)restoreAction {
    //调起苹果内购恢复接口
    [self.hudProgress showAnimated:YES];
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
    self.isRestoring = YES;
    self.isSubscribing = NO;
}

// 订阅方法
- (void)subscribeAction:(IAPType)iapType handle:(void(^)(void))result {
    self.iapType = iapType;
    self.Subscribe = result;
    self.verifyVip = NO;
    self.isSubscribing = YES;
    self.isRestoring = NO;

    NSString *proID;
    switch (iapType) {
        case IAPTypeOfMonth:
            proID = kMoonGuardianMemberOfMonth;
            break;
        case IAPTypeOfQuarter:
            proID = kMoonGuardianMemberOfQuarter;
            break;
        case IAPTypeOfYear:
            proID = kMoonGuardianMemberOfYear;
            break;
        default:
            break;
    }
    if ([SKPaymentQueue canMakePayments]) {
        self.productID = proID;
        [self requestProductData:proID];
        
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            [PLWToast showCenterWithText:@"不允许程序内付费"];
        });
    }
}

// 收到请求信息
- (void)requestProductData:(NSString *)productID{
    NSLog(@"-------------请求对应的产品信息----------------");
    [self.hudProgress showAnimated:YES];
    self.hudProgress.label.text = @"加载内购信息...";
    
    NSArray *product = [[NSArray alloc] initWithObjects:productID,nil];
    
    NSSet *nsset = [NSSet setWithArray:product];
    _request = [[SKProductsRequest alloc]initWithProductIdentifiers:nsset];
    _request.delegate = self;
    [_request start];
}

// 收到返回信息
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    NSArray *product = response.products;
    if (product.count == 0) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.hudProgress hideAnimated:YES];
            [PLWToast showCenterWithText:@"购买失败"];
        });
        return;
    }
    
    SKProduct *prod = nil;
    for (SKProduct *pro in product) {
        if ([pro.productIdentifier isEqualToString:self.productID]) {
            prod = pro;
        }
    }
    
    // 发送购买请求
    if (prod != nil) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.hudProgress.label.text = @"唤起支付...";
        });
        SKPayment *payment = [SKPayment paymentWithProduct:prod];
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }
}

// 失败回调
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.hudProgress hideAnimated:YES];
        [PLWToast showCenterWithText:@"购买失败"];
    });
}
// 支付后的反馈信息
- (void)requestDidFinish:(SKRequest *)request{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.hudProgress.label.text = @"";
    });
}

// 监听购买结果
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions{
    for (SKPaymentTransaction *tran in transactions) {
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:    // 交易完成
                if (tran.originalTransaction) { // 如果是自动续费的订单originalTransaction会有内容
                    NSLog(@"自动续费的订单originalTransaction会有内容");
                } else {  // 普通购买,以及 第一次购买 自动订阅
                    NSLog(@"普通购买,以及 第一次购买 自动订阅");
                }
                [self verifyPurchaseWithPaymentTransactionWith:tran];
                
                break;
            case SKPaymentTransactionStatePurchasing: {  //
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.hudProgress.label.text = @"加载中...";
                });
                NSLog(@"商品已经添加进列表");
            }
                break;
                
            case SKPaymentTransactionStateRestored: {
                NSLog(@"已经购买过商品");
                if (!self.verifyVip) {  // 验证一次,已购商品会有多个,避免重复验证
                    self.verifyVip = YES;
                    [self verifyPurchaseWithPaymentTransactionWith:tran];
                } else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.hudProgress hideAnimated:YES];
                    });
                    [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                }
                
                break;
            }
            case SKPaymentTransactionStateFailed:{
                NSLog(@"购买失败");
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.hudProgress hideAnimated:YES];
                    [PLWToast showCenterWithText:@"购买失败"];
                });
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];

                break;
            }
            default: {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.hudProgress hideAnimated:YES];
                });
                break;
            }
        }
    }
}

- (void)paymentQueue:(SKPaymentQueue *)queue restoreCompletedTransactionsFailedWithError:(NSError *)error API_AVAILABLE(ios(3.0), macos(10.7), watchos(6.2)) {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.hudProgress hideAnimated:YES];
        [PLWToast showCenterWithText:@"恢复失败"];
    });
}

// Sent when all transactions from the user's purchase history have successfully been added back to the queue.
- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue API_AVAILABLE(ios(3.0), macos(10.7), watchos(6.2)) {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.hudProgress hideAnimated:YES];
    });
}


/**
 *  验证购买,避免越狱软件模拟苹果请求达到非法购买问题
 *
 */
-(void)verifyPurchaseWithPaymentTransactionWith:(SKPaymentTransaction *)tran{
    WeakSelf
    dispatch_async(dispatch_get_main_queue(), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            self.hudProgress.label.text = @"验证内购信息";
        });
    });
    
    NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];
    NSString *receiptString = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];

    if (!receiptString) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.hudProgress hideAnimated:YES];
        });
        return;
    }
    [LoginManager iapVerifyRecipt:receiptString productId:self.productID result:^(NSDictionary * _Nullable resultDic) {
        [[SKPaymentQueue defaultQueue] finishTransaction:tran];
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.hudProgress hideAnimated:YES];
        });
        if ([resultDic getInteger:@"code"] == 200) {   // 订阅成功
            if (weakSelf.Subscribe) {
                weakSelf.Subscribe();
            }
            [DeviceControlManager flurryLogEvent:@"App_open_vip_success" withParameters:@{}];
        } else {
            [DeviceControlManager flurryLogEvent:@"App_open_vip_failure" withParameters:@{@"msg" : [resultDic getString:@"msg"]}];
        }
    } error:^(NSError * _Nonnull error) {
        [[SKPaymentQueue defaultQueue] finishTransaction:tran];
    }];
}

- (void)analysisInAppPurchasedData:(NSDictionary *)iapDic type:(IAPType)iapType {
    
}


#pragma mark - Getter
- (MBProgressHUD *)hudProgress {
    if (!_hudProgress) {
        _hudProgress = [[MBProgressHUD alloc] init];
    }
    return _hudProgress;
}

@end

你可能感兴趣的:(iOS开发内购(In-App Purchase)总结)