苹果内购开发总结(含掉单问题优化)

2018年8月13日
1.后台查询充值记录


苹果内购开发总结(含掉单问题优化)_第1张图片
image.png

2018年3月27日
苹果内购开发(含掉单问题优化)
一.通用流程梳理
1.原来老的的流程(第七步有掉单风险)
第1. 先创建订单
第2.订单返回正常后(有订单号),启动苹果购买流程,调用苹果接口
第3.如果 没登录会要求用户登录appleId,如果已经登录,会弹出购买确认框(该弹框也是苹果控制)
第4.点击购买后,等待直接结果回调
第5.扣款成功后,苹果回调接口里面会有receipt 数据。
第6.如果receipt不为空,将改值作为入参,调用后台印证支付成功接口。
第7.验证接口返回正常后,通知页面重新请求余额接口进行刷新。(验证订单有效的情况,可能会导致掉单情况)

2.优化后的流程图如下 (添加本地数据库机制,如果印证成功,就清除数据库同时结束交易;如果印证不成功(error或faliure),就不清除交易,调用苹果自己的重试机制)


苹果内购开发总结(含掉单问题优化)_第2张图片
image.png

二.具体实现代码如下

@interface AppDelegate ()

@end

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //支付
    [[PayCenter sharedPayCenter] startInit];

    return YES;
}
@end
#import 
typedef NS_ENUM(NSInteger, Payment) {
    IAP1 = 1,
    IAP6 = 6,
    IAP25 = 25,
    IAP68 = 68,
    IAP108 = 108,
    IAP158 = 158,
    IAP208 = 208,
    IAP288 = 288
};
@interface PayCenter : NSObject
singleton_interface(PayCenter);
- (void)startInit;
- (void)payWithMoney:(NSInteger)money andType:(PayType)type dataDic:(NSDictionary *)dataDic;
@property (nonatomic, strong) MBProgressHUD *hud;

//在内购项目中创的商品单号
#define kProductID_IAP1 @"org.test.nursning.1"    //¥1
#define kProductID_IAP6 @"org.test.nursning.6"    //¥6
#define kProductID_IAP25 @"org.test.nursning.25"  //¥25
#define kProductID_IAP68 @"org.test.nursning.68"  //¥68
#define kProductID_IAP108 @"org.test.nursning.108" //¥108
#define kProductID_IAP158 @"org.test.nursning.158" //¥158
#define kProductID_IAP208 @"org.test.nursning.208" //¥208
#define kProductID_IAP288 @"org.test.nursning.288" //¥288
#import "PayCenter.h"
#import "PayHttpRequest.h"
#import 
#import “orderFromModel.h"
@interface PayCenter ()  {
    NSInteger _money;
    NSString *_orderFromId;//订单ID
}
@property (nonatomic, strong) NSMutableDictionary *dataDic;
@end

