苹果内购 (无力吐槽,暂时先这样),说说它里面的关键步骤.
- 添加收款
银行卡
和商品
:https://www.jianshu.com/p/1e6b1152afc6 - 创建沙盒 测试账号 : https://www.jianshu.com/p/143b410ff09a
- 代码部分
大致 方向是
product_id
=>Payment
=>唤起苹果支付
通过 主要是 `SKPaymentTransactionObserver`(观察支付状态) 和
`SKProductsRequestDelegate` (通过商品id去苹果服务器获取商品信息)
为了方便的开发 我自己封装了 ApplePay
#import "ApplePay.h"
//沙盒测试环境验证
#define ApplePayWithSandBoxUrl @"https://sandbox.itunes.apple.com/verifyReceipt"
//正式环境验证
#define ApplePayWithAppStoreUrl @"https://buy.itunes.apple.com/verifyReceipt"
@interface ZLApplePay () <SKPaymentTransactionObserver,SKProductsRequestDelegate>
@property (nonatomic,copy) NSString * currentProductId;
//@property (nonatomic,strong) NSDictionary * mapDic;//product_id -> 金额的映射
@property (nonatomic,weak) id <ZLApplePayDelegate> delegate;
@end
@implementation ZLApplePay
LEE_SINGLE_M //单例
- (void)dealloc {
[self removeObserver];
}
- (instancetype)init {
if (self = [super init]) {
[self addObserver];
}
return self;
}
- (void)addObserver {
[self removeObserver];
//添加一个交易队列观察者
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}
- (void)removeObserver {
//添加一个交易队列观察者
[[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
#pragma mark - private
/**
* 验证购买,避免越狱软件模拟苹果请求达到非法购买问题
暂时不做
*
*/
-(void)verifyPurchase {
//从沙盒中获取交易凭证并且拼接成请求体数据
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:ApplePayWithSandBoxUrl];
NSMutableURLRequest *requestM=[NSMutableURLRequest requestWithURL:url];
requestM.HTTPBody=bodyData;
requestM.HTTPMethod=@"POST";
NSURLSessionDataTask *task= [[NSURLSession sharedSession] dataTaskWithRequest:requestM completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"验证购买过程中发生错误,错误信息:%@",error.localizedDescription);
return;
}
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",dic);
if([dic[@"status"] intValue]==0){
NSLog(@"购买成功!");
}else{
NSLog(@"购买失败,未通过验证!");
}
}];
[task resume];
}
//完成购买
- (void)completeTransaction:(SKPaymentTransaction *)transaction {
[ZLToast dismiss];
if ([self.delegate respondsToSelector:@selector(zlApplePaySuccessWithProductId:completeTransaction:)]) {
[self.delegate zlApplePaySuccessWithProductId:self.currentProductId completeTransaction:transaction];
} else {
[self finishTransaction:transaction];
}
}
//购买失败
- (void)failedTransaction:(SKPaymentTransaction *)transaction {
[ZLToast dismiss];
if(transaction.error.code != SKErrorPaymentCancelled) {
NSString * msg = [NSString stringWithFormat:@"购买失败 :%@",transaction.error.localizedDescription];
[ZLToast showHint:msg];
} else {
NSString * msg = [NSString stringWithFormat:@"用户取消交易"];
[ZLToast showHint:msg];
}
[self finishTransaction:transaction];
}
// 恢复已经购买的产品
- (void)restoreTransaction:(SKPaymentTransaction *)transaction {
[ZLToast dismiss];
[self finishTransaction:transaction];
}
- (void)otherTransaction:(SKPaymentTransaction *)transaction {
[ZLToast dismiss];
[ZLToast showHint:@"支付挂起,请联系官方客服!"];
[self finishTransaction:transaction];
}
#pragma mark - SKPaymentTransactionObserver (观察者监听购买状态的变化)
- (void)paymentQueue:(SKPaymentQueue *)queue
updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
for (SKPaymentTransaction *tran in transactions) {
if (SKPaymentTransactionStatePurchasing == tran.transactionState) {
[ZLToast showWithStatus:@"正在进行内购中,请不要离开."];
} else if (SKPaymentTransactionStatePurchased == tran.transactionState) {
[self completeTransaction:tran];
} else if (SKPaymentTransactionStateRestored == tran.transactionState) {
[self restoreTransaction:tran];
} else if (SKPaymentTransactionStateFailed == tran.transactionState) {
[self failedTransaction:tran];
} else {
[self otherTransaction:tran];
}
}
}
#pragma mark - SKProductsRequestDelegate (请求的代理)
// Sent immediately before -requestDidFinish:
- (void)productsRequest:(SKProductsRequest *)request
didReceiveResponse:(SKProductsResponse *)response {
//接收商品信息
NSArray *product = response.products;
if ([product count] == 0) {
return;
}
// SKProduct对象包含了在App Store上注册的商品的本地化信息。
SKProduct *currentProduct = nil;
for (SKProduct *pro in product) {
if ([pro.productIdentifier isEqualToString:self.currentProductId]) {
currentProduct = pro;
}
}
if (!currentProduct) {
return;
}
//创建一个支付对象,并放到队列中
SKMutablePayment * payment = [SKMutablePayment paymentWithProduct:currentProduct];
// //设置购买的数量
// payment.quantity = 1;
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
NSString * errorMsg = [NSString stringWithFormat:@"支付请求错误:%@",error.localizedDescription];
[ZLToast showHint:errorMsg];
[ZLToast dismiss];
}
- (void)requestDidFinish:(SKRequest *)request {
NSLog(@"支付请求成功=>开始调取ApplePay");
}
#pragma mark - public
- (void)startPayWithProductId:(NSString *)productId
delegate:(id <ZLApplePayDelegate>)delegate {
//判断是否可进行支付
if ([SKPaymentQueue canMakePayments]) {
if (productId.length == 0) {
[ZLToast showHint:@"传入的productId 是空的"];
return;
}
self.currentProductId = productId;
self.delegate = delegate;
SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObjects:productId, nil]];
request.delegate = self;
[request start];
[ZLToast showWithStatus:@"正在发起支付"];
} else {
[ZLToast showHint:@"不允许程序内付费"];
}
}
- (void)finishTransaction:(SKPaymentTransaction *)transaction {
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
@end