KDIAPManager.m 13 KB

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