@implementation PayCenter
singleton_implementation(PayCenter);
- (void)startInit {
    //添加支付结果回调监听(这样中途异常没有结束的单子,下次在进来,就会有直接继续上次没有结束的交易)
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    [[Curi_sqlite_IAP share] db_open];
}
- (void)payVipItem:(NSString *)IAP_ID dataDic:(NSDictionary *)dataDic{
    
    NSString *commodityId = dataDic[@"commodityId"] ?: @"";
    //走内购创建订单接口 还是vip创建订单接口
    NSDictionary *parameter = @{@"accountId":NurseId,
                                @"productId":commodityId};
    WS(weakSelf);
    [Request requestPOST:parameter view:nil urlPre:TradeCenterURL funItem:HuFuncItem_vipTrade_createOrder success:^(NSDictionary *dic) {
        weakSelf.orderFromId = [orderFromModel mj_objectWithKeyValues:dic[@"data"]].orderFromId;
        if ([SKPaymentQueue canMakePayments]  && IAP_ID.length > 0) {
            NSArray *product = [[NSArray alloc] initWithObjects:IAP_ID, nil];
            NSSet *nsSet = [NSSet setWithArray:product];
            SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsSet];
            request.delegate = self;
            [request start];
        } else {
            UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                               message:@"您的手机没有打开程序内付费购买"
                                                              delegate:nil
                                                     cancelButtonTitle:@"取消"
                                                     otherButtonTitles:nil];
            [alerView show];
        }
    } error:^(NSDictionary *dic) {
        [MBProgressHUD showError:dic[@"errMsg"]];
    } failure:^{
        [MBProgressHUD showError:@"服务器开小差了,请稍后再试"];
    }];
}
- (void)payWithMoney:(NSInteger)money andType:(PayType)type dataDic:(NSDictionary *)dataDic {
    _money = money;
    type = AppleInPurchasePay;
    self.dataDic = [NSMutableDictionary dictionaryWithDictionary:dataDic];
    switch (type) {
        case AppleInPurchasePay: {
            //购买之前创建订单 把订单号也传给后台 创建订单后 继续内购流程
            NSString *moneyString = [NSString stringWithFormat:@"%li", money * 100];
            NSDictionary *paremeter = @{ @"rechargeValue" : moneyString,
                                         @"accountId" : NurseId };
            WS(weakSelf);
            [Request requestPOST:paremeter
                view:nil
                urlPre:TradeCenterURL
                funItem:HuFuncItem_CreateOrder
                success:^(NSDictionary *dic) {
                    weakSelf.orderFromId = [orderFromModel mj_objectWithKeyValues:dic[@"data"]].orderFromId;
                    if ([SKPaymentQueue canMakePayments]) {
                        [self payTypeApplePay];
                    } else {
                        UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                           message:@"您的手机没有打开程序内付费购买"
                                                                          delegate:nil
                                                                 cancelButtonTitle:@"取消"
                                                                 otherButtonTitles:nil];
                        [alerView show];
                    }
                }
                error:^(NSDictionary *dic) {
                    [MBProgressHUD showError:dic[@"errMsg"]];
                }
                failure:^{
                    [MBProgressHUD showError:@"failure"];
                }];
        } break;
        default:
            break;
    }
}

