KMInAppPurchaseManager.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. //
  2. // KMInAppPurchaseManager.swift
  3. // PDF Master
  4. //
  5. // Created by lizhe on 2023/6/8.
  6. //
  7. import Cocoa
  8. import StoreKit
  9. import AuthenticationServices
  10. import Security
  11. #if VERSION_FREE
  12. let PRODUCT_1 = "com.pdftechnologies.pdfreader.mac.yearly.001"
  13. let kPRODUCTS: Set<String> = [PRODUCT_1]
  14. let kSandboxServer = "https://sandbox.itunes.apple.com/verifyReceipt";
  15. let kItunesServer = "https://buy.itunes.apple.com/verifyReceipt";
  16. let kStoreLiteKitSecret = "321ee8da056a45e7b963eb519c25c4fc";
  17. //let kStoreKitSecret = "20f0129197a34439a2130358172984bb";
  18. #endif
  19. #if VERSION_DMG
  20. let PRODUCT_1 = "com.pdfreaderpro.free.member.all_access_pack_permanent_license.001"
  21. let PRODUCT_2 = "com.pdfreaderpro.member.pdf_to_office_pack_permanent_license.001"
  22. let kPRODUCTS: Set<String> = [PRODUCT_1, PRODUCT_2]
  23. let kSandboxServer = "https://sandbox.itunes.apple.com/verifyReceipt";
  24. let kItunesServer = "https://buy.itunes.apple.com/verifyReceipt";
  25. let kStoreLiteKitSecret = "905532d3f55449a9b7a96161e7a2d538";
  26. //let kStoreKitSecret = "20f0129197a34439a2130358172984bb";
  27. #endif
  28. let keychainAccessGroup = "your.keychain.access.group"
  29. let receiptDataLabel = "receiptData"
  30. enum KMInAppPurchaseState: String, CaseIterable {
  31. case success = "Purchase Successfully"//"购买成功"
  32. case failed = "Purchase Failed"//"购买失败"
  33. case cancel = "Cancel Purchase"//"取消购买"
  34. case verFailed = "Order Verification Failed"//"订单校验失败"
  35. case verSuccess = "Order Verification Successful"//"订单校验成功"
  36. case verServerFailed = "Server Order Verification Failed"//"服务器订单校验失败"
  37. case notArrow = "In-app Purchases not Allowed" //"不允许内购"
  38. case productFailed = "Failed to Access Product"//"获取产品失败"
  39. case productSuccess = "Access Product Successfully"//"获取产品成功"
  40. case productCorrespondenceFailed = "Product not Found"//"未找到对应产品"
  41. case restoreSuccess = "Restore Successfully"//"restore成功"
  42. case restoreFailed = "Restore Failed"//"restore失败"
  43. case restoreVerSuccess = "Restore 2-step Verification Successeful"//"restore二次验证成功"
  44. case restoreVerFailed = "Restore 2-step Verification Failed"//"restore二次验证失败"
  45. case noReceipt = "No Ticket Information"//"无票据信息"
  46. case orderFailed = "Order Creation Failed"//"订单创建失败"
  47. case checkSubscriptionSuccess = "checkSubscriptionSuccess" //检测是否订阅成功
  48. case checkSubscriptionFailed = "checkSubscriptionFailed" //检测是否订阅失败
  49. }
  50. enum KMInAppPurchaseType: Int, CaseIterable {
  51. case unknow = 0
  52. case restore
  53. case purchase
  54. case check
  55. }
  56. class KMInAppPurchaseManager: NSObject {
  57. public static let manager = KMInAppPurchaseManager()
  58. var restoreCompletion: KMPurchaseRestoreCompletion?
  59. var checkSubscriptionStatusCompletion: KMPurchaseCheckSubscriptionStatusCompletion?
  60. var fetchProductCompletion: KMPurchaseFetchProductCompletion?
  61. var purchaseProductCompletion: KMPurchaseCompletion?
  62. var availableProducts: [SKProduct] = []
  63. var request: SKProductsRequest?
  64. var state: KMPurchaseManagerState {
  65. get {
  66. return self.updatePurchaseState()
  67. }
  68. }
  69. var type: KMInAppPurchaseType = .unknow
  70. var tempTransaction: SKPaymentTransaction?
  71. var isPurchaseed = false //是否购买过
  72. var orderId: String?
  73. deinit {
  74. SKPaymentQueue.default().remove(self)
  75. }
  76. override init() {
  77. super.init()
  78. // 注册购买交易观察者
  79. SKPaymentQueue.default().add(self)
  80. }
  81. func updatePurchaseState() -> KMPurchaseManagerState {
  82. let receipt: [String: Any] = UserDefaults.standard.object(forKey: "kInAppPurchaseReceipt") as? [String : Any] ?? [:]
  83. return self.verifyPurchase(purchase: receipt)
  84. }
  85. func fetchProducts(completion: @escaping KMPurchaseFetchProductCompletion) {
  86. self.fetchProductCompletion = completion
  87. let productIdentifiers: Set<String> = kPRODUCTS
  88. self.request = SKProductsRequest(productIdentifiers: productIdentifiers)
  89. self.request?.delegate = self
  90. self.request?.start()
  91. }
  92. func purchaseProduct(productIdentifier: String, orderId: String = "", completion: @escaping KMPurchaseCompletion) {
  93. self.type = .purchase
  94. self.purchaseProductCompletion = completion
  95. self.orderId = orderId
  96. if SKPaymentQueue.canMakePayments() {
  97. if let product = availableProducts.first(where: { $0.productIdentifier == productIdentifier }) {
  98. KMPrint("\("购买产品") + \(productIdentifier)")
  99. let uuid: String = GetHardwareUUID() ?? ""
  100. let payment = SKMutablePayment(product: product)
  101. payment.applicationUsername = uuid
  102. SKPaymentQueue.default().add(payment)
  103. } else {
  104. // 未找到匹配的产品
  105. if availableProducts.isEmpty {
  106. let tempProductIdentifier = productIdentifier
  107. self.fetchProducts(completion: { [unowned self] isSuccess, products, error in
  108. if isSuccess {
  109. self.purchaseProduct(productIdentifier: tempProductIdentifier, orderId: orderId, completion: completion)
  110. } else {
  111. self.handleAction(state: .productFailed)
  112. }
  113. })
  114. } else {
  115. self.handleAction(state: .productCorrespondenceFailed)
  116. }
  117. }
  118. } else {
  119. self.handleAction(state: .notArrow)
  120. }
  121. }
  122. func restorePurchases(_ orderId: String = "", _ completetion: @escaping KMPurchaseRestoreCompletion) {
  123. KMPrint("开始restore")
  124. self.type = .restore
  125. restoreCompletion = completetion
  126. self.orderId = orderId
  127. SKPaymentQueue.default().restoreCompletedTransactions()
  128. }
  129. //MARK: 购买返回类型集中处理
  130. func handleAction(state: KMInAppPurchaseState) {
  131. #if DEBUG
  132. KMPrint(state.rawValue)
  133. #endif
  134. DispatchQueue.main.async { [unowned self] in
  135. if state == .verSuccess {
  136. purchaseProductCompletion?(true, state)
  137. purchaseProductCompletion = nil
  138. restoreCompletion?(true, state)
  139. restoreCompletion = nil
  140. } else if state == .restoreFailed ||
  141. state == .restoreVerFailed {
  142. restoreCompletion?(false, state)
  143. restoreCompletion = nil
  144. } else if state == .restoreVerSuccess ||
  145. state == .restoreSuccess {
  146. if state == .restoreVerSuccess {
  147. restoreCompletion?(true, state)
  148. } else {
  149. restoreCompletion?(false, state)
  150. }
  151. restoreCompletion = nil
  152. } else if state == .checkSubscriptionSuccess ||
  153. state == .checkSubscriptionFailed {
  154. if state == .checkSubscriptionSuccess {
  155. checkSubscriptionStatusCompletion?(true)
  156. } else {
  157. checkSubscriptionStatusCompletion?(false)
  158. }
  159. checkSubscriptionStatusCompletion = nil
  160. } else {
  161. purchaseProductCompletion?(false, state)
  162. fetchProductCompletion?(false, [], state)
  163. restoreCompletion?(false, state)
  164. checkSubscriptionStatusCompletion?(false)
  165. purchaseProductCompletion = nil
  166. restoreCompletion = nil
  167. fetchProductCompletion = nil
  168. checkSubscriptionStatusCompletion = nil
  169. }
  170. if state == .noReceipt || state == .restoreFailed || state == .restoreVerFailed {
  171. self.removeReceiptInfo()
  172. KMLightMemberManager.manager.reloadUserInfo()
  173. }
  174. if state == .verFailed ||
  175. state == .verSuccess ||
  176. state == .restoreVerFailed ||
  177. state == .restoreVerSuccess {
  178. //刷新用户信息
  179. KMLightMemberManager.manager.reloadUserInfo()
  180. }
  181. self.type = .unknow
  182. }
  183. }
  184. //判断是否订阅过
  185. func checkSubscriptionStatus(_ completion: @escaping KMPurchaseCheckSubscriptionStatusCompletion) {
  186. self.type = .check
  187. // self.checkSubscriptionStatusCompletion = completion
  188. completion(isPurchaseed || self.isInAppPurchaseReceiptPurchased())
  189. // SKPaymentQueue.default().restoreCompletedTransactions()
  190. }
  191. }
  192. extension KMInAppPurchaseManager: SKProductsRequestDelegate {
  193. func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
  194. availableProducts = response.products
  195. KMPrint(availableProducts)
  196. #if DEBUG
  197. KMPrint(response.invalidProductIdentifiers)
  198. KMPrint("产品付费数量")
  199. KMPrint(response.products.count)
  200. for p in response.products {
  201. KMPrint(p.description)
  202. KMPrint(p.localizedTitle)
  203. KMPrint(p.localizedDescription)
  204. KMPrint(p.price);
  205. KMPrint(p.productIdentifier)
  206. }
  207. #endif
  208. self.request?.cancel()
  209. self.request = nil
  210. // 处理产品信息
  211. guard let callBack = self.fetchProductCompletion else { return }
  212. DispatchQueue.main.async { [unowned self] in
  213. callBack(true, availableProducts, .productSuccess)
  214. fetchProductCompletion = nil
  215. }
  216. }
  217. func request(_ request: SKRequest, didFailWithError error: Error) {
  218. // 处理请求错误
  219. KMPrint("\("用户无法进行内购") + \(error)")
  220. self.handleAction(state: .notArrow)
  221. }
  222. }
  223. extension KMInAppPurchaseManager: SKPaymentTransactionObserver {
  224. func paymentQueueDidChangeStorefront(_ queue: SKPaymentQueue) {
  225. // 用户更改了 storefront
  226. // 在这里可以执行相关的操作,例如更新价格信息或用户订阅选项
  227. // 你可以根据新的 storefront 来调整你的 App 内购买或订阅流程
  228. KMPrint("paymentQueueDidChangeStorefront")
  229. }
  230. // Sent when entitlements for a user have changed and access to the specified IAPs has been revoked.
  231. func paymentQueue(_ queue: SKPaymentQueue, didRevokeEntitlementsForProductIdentifiers productIdentifiers: [String]) {
  232. KMPrint("didRevokeEntitlementsForProductIdentifiers")
  233. }
  234. func paymentQueue(_ queue: SKPaymentQueue, shouldAddStorePayment payment: SKPayment, for product: SKProduct) -> Bool {
  235. // Handle the purchase intent here
  236. // Return true to allow the purchase or false to deny it
  237. return true
  238. }
  239. func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
  240. KMPrint("苹果服务器返回数据")
  241. if transactions.count > 0 {
  242. var restored = false
  243. var purchased = false
  244. var failed = false
  245. for transaction in transactions {
  246. debugPrint(transaction.original?.payment.productIdentifier)
  247. if transaction.original?.payment.productIdentifier != nil {
  248. SKPaymentQueue.default().finishTransaction(transaction)
  249. }
  250. if kPRODUCTS.contains(transaction.payment.productIdentifier) {
  251. // 检查购买的产品是否是订阅产品
  252. switch transaction.transactionState {
  253. case .purchased:
  254. debugPrint("purchased")
  255. purchased = true
  256. SKPaymentQueue.default().finishTransaction(transaction)
  257. break
  258. case .failed:
  259. debugPrint("failed")
  260. failed = true
  261. break
  262. case .restored:
  263. debugPrint("restored")
  264. restored = true
  265. isPurchaseed = true
  266. SKPaymentQueue.default().finishTransaction(transaction)
  267. break
  268. case .purchasing:
  269. debugPrint("purchasing")
  270. tempTransaction = transaction
  271. break
  272. default:
  273. debugPrint("default")
  274. break
  275. }
  276. } else {
  277. debugPrint("其他状态")
  278. }
  279. }
  280. if purchased {
  281. debugPrint("恢复购买,进行本地二次验证")
  282. validatePurchase(transaction: nil)
  283. } else if restored {
  284. if self.type == .restore {
  285. KMPrint("购买成功,进行本地二次验证")
  286. validatePurchase(transaction: nil)
  287. } else if self.type == .check {
  288. KMPrint("恢复购买 checkSubscriptionStatusCompletion")
  289. handleAction(state: .checkSubscriptionSuccess)
  290. } else if self.type == .purchase {
  291. validatePurchase(transaction: nil)
  292. }
  293. } else if failed {
  294. debugPrint("回调失败")
  295. if self.type == .check {
  296. handleAction(state: .checkSubscriptionFailed)
  297. } else if self.type == .restore {
  298. handleAction(state: .restoreFailed)
  299. } else if self.type == .purchase {
  300. handleAction(state: .productFailed)
  301. }
  302. } else {
  303. debugPrint("其他原因")
  304. }
  305. } else {
  306. self.handleAction(state: .productCorrespondenceFailed)
  307. }
  308. for transaction in queue.transactions {
  309. if transaction.transactionState != .purchasing {
  310. SKPaymentQueue.default().finishTransaction(transaction)
  311. }
  312. }
  313. }
  314. func validatePurchase(_ isTestServer: Bool = true, isDebug: Bool = false, transaction: SKPaymentTransaction?) {
  315. // 获取购买凭证
  316. if let receiptURL = Bundle.main.appStoreReceiptURL,
  317. let receiptData = try? Data(contentsOf: receiptURL) {
  318. // 将购买凭证发送到服务器进行验证
  319. // sendReceiptToServer(receiptData: receiptData, transaction: transaction)
  320. sendReceiptToAppleServer(isTestServer, isDebug: isDebug, receiptData: receiptData, transaction: transaction)
  321. } else {
  322. self.handleAction(state: .noReceipt)
  323. }
  324. }
  325. func appStoreEquityVerification(receiptData: Data, type: KMInAppPurchaseType) {
  326. // 构建请求
  327. let receiptString = receiptData.base64EncodedString(options: [])
  328. KMPrint(receiptString)
  329. if type == .purchase {
  330. KMRequestServerManager.manager.appStoreBuyComplete(applePayProductId: PRODUCT_1, receipt: receiptString, complete: { [unowned self] success, result in
  331. if success, let data = result?.result {
  332. } else if result?.error != nil {
  333. }
  334. })
  335. } else {
  336. KMRequestServerManager.manager.appStoreEquityVerification(applePayProductId: PRODUCT_1, receipt: receiptString, complete: { [unowned self] success, result in
  337. if success, let data = result?.result {
  338. } else if result?.error != nil {
  339. }
  340. })
  341. }
  342. }
  343. /**
  344. 1.根据字段 environment = sandbox。
  345. 2.根据验证接口返回的状态码,如果status=21007,则表示当前为沙盒环境。
  346. 苹果反馈的状态码:
  347. 21000App Store无法读取你提供的JSON数据
  348. 21002 订单数据不符合格式
  349. 21003 订单无法被验证
  350. 21004 你提供的共享密钥和账户的共享密钥不一致
  351. 21005 订单服务器当前不可用
  352. 21006 订单是有效的,但订阅服务已经过期。当收到这个信息时,解码后的收据信息也包含在返回内容中
  353. 21007 订单信息是测试用(sandbox),但却被发送到产品环境中验证
  354. 21008 订单信息是产品环境中使用,但却被发送到测试环境中验证
  355. */
  356. func sendReceiptToServer(receiptData: Data, transaction: SKPaymentTransaction?) {
  357. // 构建请求
  358. let receiptString = receiptData.base64EncodedString(options: [])
  359. let tempOrderId = self.orderId ?? ""
  360. KMPrint(receiptString)
  361. // if transaction.transactionState == .restored {
  362. if let restore = restoreCompletion {
  363. KMRequestServerManager.manager.parseVerification(applePayProductId: PRODUCT_1, orderId: tempOrderId, receipt: receiptString, restore: 1) { [unowned self] success, result in
  364. if success, let data = result?.result {
  365. // 处理服务器返回的验证结果
  366. //解析数据
  367. KMLightMemberUserInfo.parseData(data: data) { tData in
  368. KMLightMemberManager.manager.reloadUserInfo()
  369. self.handleAction(state: .restoreVerSuccess)
  370. }
  371. } else if result?.error != nil {
  372. // 处理网络请求错误
  373. // ...
  374. self.handleAction(state: .restoreVerFailed)
  375. }
  376. }
  377. } else if let purchase = purchaseProductCompletion {
  378. KMRequestServerManager.manager.parseVerification(applePayProductId: PRODUCT_1, orderId: tempOrderId, receipt: receiptString) { [unowned self] success, result in
  379. if success, let data = result?.result {
  380. // 处理服务器返回的验证结果
  381. //解析数据
  382. KMLightMemberUserInfo.parseData(data: data) { tData in
  383. KMLightMemberManager.manager.reloadUserInfo()
  384. self.handleAction(state: .verSuccess)
  385. }
  386. } else if result?.error != nil {
  387. // 处理网络请求错误
  388. // ...
  389. self.handleAction(state: .failed)
  390. }
  391. }
  392. }
  393. // SKPaymentQueue.default().finishTransaction(transaction)
  394. }
  395. func sendReceiptToAppleServer(_ isTestServer: Bool = false, isDebug: Bool = false, receiptData: Data, transaction: SKPaymentTransaction?) {
  396. // 构建请求
  397. // let url = URL(string: "https://your-server.com/verify-receipt")!
  398. // let requestContents = ["receipt-data" : receipt.base64EncodedString()]
  399. let receiptString = receiptData.base64EncodedString(options: [])
  400. let requestContents: [String: Any] = ["receipt-data": receiptString,
  401. "password": kStoreLiteKitSecret]
  402. guard let requestData = try? JSONSerialization.data(withJSONObject: requestContents, options: []) else {
  403. // 交易凭证为空验证失败
  404. self.handleAction(state: .failed)
  405. return
  406. }
  407. var url = URL(string: KMLightMemberManager.manager.config.kAppleServerURL)!
  408. if isDebug {
  409. if isTestServer {
  410. url = URL(string: "https://sandbox.itunes.apple.com/verifyReceipt")!
  411. } else {
  412. url = URL(string: "https://buy.itunes.apple.com/verifyReceipt")!
  413. }
  414. }
  415. print(url)
  416. var request = URLRequest(url: url)
  417. request.httpMethod = "POST"
  418. request.httpBody = requestData
  419. // 发送请求
  420. let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
  421. if let data = data {
  422. // 处理服务器返回的验证结果
  423. self.parseVerificationResult(data: data)
  424. } else if error != nil {
  425. // 处理网络请求错误
  426. // ...
  427. self.handleAction(state: .verFailed)
  428. }
  429. // SKPaymentQueue.default().finishTransaction(transaction)
  430. }
  431. task.resume()
  432. }
  433. func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
  434. KMPrint("paymentQueueRestoreCompletedTransactionsFinished")
  435. // 获取购买凭证
  436. if let receiptURL = Bundle.main.appStoreReceiptURL,
  437. let receiptData = try? Data(contentsOf: receiptURL) {
  438. if SKPaymentQueue.default().transactions.count > 0 {
  439. } else {
  440. self.handleAction(state: .noReceipt)
  441. }
  442. } else {
  443. self.handleAction(state: .noReceipt)
  444. }
  445. }
  446. func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
  447. KMPrint("restoreCompletedTransactionsFailedWithError")
  448. self.handleAction(state: .restoreFailed)
  449. self.handleAction(state: .checkSubscriptionFailed)
  450. }
  451. func parseVerificationResult(data: Data) {
  452. // 解析服务器返回的验证结果
  453. // 如果验证成功返回 true,否则返回 false
  454. // ...
  455. if tempTransaction != nil {
  456. SKPaymentQueue.default().finishTransaction(tempTransaction!)
  457. tempTransaction = nil
  458. }
  459. let receipt: [String: Any] = self.parseReceipt(receiptData: data) ?? [:]
  460. KMPrint(receipt)
  461. let status: Int = receipt["status"] as! Int
  462. if status == 21007 {
  463. // self.handleAction(state: .verFailed)
  464. self.validatePurchase(true, isDebug: true, transaction: nil)
  465. // [self verifyPurchaseWithPaymentTransaction:transaction isTestServer:YES];
  466. } else if status == 21008 {
  467. self.validatePurchase(false, isDebug: true, transaction: nil)
  468. } else if status == 0 {
  469. if let receiptURL = Bundle.main.appStoreReceiptURL,
  470. let receiptData = try? Data(contentsOf: receiptURL) {
  471. //给服务器发送票据验证
  472. appStoreEquityVerification(receiptData:receiptData, type: self.type)
  473. }
  474. let state = self.verifyPurchase(purchase: receipt)
  475. if state == .subscription {
  476. //保存票据信息
  477. self.saveReceiptInfo(receipt: receipt)
  478. self.handleAction(state: .verSuccess)
  479. } else {
  480. self.handleAction(state: .verFailed)
  481. }
  482. } else {
  483. self.handleAction(state: .verFailed)
  484. }
  485. }
  486. func handleError(transaction: SKPaymentTransaction?) {
  487. // 处理购买失败的逻辑
  488. if let t = transaction {
  489. SKPaymentQueue.default().finishTransaction(t)
  490. if t.transactionState == .restored {
  491. self.handleAction(state: .restoreFailed)
  492. } else {
  493. self.handleAction(state: .failed)
  494. }
  495. } else {
  496. self.handleAction(state: .failed)
  497. }
  498. }
  499. func verifyPurchase(purchase: [String: Any]) -> KMPurchaseManagerState {
  500. // 执行购买凭证验证的逻辑,例如验证产品标识符、购买日期等
  501. // 如果验证成功返回 true,否则返回 false
  502. // ...
  503. /**
  504. "expires_date" = "2023-06-27 09:28:20 Etc/GMT";
  505. "expires_date_ms" = 1687858100000;
  506. "expires_date_pst" = "2023-06-27 02:28:20 America/Los_Angeles";
  507. "in_app_ownership_type" = PURCHASED;
  508. "is_in_intro_offer_period" = false;
  509. "is_trial_period" = false;
  510. "original_purchase_date" = "2023-06-27 07:27:22 Etc/GMT";
  511. "original_purchase_date_ms" = 1687850842000;
  512. "original_purchase_date_pst" = "2023-06-27 00:27:22 America/Los_Angeles";
  513. "original_transaction_id" = 2000000357748210;
  514. "product_id" = "com.pdftechnologies.pdfreader.mac.yearly.001";
  515. "purchase_date" = "2023-06-27 08:28:20 Etc/GMT";
  516. "purchase_date_ms" = 1687854500000;
  517. "purchase_date_pst" = "2023-06-27 01:28:20 America/Los_Angeles";
  518. quantity = 1;
  519. "transaction_id" = 2000000357808638;
  520. "web_order_line_item_id" = 2000000030580071;
  521. */
  522. let receipt: [String: Any] = purchase["receipt"] as? [String : Any] ?? [:]
  523. let in_app: [NSDictionary] = receipt["in_app"] as? [NSDictionary] ?? []
  524. let request_date_ms: Int = Int(receipt["request_date_ms"] as? String ?? "0") ?? 0
  525. for item in in_app {
  526. let expires_date_ms: Int = Int(item["expires_date_ms"] as? String ?? "-1") ?? -1
  527. let product_id: String = item["product_id"] as? String ?? ""
  528. let now_date_ms: Int = Int(NSDate().timeIntervalSince1970) * 1000
  529. if product_id == PRODUCT_1 &&
  530. // expires_date_ms > request_date_ms &&
  531. expires_date_ms > now_date_ms {
  532. return .subscription
  533. }
  534. }
  535. return .unknow
  536. }
  537. func verifyApplePurchase(purchase: [String: Any]) -> KMPurchaseManagerState {
  538. // 执行购买凭证验证的逻辑,例如验证产品标识符、购买日期等
  539. // 如果验证成功返回 true,否则返回 false
  540. // ...
  541. /**
  542. "expires_date" = "2023-06-27 09:28:20 Etc/GMT";
  543. "expires_date_ms" = 1687858100000;
  544. "expires_date_pst" = "2023-06-27 02:28:20 America/Los_Angeles";
  545. "in_app_ownership_type" = PURCHASED;
  546. "is_in_intro_offer_period" = false;
  547. "is_trial_period" = false;
  548. "original_purchase_date" = "2023-06-27 07:27:22 Etc/GMT";
  549. "original_purchase_date_ms" = 1687850842000;
  550. "original_purchase_date_pst" = "2023-06-27 00:27:22 America/Los_Angeles";
  551. "original_transaction_id" = 2000000357748210;
  552. "product_id" = "com.pdftechnologies.pdfreader.mac.yearly.001";
  553. "purchase_date" = "2023-06-27 08:28:20 Etc/GMT";
  554. "purchase_date_ms" = 1687854500000;
  555. "purchase_date_pst" = "2023-06-27 01:28:20 America/Los_Angeles";
  556. quantity = 1;
  557. "transaction_id" = 2000000357808638;
  558. "web_order_line_item_id" = 2000000030580071;
  559. */
  560. let receipt: [String: Any] = purchase["receipt"] as? [String : Any] ?? [:]
  561. let in_app: [NSDictionary] = receipt["in_app"] as? [NSDictionary] ?? []
  562. let request_date_ms: Int = Int(receipt["request_date_ms"] as? String ?? "0") ?? 0
  563. for item in in_app {
  564. let expires_date_ms: Int = Int(item["expires_date_ms"] as? String ?? "-1") ?? -1
  565. let product_id: String = item["product_id"] as? String ?? ""
  566. let now_date_ms: Int = Int(NSDate().timeIntervalSince1970) * 1000
  567. if product_id == PRODUCT_1 &&
  568. // expires_date_ms > request_date_ms &&
  569. expires_date_ms > now_date_ms {
  570. return .subscription
  571. }
  572. }
  573. return .unknow
  574. }
  575. func parseReceipt(receiptData: Data) -> [String: Any]? {
  576. guard let receipt = try? JSONSerialization.jsonObject(with: receiptData, options: []) as? [String: Any] else {
  577. return nil
  578. }
  579. return receipt
  580. }
  581. }
  582. extension KMInAppPurchaseManager {
  583. func saveReceiptInfo(receipt: [String: Any]) {
  584. //保存票据信息
  585. UserDefaults.standard.set(receipt, forKey: "kInAppPurchaseReceipt")
  586. UserDefaults.standard.synchronize()
  587. //保存是否购买过本产品
  588. UserDefaults.standard.set("1", forKey: "kInAppPurchaseReceiptPurchased")
  589. UserDefaults.standard.synchronize()
  590. }
  591. func removeReceiptInfo() {
  592. //保存票据信息
  593. UserDefaults.standard.set([], forKey: "kInAppPurchaseReceipt")
  594. UserDefaults.standard.synchronize()
  595. }
  596. func isInAppPurchaseReceiptPurchased() -> Bool{
  597. let temp: String = UserDefaults.standard.object(forKey: "kInAppPurchaseReceiptPurchased") as? String ?? ""
  598. if temp == "1" {
  599. return true
  600. } else {
  601. return false
  602. }
  603. }
  604. }