核心代码:
引入头文件:#import <StoreKit/StoreKit.h>
代理:SKProductsRequestDelegate,SKPaymentTransactionObserver
设置支付服务:[[SKPaymentQueue defaultQueue] addTransactionObserver:self]
结束时销毁:[[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
1、初始化SKProductsRequest请求
// 初始化请求
SKProductsRequest *productsRequest = [[SKProductsRequest alloc]initWithProductIdentifiers:productSet];
self.request = productsRequest;
// 设置delegate
productsRequest.delegate = self;
// 开始请求
[productsRequest start];
2、在代理的方法中处理业务逻辑
#pragma mark -- SKProductsRequestDelegate <收到返回的信息>
- (void)productsRequest:(nonnull SKProductsRequest *)request didReceiveResponse:(nonnull SKProductsResponse *)response {
// 发送购买请求,创建票据,这个时候就会有弹窗了
SKPayment *payment = [SKPayment paymentWithProduct:requestProduct];
// 将票据加入到交易队列
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
#pragma mark -- SKPaymentTransactionObserver <监听购买结果>
- (void)paymentQueue:(nonnull SKPaymentQueue *)queue updatedTransactions:(nonnull NSArray<SKPaymentTransaction *> *)transactions {
for (SKPaymentTransaction *transaction in transactions) {
switch (transaction.transactionState) {
case SKPaymentTransactionStatePurchased:
// 请求服务器,验证购买
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;
case SKPaymentTransactionStateRestored:
// 恢复商品,已经购买过商品
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;
case SKPaymentTransactionStateFailed:
// 购买商品失败
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;
case SKPaymentTransactionStatePurchasing:
// 正在交易
break;
default:
break;
}
}
}
网友评论