- (void)payTypeApplePay {
    NSArray *product = nil;
    switch (_money) {
        case IAP1: {
            product = [[NSArray alloc] initWithObjects:kProductID_IAP1, nil];
        } break;
        case IAP6: {
            product = [[NSArray alloc] initWithObjects:kProductID_IAP6, nil];
        } break;
        case IAP25: {
            product = [[NSArray alloc] initWithObjects:kProductID_IAP25, nil];
        } break;
        case IAP68: {
            product = [[NSArray alloc] initWithObjects:kProductID_IAP68, nil];
        } break;
        case IAP108: {
            product = [[NSArray alloc] initWithObjects:kProductID_IAP108, nil];
        } break;
        case IAP158: {
            product = [[NSArray alloc] initWithObjects:kProductID_IAP158, nil];
        } break;
        case IAP208: {
            product = [[NSArray alloc] initWithObjects:kProductID_IAP208, nil];
        } break;
        case IAP288: {
            product = [[NSArray alloc] initWithObjects:kProductID_IAP288, nil];
        } break;
        default:
            break;
    }
    NSSet *nsSet = [NSSet setWithArray:product];
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsSet];
    request.delegate = self;
    [request start];
}
#pragma mark -  SKProductsRequestDelegate代理
//返回的在苹果服务器请求的产品信息
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    SKProduct *product = response.products.lastObject;
    //发起购买请求
    if (product) {
        //1.改方法不一定有效
        /*我们创建苹果订单初始化SKPayment时我们应该使用SKMutablePayment,这个类里面有一个参数叫applicationUsername的成员变量,我们可以把后台服务器的订单号写到这里,在付款成功后返回的SKPaymentTransaction里面能拿到这个参数【transaction.payment.applicationUsername】,然后就带着它去请求本地服务器,*/
        SKMutablePayment *payment = [SKMutablePayment paymentWithProduct:product];
        payment.applicationUsername = self.orderFromId;
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }
}
//实现监听方法 购买以后的回调
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
    SKPaymentTransaction *transaction = transactions.lastObject;
    switch (transaction.transactionState) {
        case SKPaymentTransactionStatePurchased: {
            //            NSLog(@"购买完成,向自己的服务器验证");
            [self completeTransaction:transaction];
        } break;
        case SKPaymentTransactionStateFailed: {
            //             NSLog(@"交易失败");
            [[PayCenter sharedPayCenter].hud hide:YES];
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
        } break;
        case SKPaymentTransactionStateRestored: {
            [self completeTransaction:transaction];
        } break;
        case SKPaymentTransactionStatePurchasing: {
            //            NSLog(@"商品添加进列表");
        } break;
        default: {
            //            NSLog(@"支付失败");
        } break;
    }
}
//交易结束 验证支付是否成功
- (void)completeTransaction:(SKPaymentTransaction *)transaction {
    //    取购买过后存储在本地的收据
    NSData *receipt = [NSData dataWithContentsOfURL:[[NSBundle mainBundle] appStoreReceiptURL]];
    if (receipt) {
        NSString *key = transaction.transactionIdentifier;
        NSString *orderId = transaction.payment.applicationUsername ?: self.orderFromId;
        //添加保护
        if (orderId.length <= 0) {
            NSDictionary *dic = [[Curi_sqlite_IAP share] db_select_transactionId:key];
            orderId = dic[@"orderId"];
        }
        [[Curi_sqlite_IAP share] db_insert:key orderId:orderId state:@"已支付"];
        NSDictionary *parameter = @{ @"transactionId" : key,
                                     @"receiptData" : [receipt base64EncodedStringWithOptions:0],
                                     @"orderId" : orderId };
        [Request requestPOST:parameter
            view:nil
            urlPre:TradeCenterURL
            funItem:HuFuncItem_ByApplePay
            success:^(NSDictionary *dic) {
                [[PayCenter sharedPayCenter].hud hide:YES];
                if (![dic isEqual:[NSNull null]] || ![dic isKindOfClass:[NSNull class]]) {
                    NSInteger result = [dic[@"data"][@"code"] integerValue];
                    if (result == 1) {
#warning 后台返回tid 删除对应的tid才可以
                        [[Curi_sqlite_IAP share] db_delete:key];
                        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                        [kNotificationCenter postNotificationName:kBuyCoinSuccess object:nil];
                    } else {
                        [MBProgressHUD showError:dic[@"data"][@"msg"]];
                        
                        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                    }
                }
            }
            error:^(NSDictionary *dic) {
                [[PayCenter sharedPayCenter].hud hide:YES];
            }
            failure:^{
                [[PayCenter sharedPayCenter].hud hide:YES];
            }];
    }
}
//报错流程出现问题
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
    [alertView show];
}
- (void)failedTransaction:(SKPaymentTransaction *)transaction {
    if (transaction.error.code == SKErrorPaymentCancelled) {
        [self alertViewShow:@"你已取消购买"];
    } else if (transaction.error.code == SKErrorPaymentInvalid) {
        [self alertViewShow:@"支付无效"];
    } else if (transaction.error.code == SKErrorPaymentNotAllowed) {
        [self alertViewShow:@"不允许支付"];
    } else if (transaction.error.code == SKErrorStoreProductNotAvailable) {
        [self alertViewShow:@"产品无效"];
    } else if (transaction.error.code == SKErrorClientInvalid) {
        [self alertViewShow:@"客服端无效"];
    }
    //失败也结束 
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
- (void)alertViewShow:(NSString *)errMsg{
    
    UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"提 示" message:errMsg  delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alert show];
}
- (void)dealloc{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
    [[Curi_sqlite_IAP share] db_close];
}
#import 
@interface Curi_sqlite_IAP : NSObject
@property (nonatomic, strong) FMDatabase *dataBase;
+ (Curi_sqlite_IAP *)share;
//打开
- (FMDatabase *)db_open;
//关闭
- (void)db_close;
/**
 增加一条数据到数据库
 @param transactionId 苹果返回的事物编号
 @param orderId 后台返回的业务订单编号
 @param state 记录状态  已支付  已充值
 @return 数据库插入成功标识
 */
- (BOOL)db_insert:(NSString *)transactionId orderId:(NSString *)orderId state:(NSString *)state;
//查询 返回state 
- (NSDictionary *)db_select_transactionId:(NSString *)transactionId;
//删除
- (BOOL)db_delete:(NSString *)transactionId;
@end

