KDIAPManager.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. //
  2. // KDIAPManager.m
  3. // KDChat
  4. //
  5. // Created by JYJ on 2019/6/14.
  6. // Copyright © 2019 dcjf. All rights reserved.
  7. //
  8. #import "KDIAPManager.h"
  9. #import <StoreKit/StoreKit.h>
  10. //#import "KDMainPresenter.h"
  11. #import "XSNetwork.h"
  12. @interface KDIAPManager() <SKPaymentTransactionObserver,SKProductsRequestDelegate> {
  13. IAPCompletionHandle _handle;
  14. }
  15. @property (nonatomic, strong) NSString* productId;
  16. @property (nonatomic, strong) NSString* orderId;
  17. /** presenter */
  18. //请求网络的.
  19. //@property (nonatomic, strong) KDMainPresenter *presenter;
  20. @end
  21. @implementation KDIAPManager
  22. /**
  23. 单例模式
  24. @return HZIAPManager
  25. */
  26. + (instancetype)shareIAPManager {
  27. static KDIAPManager *IAPManager = nil;
  28. static dispatch_once_t onceToken;
  29. dispatch_once(&onceToken, ^{
  30. IAPManager = [[KDIAPManager alloc] init];
  31. });
  32. return IAPManager;
  33. }
  34. - (instancetype)init {
  35. if (self = [super init]) {
  36. [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
  37. }
  38. return self;
  39. }
  40. - (void)dealloc {
  41. [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
  42. }
  43. #pragma mark -- Method
  44. /** 检测客户端与服务器漏单情况处理*/
  45. + (void)checkOrderStatus {
  46. NSDictionary *orderInfo = [KDIAPManager getReceiptData];
  47. if (orderInfo != nil) {
  48. NSString *orderId = orderInfo[@"orderId"];
  49. id receipt = orderInfo[@"receipt"];
  50. [[KDIAPManager shareIAPManager] verifyPurchaseForServiceWithOrderId:orderId receipt:receipt];
  51. }
  52. }
  53. #pragma mark -- 结束上次未完成的交易
  54. - (void)removeAllUncompleteTransactionsBeforeNewPurchase {
  55. NSArray* transactions = [SKPaymentQueue defaultQueue].transactions;
  56. if (transactions.count >= 1) {
  57. for (SKPaymentTransaction* transaction in transactions) {
  58. if (transaction.transactionState == SKPaymentTransactionStatePurchased ||
  59. transaction.transactionState == SKPaymentTransactionStateRestored) {
  60. [[SKPaymentQueue defaultQueue]finishTransaction:transaction];
  61. }
  62. }
  63. } else {
  64. NSLog(@"没有历史未消耗订单");
  65. }
  66. }
  67. - (void)startIAPWithOrderId:(NSString *)orderId productID:(NSString *)productID completeHandle: (IAPCompletionHandle)handle {
  68. _handle = handle;
  69. if(productID && productID.length > 0) {
  70. if ([SKPaymentQueue canMakePayments]) {
  71. [self removeAllUncompleteTransactionsBeforeNewPurchase];
  72. self.orderId = orderId;
  73. // 允许内购
  74. self.productId = productID;
  75. NSSet *set = [NSSet setWithObjects:productID, nil];
  76. SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:set];
  77. request.delegate = self;
  78. // 获取内购项目信息
  79. [request start];
  80. } else {
  81. // 不允许内购
  82. [self handleActionWithType:IAPResultNotArrow data:nil];
  83. }
  84. } else {
  85. NSLog(@"内购项目ID错误");
  86. [XSNetwork errorWithCode:-3 message:@"产品暂时不可用,请检查苹果后台"];
  87. [self handleActionWithType:IAPResultIDError data:nil];
  88. }
  89. }
  90. - (void)handleActionWithType:(IAPResultType)type data:(NSData *)data{
  91. switch (type) {
  92. case IAPResultSuccess:
  93. NSLog(@"购买成功");
  94. break;
  95. case IAPResultFailed:
  96. NSLog(@"购买失败");
  97. break;
  98. case IAPResultCancle:
  99. NSLog(@"用户取消购买");
  100. break;
  101. case IAPResultVerFailed:
  102. NSLog(@"订单校验失败");
  103. break;
  104. case IAPResultVerSuccess:
  105. NSLog(@"订单校验成功");
  106. break;
  107. case IAPResultNotArrow:
  108. NSLog(@"不允许程序内付费");
  109. break;
  110. default:
  111. break;
  112. }
  113. if(_handle){
  114. _handle(type, data);
  115. }
  116. }
  117. #pragma mark -- SKProductsRequestDelegate
  118. /**
  119. 收到产品信息的回调
  120. @param request 请求的信息
  121. @param response 返回的产品信息
  122. */
  123. - (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
  124. // 商品所在数组
  125. NSArray *productArr = response.products;
  126. if (productArr.count > 0) {
  127. // SKProduct *product = nil;
  128. for (SKProduct *product in productArr) {
  129. if ([product.productIdentifier isEqualToString:self.productId]) {
  130. // product = p;
  131. SKMutablePayment *payment = [SKMutablePayment paymentWithProduct:product];
  132. payment.quantity = 1;
  133. // payment.applicationUsername
  134. // payment.applicationUsername = _orderId;
  135. // 发起内购
  136. [[SKPaymentQueue defaultQueue] addPayment:payment];
  137. break;
  138. }
  139. }
  140. } else {
  141. [self handleActionWithType:IAPResultIDError data:nil];
  142. }
  143. // if ([response.invalidProductIdentifiers containsObject:self.productId]) {
  144. // self.callback(nil, [XSNetwork errorWithCode:-3 message:@"产品暂时不可用,请检查苹果后台"]);
  145. // return;
  146. // }
  147. //
  148. // for (SKProduct* product in response.products) {
  149. //
  150. // SKMutablePayment* payment = [SKMutablePayment paymentWithProduct:product];;
  151. // payment.applicationUsername = self.orderId;
  152. // [SKPaymentQueue.defaultQueue addPayment:payment];
  153. // }
  154. }
  155. #pragma mark -- SKPaymentTransactionObserver
  156. - (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
  157. // 获取结果
  158. // 验证成功与否都注销交易,否则会出现虚假凭证信息一直验证不通过,每次进程序都得输入苹果账号
  159. for (SKPaymentTransaction *trans in transactions) {
  160. switch (trans.transactionState) {
  161. case SKPaymentTransactionStatePurchasing:
  162. NSLog(@"商品添加进列表");
  163. break;
  164. case SKPaymentTransactionStatePurchased:
  165. NSLog(@"交易完成");
  166. [self completeTransaction:trans];
  167. [[SKPaymentQueue defaultQueue] finishTransaction:trans];
  168. break;
  169. case SKPaymentTransactionStateFailed:
  170. NSLog(@"交易失败");
  171. [self failedTransaction:trans];
  172. [[SKPaymentQueue defaultQueue] finishTransaction:trans];
  173. break;
  174. case SKPaymentTransactionStateRestored:
  175. NSLog(@"已经购买过商品");
  176. [[SKPaymentQueue defaultQueue] finishTransaction:trans]; //消耗型商品不用写
  177. break;
  178. case SKPaymentTransactionStateDeferred:
  179. break;
  180. default:
  181. break;
  182. }
  183. }
  184. }
  185. /**
  186. 内购完成
  187. @param transaction 内购项目体
  188. */
  189. - (void)completeTransaction:(SKPaymentTransaction *)transaction {
  190. NSString *productIdentifier = transaction.payment.productIdentifier;
  191. NSURL *recepitURL = [[NSBundle mainBundle] appStoreReceiptURL];
  192. NSData *data = [NSData dataWithContentsOfURL:recepitURL];
  193. id receiptString = [data base64EncodedStringWithOptions:0];
  194. if ([productIdentifier length] > 0 && data) {
  195. if (receiptString && self.orderId.length > 0) {
  196. //1.保存订单号和报文到本地.
  197. [self saveReceiptData:@{@"receipt":receiptString,
  198. @"orderId":self.orderId ?:@""}];
  199. //2.向自己的服务器验证购买凭证.
  200. [self verifyPurchaseForServiceWithOrderId:self.orderId
  201. receipt:receiptString];
  202. }
  203. } else {
  204. [self handleActionWithType:IAPResultVerFailed data:nil];
  205. }
  206. // // 自己向苹果发送验证
  207. // [self verifyPurchaseWithPaymentTransaction:transaction isTestServer:NO];
  208. }
  209. ///服务器验证购买凭证.
  210. - (void)verifyPurchaseForServiceWithOrderId:(NSString *)orderId
  211. receipt:(id)receiptString {
  212. if (orderId == nil && !receiptString) {
  213. [self handleActionWithType:IAPResultIDError data:nil];
  214. return;
  215. }
  216. [XSNetwork payWithReceipt:receiptString orderId:orderId complete:^(id object, NSError *error) {
  217. //TTOO:网络异常,服务器校验receiptString失败,就会出现掉单问题.需要保存订单号到本地,下次启动app,继续校验服务器.
  218. if (error != nil) {
  219. //订单校验失败.
  220. [self handleActionWithType:IAPResultVerFailed data:nil];
  221. }else{
  222. //订单校验成功,删除本地保存的订单号和苹果返回的data凭证.
  223. [self handleActionWithType:IAPResultSuccess data:nil];
  224. [self removeLocReceiptData];
  225. }
  226. }];
  227. }
  228. /**
  229. 交易失败
  230. @param transaction 内购项目体
  231. */
  232. - (void)failedTransaction:(SKPaymentTransaction *)transaction {
  233. if (transaction.error.code != SKErrorPaymentCancelled) {
  234. [self handleActionWithType:IAPResultFailed data:nil];
  235. } else {
  236. [self handleActionWithType:IAPResultCancle data:nil];
  237. }
  238. }
  239. #pragma mark -- 本地保存一次支付凭证
  240. static NSString *const kSaveReceiptData = @"kSaveReceiptData";
  241. - (void)saveReceiptData:(NSDictionary *)receiptData {
  242. [[NSUserDefaults standardUserDefaults] setValue:receiptData forKey:kSaveReceiptData];
  243. [[NSUserDefaults standardUserDefaults]synchronize];
  244. }
  245. + (NSDictionary *)getReceiptData {
  246. return [[NSUserDefaults standardUserDefaults] valueForKey:kSaveReceiptData];
  247. }
  248. - (void)removeLocReceiptData {
  249. [[NSUserDefaults standardUserDefaults] removeObjectForKey:kSaveReceiptData];
  250. [[NSUserDefaults standardUserDefaults] synchronize];
  251. }
  252. /**
  253. - (void)verifyPurchaseWithPaymentTransaction:(SKPaymentTransaction *)transaction isTestServer:(BOOL)flag {
  254. //交易验证
  255. NSURL *recepitURL = [[NSBundle mainBundle] appStoreReceiptURL];
  256. NSData *receipt = [NSData dataWithContentsOfURL:recepitURL];
  257. NSError *error;
  258. NSDictionary *requestContents = @{@"receipt-data": [receipt base64EncodedStringWithOptions:0]};
  259. NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestContents options:0 error:&error];
  260. if (!requestData) { // 交易凭证为空验证失败
  261. [self handleActionWithType:IAPResultVerFailed data:nil];
  262. return;
  263. }
  264. //In the test environment, use https://sandbox.itunes.apple.com/verifyReceipt
  265. //In the real environment, use https://buy.itunes.apple.com/verifyReceipt
  266. NSString *serverString = @"https://buy.itunes.apple.com/verifyReceipt";
  267. if (flag) {
  268. serverString = @"https://sandbox.itunes.apple.com/verifyReceipt";
  269. }
  270. NSURL *storeURL = [NSURL URLWithString:serverString];
  271. NSMutableURLRequest *storeRequest = [NSMutableURLRequest requestWithURL:storeURL];
  272. [storeRequest setHTTPMethod:@"POST"];
  273. [storeRequest setHTTPBody:requestData];
  274. storeRequest.timeoutInterval = 20;
  275. [storeRequest addValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
  276. NSURLSession *session = [NSURLSession sharedSession];
  277. NSURLSessionDataTask *task = [session dataTaskWithRequest:storeRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  278. if (error) {
  279. // 无法连接服务器,购买校验失败
  280. [self handleActionWithType:IAPResultVerFailed data:nil];
  281. } else {
  282. NSError *error;
  283. NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  284. if (!jsonResponse) {
  285. // 苹果服务器校验数据返回为空校验失败
  286. [self handleActionWithType:IAPResultVerFailed data:nil];
  287. }
  288. // 先验证正式服务器,如果正式服务器返回21007再去苹果测试服务器验证,沙盒测试环境苹果用的是测试服务器
  289. NSString *status = [NSString stringWithFormat:@"%@",jsonResponse[@"status"]];
  290. if (status && [status isEqualToString:@"21007"]) {
  291. [self verifyPurchaseWithPaymentTransaction:transaction isTestServer:YES];
  292. } else if(status && [status isEqualToString:@"0"]){
  293. [self handleActionWithType:IAPResultVerSuccess data:nil];
  294. }
  295. }
  296. }];
  297. [task resume];
  298. }
  299. */
  300. //- (KDMainPresenter *)presenter {
  301. // if (!_presenter) {
  302. // self.presenter = [[KDMainPresenter alloc] init];
  303. // }
  304. // return _presenter;
  305. //}
  306. @end