通过监听获取队列结果信息, SKPaymentTransactionStatePurchased 这个状态是已经被扣钱了的.
// 监听购买结果
// [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions { // 交易结果
for (SKPaymentTransaction *transaction in transactions) {
switch (transaction.transactionState) {
case SKPaymentTransactionStatePurchased:{ // 队列
[self completeTransaction:transaction]; // 移除队列
[self verifyPurchaseWithPaymentTransaction]; // 验证购买, 避免越狱软件模拟苹果请求达到非法购买问题
NSLog(@"----- 交易成功 --------");
}
break;
case SKPaymentTransactionStateFailed:{ //队列里面没东西
[self failedTransaction:transaction];
NSLog(@"-----交易失败--------");
}
break;
case SKPaymentTransactionStateRestored://已经购买过该商品
[self restoreTransaction:transaction];
NSLog(@"-----已经购买过该商品 --------");
case SKPaymentTransactionStatePurchasing: //商品添加进列表
NSLog(@"----- 商品添加进列表--------");
break;
default:
break;
}
}
}
- (void)completeTransaction:(SKPaymentTransaction *)transaction {
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
- 交易完成, 验证购买,避免越狱软件模拟苹果请求达到非法购买问题. 从沙盒中获取交易凭证并且拼接请求体的数据上传 AppStore, 实际开发中我们可以上传到后台, 然后后台去做验证操作. 后台验证购买是否成功, 时候改变了充值的状态.
-(void)verifyPurchaseWithPaymentTransaction{
//从沙盒中获取交易凭证并且拼接成请求体数据
NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];
//转化为base64字符串
NSString *receiptString=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
NSMutableDictionary *params = [NSMutableDictionary new];
params[@"receiptData"] = receiptString;
params[@"amount"] = _rechargeAmount;
/**
这个地方可以通过调取后台接口, 让后台进行验证, 然后移动端返回购买结果的信息 (因为涉及到ipa破解软件,存在假购买情况,需要后台进行订单验证)
*/
//拼接请求数据
NSString *bodyString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", receiptString];
NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
//创建请求到苹果官方进行购买验证
NSURL *url=[NSURL URLWithString:SANDBOX];
NSMutableURLRequest *requestM=[NSMutableURLRequest requestWithURL:url];
requestM.HTTPBody=bodyData;
requestM.HTTPMethod=@"POST";
//创建连接并发送同步请求
NSError *error=nil;
NSData *responseData=[NSURLConnection sendSynchronousRequest:requestM returningResponse :nil error:&error];
if (error) {
NSLog(@"验证购买过程中发生错误,错误信息:%@",error.localizedDescription);
return;
}
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];
if([dic[@"status"] intValue]==0){
NSLog(@"购买成功!");
NSDictionary *dicReceipt= dic[@"receipt"];
NSDictionary *dicInApp=[dicReceipt[@"in_app"] firstObject];
NSString *productIdentifier= dicInApp[@"product_id"];//读取产品标识
//如果是消耗品则记录购买数量,非消耗品则记录是否购买过
//在此处对购买记录进行存储,可以存储到开发商的服务器端
}else{
NSLog(@"购买失败,未通过验证!");
}
}