什么是内购
首先得分清楚 内购和Apple Pay。
一、Apple Pay:是一种支付方式,跟支付宝、微信支付是类似的,这里就不详细介绍了。
二、内购:只要在iPhone App上购买的不是实物产品(也就是虚拟产品如qq币、鱼翅、电子书......) 都需要走内购流程,苹果这里面抽走30%。
内购流程
一、填写协议,税务和银行业务
1、登录https://appstoreconnect.apple.com,选择进入App Store Connect。
2、进入“协议、税务和银行业务”
3、内购用的是付费应用程序,先签署《付费应用程序协议》,同意后状态变更为“用户信息待处理”,等待审核。
4、状态更改完毕后,点击“开始设置税务、银行业务和联系信息”。
a.添加银行账户,按照要求填写相关内容即可。
b.选择报税表,并填写。(我是可爱的中国公民,在美国有没有商业活动,所以我填的是否。)
然后继续填写报税表,按照填写要求填写就行了(要是英文阅读有点困难,那就双击网页,应该会有翻译成中文的功能;没有的话,那就词典。。。你懂得,哈哈哈), 我是个人开发者账户相对公司开发者账户填的会少一点,不过没关系。都是一些基本信息。
c.填写联系信息,一共5个。高级管理、财务、技术、法务、营销(可重复,像我这种人才就是5个职位都是我,开玩笑的,勿当真)。
5、上面的税务表填完了之后,点击“我的APP”,进入到项目APP的信息页,点击功能,在弹出的页面点击App内购买项目后面的+。
这里我以消耗型为例
创建完成之后 填写内购买项目信息
信息填写完成了点击右上角的 “存储”,然后点击左边 “App 内购买项目”。出现“元数据丢失”说明里面信息没填写完整,在点进去填写。直到显示“准备提交”。
6、添加沙箱测试人员
7、我们需要在工程里配置好证书,测试证书是必须的因为我们内购需要连接到苹果的App Store的,需要正式的测试证书才能测试,同时把下图工程中的这一配置打开
二、代码部分
.h文件
#import
#define isServiceVerify 1//支付完成返回 校验方式
typedefenum: NSUInteger {
EPaymentTransactionStateNoPaymentPermission,//没有Payment权限
EPaymentTransactionStateAddPaymentFailed,//addPayment失败
EPaymentTransactionStatePurchasing,//正在购买
EPaymentTransactionStatePurchased,//购买完成(销毁交易)
EPaymentTransactionStateFailed,//购买失败(销毁交易)
EPaymentTransactionStateCancel,//用户取消
EPaymentTransactionStateRestored,//恢复购买(销毁交易)
EPaymentTransactionStateDeferred,//最终状态未确定
} EPaymentTransactionState;
#define _InAppPurchasing [EInAppPurchasing sharedInstance]
@class SKProduct;
@class SKPaymentTransaction;
@protocolEInAppPurchasingDelegate
@required
- (BOOL)isProductIdentifierAvailable:(NSString*)productIdentifier;
@optional
- (void)updatedTransactions:(EPaymentTransactionState)state;
//购买成功
- (void)buySuccess:(SKPaymentTransaction*)transaction;
//购买失败
- (void)buyFailed:(NSError*)errorInfo;
@end
@interfaceEInAppPurchasing :NSObject
+ (instancetype)sharedInstance;
@property (nonatomic, weak) id<EInAppPurchasingDelegate> delegate;
//调用这个方法传入商品id
- (void)identifyCanMakePayments:(NSArray*)requestArray;
@end
.m文件
#import "EInAppPurchasing.h"
#import <StoreKit/StoreKit.h>
#if TARGET_IPHONE_SIMULATOR
// 开发时模拟器使用的验证服务器地址
#define ITMS_VERIFY_RECEIPT_URL @""
#elif TARGET_OS_IPHONE
//真机验证的服务器地址
#define ITMS_VERIFY_RECEIPT_URL @""
#endif
@interface EInAppPurchasing ()<SKProductsRequestDelegate,SKPaymentTransactionObserver,VerifyOrderCallBackDelegate>
@property (nonatomic, strong) SKProductsRequest *request;
@end
@implementationEInAppPurchasing
+ (instancetype)sharedInstance
{
staticEInAppPurchasing* instance =NULL;
staticdispatch_once_tonceToken;
dispatch_once(&onceToken, ^{
instance = [EInAppPurchasingnew];
});
returninstance;
}
- (instancetype)init
{
self= [superinit];
if(self) {
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}
return self;
}
- (void)dealloc
{
[self releaseRequest];
[[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
- (void)releaseRequest
{
if(_request) {
[_requestcancel];
_request.delegate=nil;
_request=nil;
}
}
- (void)identifyCanMakePayments:(NSArray*)requestArray
{
if(requestArray.count==0) {
if(self.delegate&& [self.delegaterespondsToSelector:@selector(updatedTransactions:)]) {
[self.delegate updatedTransactions:EPaymentTransactionStateAddPaymentFailed];
}
return;
}
if ([SKPaymentQueue canMakePayments]) {
[self releaseRequest];
self.request = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithArray:requestArray]];
_request.delegate=self;
[_requeststart];
}
else
{
if(self.delegate&& [self.delegaterespondsToSelector:@selector(updatedTransactions:)]) {
[self.delegate updatedTransactions:EPaymentTransactionStateNoPaymentPermission];
}
}
}
#pragma mark - SKProductsRequestDelegate
- (void)productsRequest:(SKProductsRequest*)request didReceiveResponse:(SKProductsResponse*)response
{
NSLog(@"-----------收到产品反馈信息-------------- 产品ID:%@ 产品数量:%ld",response.invalidProductIdentifiers,response.products.count);
NSArray * myProducts = response.products;
for(SKProduct*productinmyProducts){
NSLog(@"SKProduct 描述信息%@", [productdescription]);
NSLog(@"产品标题 %@", product.localizedTitle);
NSLog(@"产品描述信息: %@" , product.localizedDescription);
NSLog(@"价格: %@", product.price);
NSLog(@"Product id: %@" , product.productIdentifier);
}
if(myProducts && myProducts.count>0) {
SKProduct*product = [myProductsobjectAtIndex:0];
if(self.delegate&& [self.delegaterespondsToSelector:@selector(isProductIdentifierAvailable:)]) {
if ([self.delegate isProductIdentifierAvailable:product.productIdentifier]) {
SKPayment*payment = [SKPaymentpaymentWithProduct:product];
[[SKPaymentQueue defaultQueue] addPayment:payment];
return;
}
}
}
if(self.delegate&& [self.delegaterespondsToSelector:@selector(updatedTransactions:)]) {
[self.delegate updatedTransactions:EPaymentTransactionStateAddPaymentFailed];
}
}
/** 请求失败 */
- (void)request:(SKRequest*)request didFailWithError:(NSError*)error{
NSLog(@"---购买失败");
}
#pragma mark - SKPaymentTransactionObserver
/** 监听购买结果 */
- (void)paymentQueue:(SKPaymentQueue*)queue updatedTransactions:(NSArray *)transactions
{
for(SKPaymentTransaction*transactionintransactions)
{
EPaymentTransactionState state;
switch(transaction.transactionState){
case SKPaymentTransactionStatePurchasing:
{
// 连接appStore
state =EPaymentTransactionStatePurchasing;
}
break;
case SKPaymentTransactionStatePurchased:
{
state =EPaymentTransactionStatePurchased;
//交易完成
if(isServiceVerify) {
[selfcompleteTransaction:transaction];
}
else
{
//本地作校验
[selfverifyPurchase:transaction];
}
}
break;
case SKPaymentTransactionStateFailed:
{
//交易失败
if(transaction.error.code!=SKErrorPaymentCancelled)
{
state =EPaymentTransactionStateFailed;
}else
{
state =EPaymentTransactionStateCancel;
}
[selffinshTransaction:transaction];
}
break;
case SKPaymentTransactionStateRestored:
{
state =EPaymentTransactionStateRestored;
//已经购买过该商品
[selffinshTransaction:transaction];
}
break;
case SKPaymentTransactionStateDeferred:
{
state =EPaymentTransactionStateDeferred;
}
break;
default:
break;
}
if(self.delegate&& [self.delegaterespondsToSelector:@selector(updatedTransactions:)]) {
[self.delegate updatedTransactions:state];
}
}
}
// Sent when transactions are removed from the queue (via finishTransaction:).
- (void)paymentQueue:(SKPaymentQueue*)queue removedTransactions:(NSArray *)transactions
{
NSLog(@"---removedTransactions");
}
// Sent when an error is encountered while adding transactions from the user's purchase history back to the queue.
- (void)paymentQueue:(SKPaymentQueue*)queue restoreCompletedTransactionsFailedWithError:(NSError*)error
{
NSLog(@"restoreCompletedTransactionsFailedWithError");
}
// Sent when all transactions from the user's purchase history have successfully been added back to the queue.
- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue*)queue
{
NSLog(@"paymentQueueRestoreCompletedTransactionsFinished");
}
// Sent when the download state has changed.
- (void)paymentQueue:(SKPaymentQueue*)queue updatedDownloads:(NSArray *)downloads
{
NSLog(@"updatedDownloads");
}
#pragma mark - Private
#pragma mark 验证购买
// 验证购买,在每一次购买完成之后,需要对购买的交易进行验证
// 所谓验证,是将交易的凭证进行"加密",POST请求传递给苹果的服务器,苹果服务器对"加密"数据进行验证之后,
// 会返回一个json数据,供开发者判断凭据是否有效
// 有些“内购助手”同样会拦截验证凭据,返回一个伪造的验证结果
// 所以在开发时,对凭据的检验要格外小心
- (void)verifyPurchase:(SKPaymentTransaction*)transaction
{
//ios7开始支持
NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
NSData*receiptData = [NSDatadataWithContentsOfURL:receiptURL];
NSString *encodeStr = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
NSURL *url = [NSURL URLWithString:ITMS_VERIFY_RECEIPT_URL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
NSString *payload = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", encodeStr];
NSData *payloadData = [payload dataUsingEncoding:NSUTF8StringEncoding];
[requestsetHTTPBody:payloadData];
[requestsetHTTPMethod:@"POST"];
NSURLResponse*response =nil;
// 此请求返回的是一个json结果 将数据反序列化为数据字典
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
if(data ==nil) {
return;
}
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
if(jsonResponse !=nil) {
if([[jsonResponseobjectForKey:@"status"]intValue] ==0)
{
//通常需要校验:bid,product_id,purchase_date,status
}
else
{
//验证失败,检查你的机器是否越狱
}
}
//结束交易
[selffinshTransaction:transaction];
}
- (void)completeTransaction:(SKPaymentTransaction*)transaction
{
//服务器校验
}
- (void)finshTransaction:(SKPaymentTransaction*)transaction
{
//结束交易
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
@end
三、注意事项
1.接入内购后把支付宝、微信支付的SDK删掉,苹果那边能扫出来(因为这个原因我被拒过)。
2.内购商品是和项目一起提交然后审核过了商品才有效!
3.测试内购一定要用真机测试,商品信息如果无效,一般是 商品还没有审核通过 !