1.導(dǎo)入頭文件<StoreKit/StoreKit.h>
#import <StoreKit/StoreKit.h>
2.將所有內(nèi)購(gòu)產(chǎn)品的ID放進(jìn)一個(gè)數(shù)組productArr
#define Product1 @"product1" //產(chǎn)品ID
#define Product2 @"product2"
#define Product3 @"product3"
#define Product4 @"product4"
#define Product5 @"product5"
#define Product6 @"product6"
3.加入?yún)f(xié)議
@interface ViewController ()
<
SKPaymentTransactionObserver,
SKProductsRequestDelegate
>
@property (nonatomic, assign) NSInteger selectedProduct;//選擇購(gòu)買(mǎi)的產(chǎn)品在數(shù)組中的序號(hào)
@end
@implementation ViewController{
NSArray *productArr; //存放產(chǎn)品ID
}
4.添加一個(gè)購(gòu)買(mǎi)按鈕
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[ button setTitle: @"點(diǎn)擊購(gòu)買(mǎi)"forState:UIControlStateNormal];
[button addTarget:self action:@selector(startPayClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
//添加一個(gè)交易隊(duì)列觀察者
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
productArr = @[Product1,Product2,Product3,Product4,Product5,Product6];
}
pragma mark - Event response 購(gòu)買(mǎi)按鈕點(diǎn)擊事件
-(void)startPayClick:(UIButton *)button{
self.selectedProduct = 1;//購(gòu)買(mǎi)第一個(gè)產(chǎn)品
//判斷是否可進(jìn)行支付
if ([SKPaymentQueue canMakePayments]) {
NSLog(@"----------允許程序內(nèi)付費(fèi)--------");
[self requestProductData:productArr[self.selectedProduct]];
} else {
NSLog(@"不允許程序內(nèi)付費(fèi)");
}
}
pragma mark ---內(nèi)購(gòu)測(cè)試
- (void)requestProductData:(NSString *)type {
//根據(jù)商品ID查找商品信息
NSArray *product = [[NSArray alloc] initWithObjects:type, nil];
NSSet *nsset = [NSSet setWithArray:product];
//創(chuàng)建SKProductsRequest對(duì)象,用想要出售的商品的標(biāo)識(shí)來(lái)初始化瓶竭, 然后附加上對(duì)應(yīng)的委托對(duì)象卷雕。
//該請(qǐng)求的響應(yīng)包含了可用商品的本地化信息幸逆。
SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
request.delegate = self;
[request start];
}
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
NSLog(@"-----------收到產(chǎn)品反饋信息--------------");
NSArray *product = response.products;
NSLog(@"產(chǎn)品Product ID:%@",response.invalidProductIdentifiers);
NSLog(@"產(chǎn)品付費(fèi)數(shù)量: %ld", [product count]);
if ([product count] == 0) {
return;
}
// SKProduct對(duì)象包含了在App Store上注冊(cè)的商品的本地化信息却嗡。
SKProduct *storeProduct = nil;
for (SKProduct *pro in product) {
NSLog(@"product info");
NSLog(@"SKProduct 描述信息%@", [pro description]);
NSLog(@"產(chǎn)品標(biāo)題 %@" , pro.localizedTitle);
NSLog(@"產(chǎn)品描述信息: %@" , pro.localizedDescription);
NSLog(@"價(jià)格: %@" , pro.price);
NSLog(@"Product id: %@" , pro.productIdentifier);
if ([pro.productIdentifier isEqualToString:productArr[self.selectedProduct]]) {
storeProduct = pro;
}
}
SKPayment *payment = [SKPayment paymentWithProduct:storeProduct];
NSLog(@"--------發(fā)送購(gòu)買(mǎi)請(qǐng)求---------");
[[SKPaymentQueue defaultQueue ] addPayment:payment];
}
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
NSLog(@"請(qǐng)求商品失敗%@", error);
}
- (void)requestDidFinish:(SKRequest *)request {
NSLog(@"反饋信息結(jié)束調(diào)用 ");
}
-(void) paymentQueue:(SKPaymentQueue *) paymentQueue restoreCompletedTransactionsFailedWithError:(NSError *)error{
NSLog(@"-------paymentQueue----");
}
//監(jiān)聽(tīng)購(gòu)買(mǎi)結(jié)果
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transaction {
for (SKPaymentTransaction *tran in transaction) {
switch (tran.transactionState) {
case SKPaymentTransactionStatePurchased:
NSLog(@"-----交易完成 --------");
[self completeTransaction:tran];
[[SKPaymentQueue defaultQueue]finishTransaction:tran];
break;
case SKPaymentTransactionStatePurchasing:
NSLog(@"商品加入列表");
break;
case SKPaymentTransactionStateRestored:
[self restoreTransaction:tran];
NSLog(@"-----已經(jīng)購(gòu)買(mǎi)過(guò)該商品 --------");
[[SKPaymentQueue defaultQueue]finishTransaction:tran];
break;
case SKPaymentTransactionStateFailed:
NSLog(@"交易失敗");
[self failedTransaction:tran];
break;
default:
break;
}
}
}
//交易結(jié)束
- (void)completeTransaction:(SKPaymentTransaction *)transaction {
NSLog(@"交易結(jié)束!!!!!!!!!!!!!!!");
// appStoreReceiptURL iOS7.0增加的,購(gòu)買(mǎi)交易完成后翻诉,會(huì)將憑據(jù)存放在該地址
NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
// 獲取到購(gòu)買(mǎi)憑據(jù)
NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
NSString *encodeStr = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
//購(gòu)買(mǎi)完成向后臺(tái)發(fā)送receipt-data炮姨,后臺(tái)校驗(yàn)發(fā)送部分略
NSString *sendString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", encodeStr];
//??沙盒測(cè)試時(shí)用
NSString * str = [[NSString alloc]initWithData:transaction.transactionReceipt encoding:NSUTF8StringEncoding];
NSString *environment=[self environmentForReceipt:str];
NSURL *StoreURL=nil;
if ([environment isEqualToString:@"environment=Sandbox"]) {
StoreURL= [[NSURL alloc] initWithString: @"https://sandbox.itunes.apple.com/verifyReceipt"];
}
else{
StoreURL= [[NSURL alloc] initWithString: @"https://buy.itunes.apple.com/verifyReceipt"];
}
//或者不用判斷沙盒環(huán)境,直接用NSURL *StoreURL= [[NSURL alloc] initWithString: @"https://sandbox.itunes.apple.com/verifyReceipt"];
/*??提交審核時(shí)用碰煌,將沙盒測(cè)試部分(171-183行)去掉舒岸,不然審核通過(guò)后內(nèi)購(gòu)有問(wèn)題
NSURL *StoreURL= [[NSURL alloc] initWithString: @"https://buy.itunes.apple.com/verifyReceipt"];
*/
//這個(gè)二進(jìn)制數(shù)據(jù)由服務(wù)器進(jìn)行驗(yàn)證;zl
NSData *postData = [NSData dataWithBytes:[sendString UTF8String] length:[sendString length]];
NSMutableURLRequest *connectionRequest = [NSMutableURLRequest requestWithURL:StoreURL];
[connectionRequest setHTTPMethod:@"POST"];
[connectionRequest setTimeoutInterval:50.0];//120.0---50.0zl
[connectionRequest setCachePolicy:NSURLRequestUseProtocolCachePolicy];
[connectionRequest setHTTPBody:postData];
NSString *product = transaction.payment.productIdentifier;
if ([product length] > 0) {
NSArray *tt = [product componentsSeparatedByString:@"."];
NSString *bookid = [tt lastObject];
if ([bookid length] > 0) {
[self recordTransaction:bookid];
[self provideContent:bookid];
}
}
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
//記錄交易
-(void)recordTransaction:(NSString *)product{
NSLog(@"-----記錄交易--------");
}
//處理下載內(nèi)容
-(void)provideContent:(NSString *)product{
NSLog(@"-----下載--------");
}
- (void) failedTransaction: (SKPaymentTransaction *)transaction{
NSLog(@"失敗");
//此處最好提示用戶芦圾,讓用戶重新購(gòu)買(mǎi)或者……(UE)
if (transaction.error.code != SKErrorPaymentCancelled)
{
}
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
- (void)restoreTransaction:(SKPaymentTransaction *)transaction {
// 恢復(fù)已經(jīng)購(gòu)買(mǎi)的產(chǎn)品
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
//收據(jù)的環(huán)境判斷蛾派;
-(NSString * )environmentForReceipt:(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:@";"];
//存儲(chǔ)收據(jù)環(huán)境的變量
NSString * environment=arr[2];
return environment;
}
源代碼見(jiàn)https://github.com/hubangguo/applePay