继上一篇iOS内购图文教程,下面是代码教程
创建一个单例类
.h文件
#import <Foundation/Foundation.h>
#import <StoreKit/StoreKit.h>
@protocol LMIAPManagerDelegate <NSObject>
@optional
- (void)receiveProduct:(SKProduct *)product;
- (void)successfulPurchaseOfId:(NSString *)productId andReceipt:(NSData *)transactionReceipt;
- (void)failedPurchaseWithError:(NSString *)errorDescripiton;
@end
@interface ApplePayManager : NSObject
@property (nonatomic, assign)id<LMIAPManagerDelegate> delegate;
//创建单例
+ (instancetype)sharedInstance;
- (BOOL)requestProductWithId:(NSString *)productId;
- (BOOL)purchaseProduct:(SKProduct *)skProduct;
- (BOOL)restorePurchase;
@property (strong, nonatomic)NSTimer *timer;
.m文件
#import "ApplePayManager.h"
@interface ApplePayManager()<SKProductsRequestDelegate, SKPaymentTransactionObserver>
{
SKProduct *myProduct;
}
@end
@implementation ApplePayManager
//单例
+ (instancetype)sharedInstance{
static ApplePayManager *payManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
payManager = [[ApplePayManager alloc] init];
});
return payManager;
}
#pragma mark - **************** Public Methods
/** TODO:请求商品*/
- (BOOL)requestProductWithId:(NSString *)productId {
if (productId.length > 0) {
NSLog(@"请求商品: %@", productId);
SKProductsRequest *productRequest = [[SKProductsRequest alloc]initWithProductIdentifiers:[NSSet setWithObject:productId]];
productRequest.delegate = self;
[productRequest start];
return YES;
} else {
NSLog(@"商品ID为空");
}
return NO;
}
/** TODO:购买商品*/
- (BOOL)purchaseProduct:(SKProduct *)skProduct {
if (skProduct != nil) {
if ([SKPaymentQueue canMakePayments]) {
SKPayment *payment = [SKPayment paymentWithProduct:skProduct];
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
[[SKPaymentQueue defaultQueue] addPayment:payment];
return YES;
} else {
NSLog(@"失败,用户禁止应用内付费购买.");
}
}
return NO;
}
/** TODO:非消耗品恢复*/
- (BOOL)restorePurchase {
if ([SKPaymentQueue canMakePayments]) {
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
return YES;
} else {
NSLog(@"失败,用户禁止应用内付费购买.");
}
return NO;
}
#pragma mark - **************** SKProductsRequest Delegate
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
NSArray *myProductArray = response.products;
if (myProductArray.count > 0) {
myProduct = [myProductArray objectAtIndex:0];
[_delegate receiveProduct:myProduct];
}else {
NSLog(@"无法获取产品信息,购买失败。");
[_delegate receiveProduct:myProduct];
}
}
#pragma mark - **************** SKPaymentTransactionObserver Delegate
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
for (SKPaymentTransaction *transaction in transactions) {
switch (transaction.transactionState) {
case SKPaymentTransactionStatePurchasing: //商品添加进列表
NSLog(@"商品:%@被添加进购买列表",myProduct.localizedTitle);
break;
case SKPaymentTransactionStatePurchased://交易成功
[self completeTransaction:transaction];
break;
case SKPaymentTransactionStateFailed://交易失败
[self failedTransaction:transaction];
break;
case SKPaymentTransactionStateRestored://已购买过该商品
break;
case SKPaymentTransactionStateDeferred://交易延迟
break;
default:
break;
}
}
}
#pragma mark - **************** Private Methods
- (void)completeTransaction:(SKPaymentTransaction *)transaction {
NSURL *receiptUrl = [[NSBundle mainBundle] appStoreReceiptURL];
NSData *receiptData = [NSData dataWithContentsOfURL:receiptUrl];
[_delegate successfulPurchaseOfId:transaction.payment.productIdentifier andReceipt:receiptData];
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
- (void)failedTransaction:(SKPaymentTransaction *)transaction {
if (transaction.error.code != SKErrorPaymentCancelled && transaction.error.code != SKErrorUnknown) {
[_delegate failedPurchaseWithError:transaction.error.localizedDescription];
}
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
-(void)dealloc
{
[[SKPaymentQueue defaultQueue] removeTransactionObserver:self];//解除监听
}
在礼物页面,调起单例,添加内购代理方法
//appleProductId 就是添加商品时填写的ID
[[ApplePayManager sharedInstance] requestProductWithId:[NSString stringWithFormat:@"%@",model.appleProductId]];
self.hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
self.hud.delegate = self;
self.hud.labelText = @"连接苹果商店";
实现代理方法
#pragma mark - **************** MLIAPManager Delegate
- (void)receiveProduct:(SKProduct *)product {
if (product != nil) {
//购买商品
if (![[ApplePayManager sharedInstance] purchaseProduct:product]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"失败" message:@"您禁止了应用内购买权限,请到设置中开启" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:nil, nil];
[alert show];
}
[self.hud hide:YES];
} else {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"失败" message:@"无法连接App store!" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:nil, nil];
[alert show];
[self.hud hide:YES];
}
}
- (void)successfulPurchaseOfId:(NSString *)productId andReceipt:(NSData *)transactionReceipt {
NSString *transactionReceiptString = [transactionReceipt base64EncodedStringWithOptions:0];
if ([transactionReceiptString length] > 0) {
// 向自己的服务器验证购买凭证(此处应该考虑将凭证本地保存,对服务器有失败重发机制)
/**
服务器要做的事情:
接收ios端发过来的购买凭证。
判断凭证是否已经存在或验证过,然后存储该凭证。
将该凭证发送到苹果的服务器验证,并将验证结果返回给客户端。
如果需要,修改用户相应的会员权限
*/
//1.如果用户购买成功之后,网络突然不好,无法上传服务器,会造成购买之后没有金币返回
//2.如果上传服务器失败,凭证保存在本地数组,向服务器发送请求,直至成功为止。
//3.如果购买成功之后,因某些原因APP突然闪退,凭证保存在本地,应用启动时,再次向服务器发送请求,直至成功为止
//4.出现以外情况,例如手机突然关机等,提示用户联系客服
//5.我的做法:在mainRunLoop中添加定时器,在出现以上状况时,发起请求,直至数组中所有凭证上传成功之后,移除定时器。
NSLog(@"%@",transactionReceiptString);
}
}
- (void)failedPurchaseWithError:(NSString *)errorDescripiton {
NSLog(@"购买失败");
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"失败" message:errorDescripiton delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:nil, nil];
[alert show];
}
网友评论