KMInAppPurchaseManager.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. //
  2. // KMInAppPurchaseManager.swift
  3. // PDF Reader Pro
  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. #if VERSION_DMG
  13. let PRODUCT_1 = "com.pdfreaderpro.free.member.all_access_pack_permanent_license.001"
  14. let PRODUCT_2 = "com.pdfreaderpro.member.pdf_to_office_pack_permanent_license.001"
  15. let kPRODUCTS: Set<String> = [PRODUCT_1, PRODUCT_2]
  16. let kSandboxServer = "https://sandbox.itunes.apple.com/verifyReceipt";
  17. let kItunesServer = "https://buy.itunes.apple.com/verifyReceipt";
  18. let kStoreLiteKitSecret = "905532d3f55449a9b7a96161e7a2d538";
  19. //let kStoreKitSecret = "20f0129197a34439a2130358172984bb";
  20. #else
  21. let PRODUCT_1 = "com.pdftechnologies.pdfreader.mac.yearly.001"
  22. let kPRODUCTS: Set<String> = [PRODUCT_1]
  23. let kSandboxServer = "https://sandbox.itunes.apple.com/verifyReceipt";
  24. let kItunesServer = "https://buy.itunes.apple.com/verifyReceipt";
  25. let kStoreLiteKitSecret = "321ee8da056a45e7b963eb519c25c4fc";
  26. //let kStoreKitSecret = "20f0129197a34439a2130358172984bb";
  27. #endif
  28. #endif
  29. #if VERSION_PRO
  30. let PRODUCT_1 = "com.pdftechnologies.pdfreader.mac.yearly.001"
  31. let kPRODUCTS: Set<String> = [PRODUCT_1]
  32. let kSandboxServer = "https://sandbox.itunes.apple.com/verifyReceipt";
  33. let kItunesServer = "https://buy.itunes.apple.com/verifyReceipt";
  34. let kStoreLiteKitSecret = "321ee8da056a45e7b963eb519c25c4fc";
  35. //let kStoreKitSecret = "20f0129197a34439a2130358172984bb";
  36. #endif
  37. let keychainAccessGroup = "your.keychain.access.group"
  38. let receiptDataLabel = "receiptData"
  39. enum KMInAppPurchaseState: String, CaseIterable {
  40. case success = "Purchase Successfully"//"购买成功"
  41. case failed = "Purchase Failed"//"购买失败"
  42. case cancel = "Cancel Purchase"//"取消购买"
  43. case verFailed = "Order Verification Failed"//"订单校验失败"
  44. case verSuccess = "Order Verification Successful"//"订单校验成功"
  45. case verServerFailed = "Server Order Verification Failed"//"服务器订单校验失败"
  46. case notArrow = "In-app Purchases not Allowed" //"不允许内购"
  47. case productFailed = "Failed to Access Product"//"获取产品失败"
  48. case productSuccess = "Access Product Successfully"//"获取产品成功"
  49. case productCorrespondenceFailed = "Product not Found"//"未找到对应产品"
  50. case restoreSuccess = "Restore Successfully"//"restore成功"
  51. case restoreFailed = "Restore Failed"//"restore失败"
  52. case restoreVerSuccess = "Restore 2-step Verification Successeful"//"restore二次验证成功"
  53. case restoreVerFailed = "Restore 2-step Verification Failed"//"restore二次验证失败"
  54. case noReceipt = "No Ticket Information"//"无票据信息"
  55. case orderFailed = "Order Creation Failed"//"订单创建失败"
  56. case checkSubscriptionSuccess = "checkSubscriptionSuccess" //检测是否订阅成功
  57. case checkSubscriptionFailed = "checkSubscriptionFailed" //检测是否订阅失败
  58. }
  59. enum KMInAppPurchaseType: Int, CaseIterable {
  60. case unknow = 0
  61. case restore
  62. case purchase
  63. case check
  64. }
  65. class KMInAppPurchaseManager: NSObject {
  66. public static let manager = KMInAppPurchaseManager()
  67. var restoreCompletion: KMPurchaseRestoreCompletion?
  68. var checkSubscriptionStatusCompletion: KMPurchaseCheckSubscriptionStatusCompletion?
  69. var fetchProductCompletion: KMPurchaseFetchProductCompletion?
  70. var purchaseProductCompletion: KMPurchaseCompletion?
  71. var availableProducts: [SKProduct] = []
  72. var request: SKProductsRequest?
  73. var state: KMPurchaseManagerState {
  74. get {
  75. return self.updatePurchaseState()
  76. }
  77. }
  78. var type: KMInAppPurchaseType = .unknow
  79. var tempTransaction: SKPaymentTransaction?
  80. var isPurchaseed = false //是否购买过
  81. var orderId: String?
  82. deinit {
  83. }
  84. override init() {
  85. super.init()
  86. // 注册购买交易观察者
  87. }
  88. func updatePurchaseState() -> KMPurchaseManagerState {
  89. return .unknow
  90. }
  91. func fetchProducts(completion: @escaping KMPurchaseFetchProductCompletion) {
  92. self.fetchProductCompletion = completion
  93. let productIdentifiers: Set<String> = kPRODUCTS
  94. self.request = SKProductsRequest(productIdentifiers: productIdentifiers)
  95. self.request?.delegate = self
  96. self.request?.start()
  97. }
  98. func purchaseProduct(productIdentifier: String, orderId: String = "", completion: @escaping KMPurchaseCompletion) {
  99. self.type = .purchase
  100. self.purchaseProductCompletion = completion
  101. self.orderId = orderId
  102. if SKPaymentQueue.canMakePayments() {
  103. if let product = availableProducts.first(where: { $0.productIdentifier == productIdentifier }) {
  104. KMPrint("\("购买产品") + \(productIdentifier)")
  105. let uuid: String = GetHardwareUUID() ?? ""
  106. let payment = SKMutablePayment(product: product)
  107. payment.applicationUsername = uuid
  108. SKPaymentQueue.default().add(payment)
  109. } else {
  110. // 未找到匹配的产品
  111. if availableProducts.isEmpty {
  112. let tempProductIdentifier = productIdentifier
  113. self.fetchProducts(completion: { [weak self] isSuccess, products, error in
  114. if isSuccess {
  115. self?.purchaseProduct(productIdentifier: tempProductIdentifier, orderId: orderId, completion: completion)
  116. } else {
  117. self?.handleAction(state: .productFailed)
  118. }
  119. })
  120. } else {
  121. self.handleAction(state: .productCorrespondenceFailed)
  122. }
  123. }
  124. } else {
  125. self.handleAction(state: .notArrow)
  126. }
  127. }
  128. func restorePurchases(_ orderId: String = "", _ completetion: @escaping KMPurchaseRestoreCompletion) {
  129. KMPrint("开始restore")
  130. self.type = .restore
  131. restoreCompletion = completetion
  132. self.orderId = orderId
  133. SKPaymentQueue.default().restoreCompletedTransactions()
  134. }
  135. //MARK: 购买返回类型集中处理
  136. func handleAction(state: KMInAppPurchaseState) {
  137. #if DEBUG
  138. KMPrint(state.rawValue)
  139. #endif
  140. DispatchQueue.main.async { [unowned self] in
  141. if state == .verSuccess {
  142. purchaseProductCompletion?(true, state)
  143. purchaseProductCompletion = nil
  144. restoreCompletion?(true, state)
  145. restoreCompletion = nil
  146. } else if state == .restoreFailed ||
  147. state == .restoreVerFailed {
  148. restoreCompletion?(false, state)
  149. restoreCompletion = nil
  150. } else if state == .restoreVerSuccess ||
  151. state == .restoreSuccess {
  152. if state == .restoreVerSuccess {
  153. restoreCompletion?(true, state)
  154. } else {
  155. restoreCompletion?(false, state)
  156. }
  157. restoreCompletion = nil
  158. } else if state == .checkSubscriptionSuccess ||
  159. state == .checkSubscriptionFailed {
  160. if state == .checkSubscriptionSuccess {
  161. checkSubscriptionStatusCompletion?(true)
  162. } else {
  163. checkSubscriptionStatusCompletion?(false)
  164. }
  165. checkSubscriptionStatusCompletion = nil
  166. } else {
  167. purchaseProductCompletion?(false, state)
  168. fetchProductCompletion?(false, [], state)
  169. restoreCompletion?(false, state)
  170. checkSubscriptionStatusCompletion?(false)
  171. purchaseProductCompletion = nil
  172. restoreCompletion = nil
  173. fetchProductCompletion = nil
  174. checkSubscriptionStatusCompletion = nil
  175. }
  176. if state == .noReceipt || state == .restoreFailed || state == .restoreVerFailed {
  177. self.removeReceiptInfo()
  178. KMLightMemberManager.manager.reloadUserInfo()
  179. }
  180. if state == .verFailed ||
  181. state == .verSuccess ||
  182. state == .restoreVerFailed ||
  183. state == .restoreVerSuccess {
  184. //刷新用户信息
  185. KMLightMemberManager.manager.reloadUserInfo()
  186. }
  187. self.type = .unknow
  188. }
  189. }
  190. //判断是否订阅过
  191. func checkSubscriptionStatus(_ completion: @escaping KMPurchaseCheckSubscriptionStatusCompletion) {
  192. self.type = .check
  193. // self.checkSubscriptionStatusCompletion = completion
  194. completion(isPurchaseed || self.isInAppPurchaseReceiptPurchased())
  195. // SKPaymentQueue.default().restoreCompletedTransactions()
  196. }
  197. }
  198. extension KMInAppPurchaseManager: SKProductsRequestDelegate {
  199. func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
  200. availableProducts = response.products
  201. KMPrint(availableProducts)
  202. #if DEBUG
  203. KMPrint(response.invalidProductIdentifiers)
  204. KMPrint("产品付费数量")
  205. KMPrint(response.products.count)
  206. for p in response.products {
  207. KMPrint(p.description)
  208. KMPrint(p.localizedTitle)
  209. KMPrint(p.localizedDescription)
  210. KMPrint(p.price);
  211. KMPrint(p.productIdentifier)
  212. }
  213. #endif
  214. self.request?.cancel()
  215. self.request = nil
  216. // 处理产品信息
  217. guard let callBack = self.fetchProductCompletion else { return }
  218. DispatchQueue.main.async { [unowned self] in
  219. callBack(true, availableProducts, .productSuccess)
  220. fetchProductCompletion = nil
  221. }
  222. }
  223. func request(_ request: SKRequest, didFailWithError error: Error) {
  224. // 处理请求错误
  225. KMPrint("\("用户无法进行内购") + \(error)")
  226. self.handleAction(state: .notArrow)
  227. }
  228. }
  229. extension KMInAppPurchaseManager {
  230. func saveReceiptInfo(receipt: [String: Any]) {
  231. //保存票据信息
  232. UserDefaults.standard.set(receipt, forKey: "kInAppPurchaseReceipt")
  233. UserDefaults.standard.synchronize()
  234. //保存是否购买过本产品
  235. UserDefaults.standard.set("1", forKey: "kInAppPurchaseReceiptPurchased")
  236. UserDefaults.standard.synchronize()
  237. }
  238. func removeReceiptInfo() {
  239. //保存票据信息
  240. UserDefaults.standard.set([], forKey: "kInAppPurchaseReceipt")
  241. UserDefaults.standard.synchronize()
  242. }
  243. func isInAppPurchaseReceiptPurchased() -> Bool{
  244. let temp: String = UserDefaults.standard.object(forKey: "kInAppPurchaseReceiptPurchased") as? String ?? ""
  245. if temp == "1" {
  246. return true
  247. } else {
  248. return false
  249. }
  250. }
  251. }