iOS 内购 大致步骤

原创
2018/09/20 09:42
阅读数 196
  1. 你的苹果开发者账号需要完善银行税务等资料。不完成后面有大坑!

完善开发者账号资料

  1. 需要创建内购项目

内购项目

  1. 核心代码(伪代码)

导入头文件

#import<StoreKit/StoreKit.h>

//开始充值请求 rechargeid是自己设置产品id

-(void)startRechargeWithRechargeId:(NSString *)rechargeId {
    SKProductsRequest *queryRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithArray:@[rechargeId]]];
    queryRequest.delegate = self;
    [queryRequest start];
	}```
//充值查询回调

```-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
	NSArray * recharges = response.products;
    	if(recharges.count == 0){
     	// 充值查询失败
        	return;
    	}
    SKProduct *sp = recharges[0];
    SKPayment *payment = [SKPayment paymentWithProduct:sp];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
	}
	#pragma mark - 充值查询请求不成功
	-(void)request:(SKRequest *)request didFailWithError:(NSError *)error {
    if(error) {
        NSLog(@"失败原因>>>%@",error);
        [self dismissHUD];
    }
	}
	//反馈信息
	- (void)requestDidFinish:(SKRequest *)request {
    NSLog(@"充值信息>>>%@",request);
	}

//完成交易事务

-(void)completeTransaction:(SKPaymentTransaction *)transaction {
    //验证购买凭证
    [self verifyPruchaseWithRechargeId:transaction.payment.productIdentifier];
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
	}
  1. 找后台验证凭据,凭据格式要和后台协商好(换个后台协商凭据格式就要搞一天)
-(void)verifyPruchaseWithRechargeId:(NSString *)rechargeId {
	if(!rechargeId || rechargeId.length == 0){
		//验证充值失败!(获取充值ID失败,请联系客服)
        	return;
    	}
    
    //获取验证凭据
    NSData *receiptData = [NSData dataWithContentsOfURL:[[NSBundle mainBundle] appStoreReceiptURL]];
    if(!receiptData || receiptData.length == 0){
         [self showImplyInfo:@"验证充值失败!(获取充值凭证失败,请联系客服)" isActive:NO];
        return;
    }

	// 下面凭证转化取一种就行,看后台习惯哪种
	// 凭证可以转为base64
        receiptHex  = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];


	//或者凭证转换为hex 
        receiptHex = [self hexFromData:receiptData];

	}

转化方法

-(NSString *)hexFromData:(NSData *)data {
    if(!data) return nil;
    NSMutableString *hex = [NSMutableString string];
    char *chars = (char *)data.bytes;
    for(NSUInteger i = 0; i < data.length; i++) {
        [hex appendFormat:@"%0.2hhx",chars[i]];
    }
    return hex;
	}
	
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部