<SKPaymentTransactionObserver,SKRequestDelegate,SKProductsRequestDelegate>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{ //添加一个交易队列观察者
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}
- (void)paymentQueue:(SKPaymentQueue *)queue restoreCompletedTransactionsFailedWithError:(NSError *)error {
NSLog(@"%@",error);
}
/// Called when all restorable transactions have been processed by the payment queue.
- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue {
NSLog(@"%@",queue.transactions);
if (queue.transactions.count==0)
{
[YJProgressHUD showMessage:@"您还没购买过会员!"];
}
else
{
for (SKPaymentTransaction *transaction in queue.transactions)
{
NSLog(@"%@",transaction.originalTransaction.transactionIdentifier);//不会改变的订单号
}
通过这个订单号去向后台请求会员状态
}
}
//监听购买结果
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions API_AVAILABLE(ios(3.0), macos(10.7), watchos(6.2))
{
for (SKPaymentTransaction *tran in transactions) {
[Singleton ShareDatabase].hgtran = tran;//一会儿需要删除的购买凭证
// 如果小票状态是购买完成
if (SKPaymentTransactionStatePurchased == tran.transactionState) {
// 订阅特殊处理
if (tran.originalTransaction) {
// 如果是自动续费的订单,originalTransaction会有内容
NSLog(@"自动续费的订单,originalTransaction = %@",tran.originalTransaction);
} else {
// 普通购买,以及第一次购买自动订阅
NSLog(@"普通购买,以及第一次购买自动订阅");
}
[[SKPaymentQueue defaultQueue] finishTransaction:tran];
[self verifyPruchase:tran isServerflag:NO];
} else if (SKPaymentTransactionStatePurchasing == tran.transactionState) {
NSLog(@"商品添加进列表");
} else if (SKPaymentTransactionStateRestored == tran.transactionState) {
NSLog(@"已经购买过商品");
[YJProgressHUD hideHUD];
[[SKPaymentQueue defaultQueue] finishTransaction:tran];
} else if (SKPaymentTransactionStateFailed == tran.transactionState) {
NSLog(@"交易失败");
[YJProgressHUD hideHUD];
[[SKPaymentQueue defaultQueue] finishTransaction:tran];
}
}
}
测试验证地址:https://sandbox.itunes.apple.com/verifyReceipt
//正式验证地址:https://buy.itunes.apple.com/verifyReceipt
- (void)verifyPruchase:(SKPaymentTransaction *)tran isServerflag:(BOOL)flag
{// 发送给苹果服务器/自己服务器认证:
NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
// 从沙盒中获取到购买凭据
NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
// 发送网络POST请求,对购买凭据进行验证
NSString *serverString = @"https://buy.itunes.apple.com/verifyReceipt";
if (flag) {
serverString = @"https://sandbox.itunes.apple.com/verifyReceipt";
}
NSURL *storeURL = [NSURL URLWithString:serverString];
NSMutableURLRequest *urlRequest =
[NSMutableURLRequest requestWithURL:storeURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
urlRequest.HTTPMethod = @"POST";
NSDictionary *requestContents = @{
@"receipt-data":[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed],
@"password":@""//自己的内购配置
};
NSData *payloadData = [NSJSONSerialization dataWithJSONObject:requestContents
options:0
error:nil];
urlRequest.HTTPBody = payloadData;
// 提交验证请求,并获得官方的验证JSON结果 iOS9后更改了另外的一个方法
NSData *resultData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
// 官方验证结果为空
if (resultData == nil) {
NSLog(@"验证失败");
return;
}
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:resultData options:NSJSONReadingAllowFragments error:nil];
if (dict != nil) {
NSLog(@"%@",dict);
NSString *status = [NSString stringWithFormat:@"%@",dict[@"status"]];
if (status && [status isEqualToString:@"21007"]) {
[self verifyPruchase:[Singleton ShareDatabase].hgtran isServerflag:YES];
}
else if (status && [status isEqualToString:@"0"])
{
[Singleton ShareDatabase].TransactionID = StringFormat(@"%@",[[[dict valueForKey:@"latest_receipt_info"] objectAtIndex:0] valueForKey:@"original_transaction_id"]);
[Singleton ShareDatabase].tokenStr = [Singleton ShareDatabase].TransactionID;
[[NSUserDefaults standardUserDefaults]setValue:[Singleton ShareDatabase].tokenStr forKey:@"TokenStr"];
[[NSUserDefaults standardUserDefaults]synchronize];
[Singleton ShareDatabase].receipt = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
NSString *typeStr = @"";
if(flag == YES){
typeStr = @"0";//沙盒
}
else{
typeStr = @"1";//正式
}
去请求后台,改变会员状态,成功后记得销毁凭证
[[SKPaymentQueue defaultQueue] finishTransaction:[Singleton ShareDatabase].hgtran];
}
}
}
购买方法
NSString *PRODUCTID = @"";//自己内购配置
//判断是否可进行支付
if ([SKPaymentQueue canMakePayments]) {
[YJProgressHUD showLoading:@"加载中..."];
[self requestProductData:PRODUCTID];
} else {
NSLog(@"不允许程序内付费");
}
- (void)requestProductData:(NSString *)type {
//根据商品ID查找商品信息
NSArray *product = [[NSArray alloc] initWithObjects:type, nil];
NSSet *nsset = [NSSet setWithArray:product];
//创建SKProductsRequest对象,用想要出售的商品的标识来初始化, 然后附加上对应的委托对象。
//该请求的响应包含了可用商品的本地化信息。
SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
request.delegate = self;
[request start];
}
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response API_AVAILABLE(ios(3.0), macos(10.7), watchos(6.2))
{
//接收商品信息
NSArray *product = response.products;
if ([product count] == 0) {
NSLog(@"--------------没有商品------------------");
return;
}
NSLog(@"productID:%@", response.invalidProductIdentifiers);
NSLog(@"产品付费数量:%lu",(unsigned long)[product count]);
// SKProduct对象包含了在App Store上注册的商品的本地化信息。
SKProduct *storeProduct = nil;
for (SKProduct *pro in product) {
NSLog(@"%@", [pro description]);
NSLog(@"%@", [pro localizedTitle]);
NSLog(@"%@", [pro localizedDescription]);
NSLog(@"%@", [pro price]);
NSLog(@"%@", [pro productIdentifier]);
storeProduct = pro;
}
SKPayment *payment = [SKPayment paymentWithProduct:storeProduct];
//发送内购请求
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
NSLog(@"------------------购买失败-----------------:%@", error);
}
- (void)requestDidFinish:(SKRequest *)request {
NSLog(@"------------购买完成-----------------");
}
恢复购买方法
[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];