首先介绍实现苹果内购的流程
购买
1.向苹果服务器 请求商品列表
2.苹果服务器 在回调中返回商品列表
3.向苹果服务器 请求购买商品列表的第一个
4.苹果服务器 在回调中返回购买结果
5.根据回调的结果 进行处理
恢复购买
1.向苹果服务器 请求恢复购买
2.苹果服务器 在回调中返回恢复购买结果
5.根据回调的结果 进行处理
下面是代码实现
下面是.h文件的实现
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface PQIAPManager : NSObject
+ (PQIAPManager *)sharedManager;
/**请求购买商品*/
- (void)requestProductWithId:(NSString *)productId;
/**请求恢复购买*/
- (void)restore;
@end
NS_ASSUME_NONNULL_END
下面是.m文件的实现
#import "PQIAPManager.h"
#import <StoreKit/StoreKit.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/AdSupport.h>
/**共享密钥*/
#define KSecretKey @""
/**凭证校验地址*/
#define KReceiptCheckUrl @""
/**订阅状态检验地址*/
#define KStateCheckUrl @""
@interface PQIAPManager()<SKPaymentTransactionObserver,SKProductsRequestDelegate,SKRequestDelegate>
// 交易是否结束
@property (nonatomic, assign) BOOL isRequestFinished;
// 判断是购买还是恢复
@property (nonatomic, assign) BOOL isRestore;
@end
@implementation PQIAPManager
// 单例
+ (instancetype)sharedManager{
static dispatch_once_t pred;
static PQIAPManager *manager = nil;
dispatch_once(&pred, ^{
manager = [[self alloc] init];
});
return manager;
}
// 创建时就开始监听购买事件
- (instancetype)init{
if (self = [super init]) {
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
self.isRequestFinished = YES;
}
return self;
}
// 销毁时就移除监听事件
- (void)dealloc{
[[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
继续在.m文件中添加方法
/**请求商品列表*/
- (void)requestProductWithId:(NSString *)productId {
self.isRestore = NO;
if (self.isRequestFinished) {
if ([SKPaymentQueue canMakePayments]) { //用户允许app内购
if (productId.length) {
self.isRequestFinished = NO; //正在请求
NSLog(@"%@商品正在请求中...",productId);
NSArray *product = [[NSArray alloc] initWithObjects:productId, nil];
NSSet *set = [NSSet setWithArray:product];
SKProductsRequest *productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:set];
productsRequest.delegate = self;
[productsRequest start];
}
} else { //没有权限
self.isRequestFinished = YES; //完成请求
NSLog(@"没有购买权限");
}
} else {
NSLog(@"上次请求购买未完成,请稍后重试!");
}
}
// 请求购买商品列表的第一个
#pragma mark SKProductsRequestDelegate 请求商品列表后的回调
- (void)productsRequest:(nonnull SKProductsRequest *)request didReceiveResponse:(nonnull SKProductsResponse *)response {
NSArray *product = response.products;
if (product.count == 0){
return;
} else {
if (response.invalidProductIdentifiers.count) {
NSLog(@"商品请求错误,error:%@", response.invalidProductIdentifiers);
}
NSLog(@"商品详情:%@",[product[0] description]);
NSLog(@"商品价格:%@",[product[0] price]);
NSLog(@"商品名字:%@",[product[0] productIdentifier]);
// 请求购买
SKPayment *payment = [SKPayment paymentWithProduct:product[0]];
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
}
// 处理请求购买后的回调
#pragma mark - SKProductsRequestDelegate 请求购买后的回调
- (void)paymentQueue:(nonnull SKPaymentQueue *)queue updatedTransactions:(nonnull NSArray<SKPaymentTransaction *> *)transactions {
if (!self.isRestore) {
for (SKPaymentTransaction *tran in transactions) {
switch (tran.transactionState) {
case SKPaymentTransactionStatePurchasing: // 正在交易
break;
case SKPaymentTransactionStatePurchased: // 交易完成
[self completeTransaction:tran];
if (tran.originalTransaction) {
// 如果是自动续费的订单,originalTransaction会有内容
if (tran.originalTransaction.transactionIdentifier) {
NSLog(@"自动续费的订单ID = %@",tran.originalTransaction.transactionIdentifier);
[self saveOrderId:tran.originalTransaction.transactionIdentifier];
}
} else {
// 普通购买,以及第一次购买自动订阅
if (tran.transactionIdentifier) {
NSLog(@"普通购买,以及第一次购买自动订阅ID = %@",tran.transactionIdentifier);
[self saveOrderId:tran.transactionIdentifier];
}
}
NSLog(@"购买完成,正在校验购买凭证...");
[self vertifyReceipt]; // 校验购买凭证
break;
case SKPaymentTransactionStateFailed: // 交易失败
[self completeTransaction:tran];
NSLog(@"购买失败!");
break;
case SKPaymentTransactionStateRestored: // 已经购买过该商品
[self completeTransaction:tran];
NSLog(@"已经购买过该商品!");
break;
default:
break;
}
}
}
}
- (void)completeTransaction:(SKPaymentTransaction *)transaction {
self.isRequestFinished = YES; // 请求完成
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
// 根据公司需求校验凭证
- (void)vertifyReceipt{
NSURL * receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
if ([[NSFileManager defaultManager] fileExistsAtPath:[receiptURL path]]){
[self vertifyReceiptSuccess:^{
NSLog(@"校验成功!");
} failure:^{
NSLog(@"校验失败!");
}];
} else {
// 如果凭证为空,则再发一次凭证请求
SKReceiptRefreshRequest *refreshReceiptRequest = [[SKReceiptRefreshRequest alloc] initWithReceiptProperties:@{}];
refreshReceiptRequest.delegate = self;
[refreshReceiptRequest start];
}
}
// 如果凭证为空,需要再发一次凭证请求,处理请求成功后的回调
#pragma mark - 成功请求凭证后的回调
- (void)requestDidFinish:(SKRequest *)request{
if ([request isKindOfClass:[SKReceiptRefreshRequest class]]) {
NSURL *receiptUrl = [[NSBundle mainBundle] appStoreReceiptURL];
if ([[NSFileManager defaultManager] fileExistsAtPath:[receiptUrl path]]) {
[self vertifyReceiptSuccess:^{
NSLog(@"再次请求凭证后,校验成功!");
} failure:^{
NSLog(@"再次请求凭证后,校验失败!");
}];
}
}
}
// 校验凭证
- (void)vertifyReceiptSuccess:(void(^)(void))success failure:(void(^)(void))failure {
NSString *receipt = [self getReceipt];
// 校验凭证步骤需要按照你公司的需求来写
}
// 检验订单是否还在订阅期内
- (void)checkOrderStateSuccess:(void(^)(void))success failure:(void(^)(void))failure {
NSString *receipt = [self getOrderId];
// 检验订单步骤需要按照你公司的需求来写
}
// 获取凭证
- (NSString *)getReceipt {
NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
NSString *encodeReceiptStr = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
return encodeReceiptStr;
}
// 保存订单ID
- (void)saveOrderId:(NSString *)orderId{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:orderId forKey:@"orderId"];
[defaults synchronize];
}
// 获取订单ID
- (NSString *)getOrderId{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
return [defaults valueForKey:@"orderId"];
}
恢复购买
// 恢复购买
- (void)restore {
self.isRestore = YES;
[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}
// 恢复成功后的回调
- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue{
if (queue.transactions.count) {
for (SKPaymentTransaction *tran in queue.transactions) {
if (tran.originalTransaction.transactionIdentifier) {
[self saveOrderId:tran.originalTransaction.transactionIdentifier];
break;
}
}
// 检验订单是否还在订阅期内
[self checkOrderStateSuccess:^{
NSLog(@"订单还在订阅期,校验成功!");
} failure:^{
NSLog(@"订单已过期,校验失败!");
}];
} else {
// 没有可恢复的购买项
}
}
// 恢复失败后的回调
- (void)paymentQueue:(SKPaymentQueue *)queue restoreCompletedTransactionsFailedWithError:(NSError *)error {
// 没有可恢复的购买项
}
最后
本篇主要讲述了一个详细的内购流程及代码实现,感兴趣的给个赞或者关注~~~
你们的支持就是我更新的动力!!!