内购
#import"ViewController.h"
#import
@interfaceViewController ()
@property(nonatomic,strong) NSArray *profuctIdArr;
@property(nonatomic,copy) NSString *currentProId;
@end
@implementationViewController
- (void)viewDidLoad {
[superviewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(100,100,100,100)];
btn.backgroundColor = [UIColor redColor];
[btn addTarget:selfaction:@selector(ClickOn:) forControlEvents:UIControlEventTouchUpInside];
[btn setTitle:@"6元"forState:UIControlStateNormal];
btn.tag =100;
[self.view addSubview:btn];
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}
- (void) ClickOn:(UIButton *)sender{
NSString *product =self.profuctIdArr[sender.tag-100];
_currentProId = product;
if([SKPaymentQueue canMakePayments]) {
NSLog(@"yes");
[selfgetRequestAppleProduct];
}else{
NSLog(@"no");
}
}
- (void)getRequestAppleProduct{
NSArray *product = [[NSArray alloc] initWithObjects:@"123456",@"com.CYTestAppStore123",nil];
NSSet * nsset = [NSSet setWithArray:product];
SKProductsRequest * request = [[SKProductsRequest alloc]initWithProductIdentifiers:nsset];
request.delegate =self;
[request start];
}
#pragma SKProductsRequestDelegate
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
NSArray * product = response.products;
NSLog(@"%@",response.invalidProductIdentifiers);
if(product.count ==0) {
NSLog(@"nothing");
return;
}
SKProduct *requestProduct =nil;
for(SKProduct * proinproduct) {
NSLog(@"%@",[pro description]);
NSLog(@"%@",[pro localizedTitle]);
NSLog(@"%@",[pro localizedDescription]);
NSLog(@"%@",[pro price]);
NSLog(@"%@",[pro productIdentifier]);
if([pro.productIdentifier isEqualToString:@"123456"]) {
requestProduct = pro;
}
}
SKPayment * payment = [SKPayment paymentWithProduct:requestProduct];
[[SKPaymentQueue defaultQueue]addPayment:payment];
}
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
NSLog(@"error:%@",error);
}
- (void)requestDidFinish:(SKRequest *)request{
NSLog(@"信息反馈结束");
}
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions{
for(SKPaymentTransaction * tranintransactions) {
switch(tran.transactionState) {
caseSKPaymentTransactionStatePurchased:
NSLog(@"交易完成");
[selfverifyPurchaseWithPaymentTransaction];
[[SKPaymentQueue defaultQueue] finishTransaction:tran];
break;
caseSKPaymentTransactionStatePurchasing:
NSLog(@"商品添加进列表");
break;
caseSKPaymentTransactionStateRestored:
NSLog(@"已经购买过商品");
break;
caseSKPaymentTransactionStateFailed:
NSLog(@"交易失败");
[[SKPaymentQueue defaultQueue] finishTransaction:tran];
break;
default:
break;
}
}
}
//沙盒测试环境验证
#define SANDBOX @"https://sandbox.itunes.apple.com/verifyReceipt"
//正式环境验证
#define AppStore @"https://buy.itunes.apple.com/verifyReceipt"
/**
*验证购买,避免越狱软件模拟苹果请求达到非法购买问题
*
*/
-(void)verifyPurchaseWithPaymentTransaction{
//从沙盒中获取交易凭证并且拼接成请求体数据
NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];
NSString *receiptString=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];//转化为base64字符串
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:nilerror:&error];
if(error) {
NSLog(@"验证购买过程中发生错误,错误信息:%@",error.localizedDescription);
return;
}
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",dic);
if([dic[@"status"] intValue]==0){
NSLog(@"购买成功!");
NSDictionary *dicReceipt= dic[@"receipt"];
NSDictionary *dicInApp=[dicReceipt[@"in_app"] firstObject];
NSString *productIdentifier= dicInApp[@"product_id"];//读取产品标识
//如果是消耗品则记录购买数量,非消耗品则记录是否购买过
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
if([productIdentifier isEqualToString:@"123"]) {
intpurchasedCount=[defaults integerForKey:productIdentifier];//已购买数量
[[NSUserDefaults standardUserDefaults] setInteger:(purchasedCount+1) forKey:productIdentifier];
}else{
[defaults setBool:YESforKey:productIdentifier];
}
//在此处对购买记录进行存储,可以存储到开发商的服务器端
}else{
NSLog(@"购买失败,未通过验证!");
}
}
//交易结束
- (void)completeTransaction:(SKPaymentTransaction *)transaction{
NSLog(@"交易结束");
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
- (NSString *)evironmentForReceipt:(NSString *)str{
str = [str stringByReplacingOccurrencesOfString:@"\r\n"withString:@""];
str = [str stringByReplacingOccurrencesOfString:@"\n"withString:@""];
str = [str stringByReplacingOccurrencesOfString:@"\t"withString:@""];
str = [str stringByReplacingOccurrencesOfString:@" "withString:@""];
str = [str stringByReplacingOccurrencesOfString:@"\""withString:@""];
NSArray * arr = [str componentsSeparatedByString:@";"];
NSString * environment = arr[2];
returnenvironment;
}
- (void)dealloc
{
[[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
网友评论