KDIAPManager.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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 "XSNetwork.h"
  11. //#import <Adjust/Adjust.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. }
  144. #pragma mark -- SKPaymentTransactionObserver
  145. - (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
  146. // 获取结果
  147. // 验证成功与否都注销交易,否则会出现虚假凭证信息一直验证不通过,每次进程序都得输入苹果账号
  148. for (SKPaymentTransaction *trans in transactions) {
  149. switch (trans.transactionState) {
  150. case SKPaymentTransactionStatePurchasing:
  151. NSLog(@"商品添加进列表");
  152. break;
  153. case SKPaymentTransactionStatePurchased:
  154. {
  155. NSLog(@"交易完成");
  156. [self completeTransaction:trans];
  157. [[SKPaymentQueue defaultQueue] finishTransaction:trans];
  158. //1. adjust统计内购支付事件
  159. // NSString *kRechargeEventToken = [NSBundle mainBundle].infoDictionary[@"kRechargeEventToken"];
  160. // ADJEvent *event = [ADJEvent eventWithEventToken:kRechargeEventToken];
  161. // //[event setRevenue:1.0 currency:@"EUR"];
  162. // [event setTransactionId:trans.transactionIdentifier]; //避免重复
  163. // [Adjust trackEvent:event];
  164. }
  165. break;
  166. case SKPaymentTransactionStateFailed:
  167. NSLog(@"交易失败");
  168. [self failedTransaction:trans];
  169. [[SKPaymentQueue defaultQueue] finishTransaction:trans];
  170. break;
  171. case SKPaymentTransactionStateRestored:
  172. NSLog(@"已经购买过商品");
  173. [[SKPaymentQueue defaultQueue] finishTransaction:trans]; //消耗型商品不用写
  174. break;
  175. case SKPaymentTransactionStateDeferred:
  176. break;
  177. default:
  178. break;
  179. }
  180. }
  181. }
  182. /**
  183. 内购完成
  184. @param transaction 内购项目体
  185. */
  186. - (void)completeTransaction:(SKPaymentTransaction *)transaction {
  187. NSString *productIdentifier = transaction.payment.productIdentifier;
  188. NSURL *recepitURL = [[NSBundle mainBundle] appStoreReceiptURL];
  189. NSData *data = [NSData dataWithContentsOfURL:recepitURL];
  190. id receiptString = [data base64EncodedStringWithOptions:0];
  191. if ([productIdentifier length] > 0 && data) {
  192. if (receiptString && self.orderId.length > 0) {
  193. //1.保存订单号和报文到本地.
  194. [self saveReceiptData:@{@"receipt":receiptString,
  195. @"orderId":self.orderId ?:@""}];
  196. //2.向自己的服务器验证购买凭证.
  197. [self verifyPurchaseForServiceWithOrderId:self.orderId
  198. receipt:receiptString];
  199. }
  200. } else {
  201. [self handleActionWithType:IAPResultVerFailed data:nil];
  202. }
  203. // // 自己向苹果发送验证
  204. // [self verifyPurchaseWithPaymentTransaction:transaction isTestServer:NO];
  205. }
  206. ///服务器验证购买凭证.
  207. - (void)verifyPurchaseForServiceWithOrderId:(NSString *)orderId
  208. receipt:(id)receiptString {
  209. if (orderId == nil && !receiptString) {
  210. [self handleActionWithType:IAPResultIDError data:nil];
  211. return;
  212. }
  213. [XSNetwork payWithReceipt:receiptString orderId:orderId complete:^(id object, NSError *error) {
  214. //TTOO:网络异常,服务器校验receiptString失败,就会出现掉单问题.需要保存订单号到本地,下次启动app,继续校验服务器.
  215. if (error != nil) {
  216. //订单校验失败.
  217. [self handleActionWithType:IAPResultVerFailed data:nil];
  218. }else{
  219. //订单校验成功,删除本地保存的订单号和苹果返回的data凭证.
  220. [self handleActionWithType:IAPResultSuccess data:nil];
  221. [self removeLocReceiptData];
  222. }
  223. }];
  224. }
  225. /**
  226. 交易失败
  227. @param transaction 内购项目体
  228. */
  229. - (void)failedTransaction:(SKPaymentTransaction *)transaction {
  230. if (transaction.error.code != SKErrorPaymentCancelled) {
  231. [self handleActionWithType:IAPResultFailed data:nil];
  232. } else {
  233. [self handleActionWithType:IAPResultCancle data:nil];
  234. }
  235. }
  236. #pragma mark -- 本地保存一次支付凭证
  237. static NSString *const kSaveReceiptData = @"kSaveReceiptData";
  238. - (void)saveReceiptData:(NSDictionary *)receiptData {
  239. [[NSUserDefaults standardUserDefaults] setValue:receiptData forKey:kSaveReceiptData];
  240. [[NSUserDefaults standardUserDefaults]synchronize];
  241. }
  242. + (NSDictionary *)getReceiptData {
  243. return [[NSUserDefaults standardUserDefaults] valueForKey:kSaveReceiptData];
  244. }
  245. - (void)removeLocReceiptData {
  246. [[NSUserDefaults standardUserDefaults] removeObjectForKey:kSaveReceiptData];
  247. [[NSUserDefaults standardUserDefaults] synchronize];
  248. }
  249. /**
  250. - (void)verifyPurchaseWithPaymentTransaction:(SKPaymentTransaction *)transaction isTestServer:(BOOL)flag {
  251. //交易验证
  252. NSURL *recepitURL = [[NSBundle mainBundle] appStoreReceiptURL];
  253. NSData *receipt = [NSData dataWithContentsOfURL:recepitURL];
  254. NSError *error;
  255. NSDictionary *requestContents = @{@"receipt-data": [receipt base64EncodedStringWithOptions:0]};
  256. NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestContents options:0 error:&error];
  257. if (!requestData) { // 交易凭证为空验证失败
  258. [self handleActionWithType:IAPResultVerFailed data:nil];
  259. return;
  260. }
  261. //In the test environment, use https://sandbox.itunes.apple.com/verifyReceipt
  262. //In the real environment, use https://buy.itunes.apple.com/verifyReceipt
  263. NSString *serverString = @"https://buy.itunes.apple.com/verifyReceipt";
  264. if (flag) {
  265. serverString = @"https://sandbox.itunes.apple.com/verifyReceipt";
  266. }
  267. NSURL *storeURL = [NSURL URLWithString:serverString];
  268. NSMutableURLRequest *storeRequest = [NSMutableURLRequest requestWithURL:storeURL];
  269. [storeRequest setHTTPMethod:@"POST"];
  270. [storeRequest setHTTPBody:requestData];
  271. storeRequest.timeoutInterval = 20;
  272. [storeRequest addValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
  273. NSURLSession *session = [NSURLSession sharedSession];
  274. NSURLSessionDataTask *task = [session dataTaskWithRequest:storeRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  275. if (error) {
  276. // 无法连接服务器,购买校验失败
  277. [self handleActionWithType:IAPResultVerFailed data:nil];
  278. } else {
  279. NSError *error;
  280. NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  281. if (!jsonResponse) {
  282. // 苹果服务器校验数据返回为空校验失败
  283. [self handleActionWithType:IAPResultVerFailed data:nil];
  284. }
  285. // 先验证正式服务器,如果正式服务器返回21007再去苹果测试服务器验证,沙盒测试环境苹果用的是测试服务器
  286. NSString *status = [NSString stringWithFormat:@"%@",jsonResponse[@"status"]];
  287. if (status && [status isEqualToString:@"21007"]) {
  288. [self verifyPurchaseWithPaymentTransaction:transaction isTestServer:YES];
  289. } else if(status && [status isEqualToString:@"0"]){
  290. [self handleActionWithType:IAPResultVerSuccess data:nil];
  291. }
  292. }
  293. }];
  294. [task resume];
  295. }
  296. */
  297. //- (KDMainPresenter *)presenter {
  298. // if (!_presenter) {
  299. // self.presenter = [[KDMainPresenter alloc] init];
  300. // }
  301. // return _presenter;
  302. //}
  303. @end