#import "Curi_sqlite_IAP.h"
@implementation Curi_sqlite_IAP
+ (Curi_sqlite_IAP *)share {
    static Curi_sqlite_IAP *sql = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sql = [[Curi_sqlite_IAP alloc] init];
    });
    return sql;
}
- (FMDatabase *)db_open {
    if (_dataBase != nil) {
        return _dataBase;
    }
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *dbPath = [path stringByAppendingPathComponent:@"curi.sqlite"];
    TRACELOG(@"%@", dbPath);
    _dataBase = [FMDatabase databaseWithPath:dbPath];
    if ([_dataBase open]) {
        //        NSLog(@"打开成功");
    } else {
        //        NSLog(@"打开失败");
    }
    //如果是新版本删除旧表
    //    if([HuConfigration sharedHuConfigration].isNewVersion)
    //    {
    //        NSString *sql = [NSString stringWithFormat:@"DROP TABLE IF EXISTS IAP"];
    //        [_dataBase executeUpdate:sql];
    //    }
    NSString *sql = [NSString stringWithFormat:@"create table if not exists IAP (id integer primary key autoincrement, accountId integer, transactionId TEXT, orderId TEXT,transactionDate DATETIME, rechargeDate DATETIME, state TEXT)"];
    [_dataBase executeUpdate:sql];
    return _dataBase;
}
- (void)db_close {
    [_dataBase close];
    _dataBase = nil;
}
- (BOOL)db_insert:(NSString *)transactionId orderId:(NSString *)orderId state:(NSString *)state {
    NSString *sql;
    NSDictionary *dic = [[Curi_sqlite_IAP share] db_select_transactionId:transactionId];
    NSString *curState = dic[@"state"] ?: @"";
    //有记录
    if (curState.length > 0) {
        sql = [NSString stringWithFormat:@"update IAP set state = '%@' where transactionId = '%@'", state, transactionId];
    }
    //无记录
    else {
        sql = [NSString stringWithFormat:@"insert into IAP (accountId, transactionId, orderId, transactionDate, rechargeDate, state) values(%ld, '%@', '%@', '%@', '%@', '%@')", [NurseId integerValue], transactionId, orderId, @"", @"", state];
    }
    return [_dataBase executeUpdate:sql];
}
- (NSDictionary *)db_select_transactionId:(NSString *)transactionId {
    NSDictionary *dic;
    //单条记录
    if (transactionId > 0) {
        NSString *sql = [NSString stringWithFormat:@"select * from IAP where transactionId = '%@'", transactionId];
        FMResultSet *rs = [_dataBase executeQuery:sql];
        [rs next];
        NSString *state = [rs stringForColumn:@"state"] ?: @"";
        NSString *orderId = [rs stringForColumn:@"orderId"] ?: @"";
        dic = @{ @"state" : state,
                 @"orderId" : orderId };
    }
    return dic;
}
- (BOOL)db_delete:(NSString *)transactionId {
    NSString *sql;
    if (transactionId > 0) {
        sql = [NSString stringWithFormat:@"delete from IAP where transactionId = '%@'", transactionId];
    } else {
        sql = @"delete from IAP";
    }
    return [_dataBase executeUpdate:sql];
}
@end

2018年3月17日
第一次提交内购 一定要选择添加内功项目,不然上架的app是不会开启内购功能的


苹果内购开发总结(含掉单问题优化)_第3张图片
image.png

2018年2月8日
一.苹果后台页面一些内购项目配置


苹果内购开发总结(含掉单问题优化)_第4张图片
image.png

苹果内购开发总结(含掉单问题优化)_第5张图片
image.png

2018年2月6日
一.内购测试相关


苹果内购开发总结(含掉单问题优化)_第6张图片
image.png

第一步:将手机appleid 注销掉
第二步:直接购买,接着你输入上面 沙盒账号
出现如下画面,说明正常


苹果内购开发总结(含掉单问题优化)_第7张图片
image.png

2017年11月21日
1.app内购无法购买问题,经过排查是可以正常购买的。
线上版本2.6.6是正常 的
苹果内购开发总结(含掉单问题优化)_第8张图片
image.png

目前测试出来:
只有appstore上的包,才可以用真实账号购买
如果装的是本地包(jenkins下载的或企业版本),建议用沙盒账号测试内购功能。
2017年9月20日
1.项目需要开启


苹果内购开发总结(含掉单问题优化)_第9张图片
image.png

如果您发现本文对你有所帮助,如果您认为其他人也可能受益,请把它分享出去。

你可能感兴趣的:(苹果内购开发总结(含掉单问题优化))