什么是內購
首先得分清楚 內購和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.測試內購一定要用真機測試,商品信息如果無效,一般是 商品還沒有審核通過 ?!