TSPurchaseManager.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. //
  2. // TSPurchaseManager.swift
  3. // TSLiveWallpaper
  4. //
  5. // Created by 100Years on 2025/1/13.
  6. //
  7. import Foundation
  8. import StoreKit
  9. public enum PremiumPeriod: String, CaseIterable {
  10. case none = ""
  11. case week = "Week"
  12. case month = "Monthly"
  13. case year = "Yearly"
  14. case lifetime = "Lifetime"
  15. }
  16. public struct PurchaseProduct {
  17. public let productId: String
  18. public let period: PremiumPeriod
  19. public init(productId: String, period: PremiumPeriod) {
  20. self.productId = productId
  21. self.period = period
  22. }
  23. }
  24. public enum PremiumRequestState {
  25. case none
  26. case loading
  27. case loadSuccess
  28. case loadFail
  29. case paying
  30. case paySuccess
  31. case payFail
  32. case restoreing
  33. case restoreSuccess
  34. case restoreFail
  35. case verifying
  36. case verifySuccess
  37. case verifyFail
  38. }
  39. public extension Notification.Name {
  40. static let kPurchasePrepared = Self.init("kPurchaseProductPrepared")
  41. static let kPurchaseDidChanged = Self.init("kPurchaseDidChanged")
  42. }
  43. private let kPremiumExpiredInfoKey = "premiumExpiredInfoKey"
  44. typealias PurchaseStateChangeHandler = (_ manager: PurchaseManager, _ state: PremiumRequestState, _ object: Any?) -> Void
  45. public let kPurchaseDefault = PurchaseManager.default
  46. public class PurchaseManager: NSObject {
  47. @objc public static let `default` = PurchaseManager()
  48. //苹果共享密钥
  49. public var AppleSharedKey:String = ""
  50. //商品信息
  51. public lazy var purchaseProducts:[PurchaseProduct] = []
  52. struct Config {
  53. static let verifyUrl = "https://buy.itunes.apple.com/verifyReceipt"
  54. static let sandBoxUrl = "https://sandbox.itunes.apple.com/verifyReceipt"
  55. }
  56. lazy var products: [SKProduct] = []
  57. var onPurchaseStateChanged: PurchaseStateChangeHandler?
  58. // 会员信息
  59. var vipInformation: [String: Any] = [:]
  60. //原始订单交易id dict
  61. var originalTransactionIdentifierDict:[String:String] = [:]
  62. override init() {
  63. super.init()
  64. SKPaymentQueue.default().add(self)
  65. if let info = UserDefaults.standard.object(forKey: kPremiumExpiredInfoKey) as? [String: Any] {
  66. vipInformation = info
  67. }
  68. }
  69. public var expiredDate: Date? {
  70. guard let time = vipInformation["expireTime"] as? String else {
  71. return nil
  72. }
  73. return convertExpireDate(from: time)
  74. }
  75. public var expiredDateString: String {
  76. if vipType == .lifetime{
  77. return "Life Time"
  78. } else {
  79. if let expDate = expiredDate {
  80. let format = DateFormatter()
  81. format.locale = .current
  82. format.dateFormat = "yyyy-MM-dd"
  83. return format.string(from: expDate)
  84. } else {
  85. return "--"
  86. }
  87. }
  88. }
  89. private func convertExpireDate(from string: String) -> Date? {
  90. if let ts = TimeInterval(string) {
  91. let date = Date(timeIntervalSince1970: ts / 1000)
  92. return date
  93. }
  94. return nil
  95. }
  96. @objc public var isVip: Bool {
  97. guard let expiresDate = expiredDate else {
  98. return false
  99. }
  100. let todayStart = Calendar.current.startOfDay(for: Date())
  101. let todayStartTs = todayStart.timeIntervalSince1970
  102. let expiresTs = expiresDate.timeIntervalSince1970
  103. return expiresTs > todayStartTs
  104. }
  105. public var vipType: PremiumPeriod {
  106. guard isVip, let type = vipInformation["type"] as? String else {
  107. return .none
  108. }
  109. return PremiumPeriod(rawValue: type) ?? .none
  110. }
  111. /// 过期时间: 1683277585000 毫秒
  112. func updateExpireTime(_ timeInterval: String,
  113. for productId: String) {
  114. vipInformation.removeAll()
  115. vipInformation["expireTime"] = timeInterval
  116. vipInformation["productId"] = productId
  117. vipInformation["type"] = period(for: productId).rawValue
  118. UserDefaults.standard.set(vipInformation, forKey: kPremiumExpiredInfoKey)
  119. UserDefaults.standard.synchronize()
  120. NotificationCenter.default.post(name: .kPurchaseDidChanged, object: nil)
  121. }
  122. // 商品id对应的时间周期
  123. func period(for productId: String) -> PremiumPeriod {
  124. return purchaseProducts.first(where: { $0.productId == productId })?.period ?? .none
  125. }
  126. // 时间周期对应的商品id
  127. func productId(for period: PremiumPeriod) -> String? {
  128. return purchaseProducts.first(where: { $0.period == period })?.productId
  129. }
  130. }
  131. // MARK: 商品信息
  132. extension PurchaseManager {
  133. public func product(for period: PremiumPeriod) -> SKProduct? {
  134. return products.first(where: { $0.productIdentifier == productId(for: period) })
  135. }
  136. // 商品价格
  137. public func price(for period: PremiumPeriod) -> String? {
  138. guard let product = product(for: period) else {
  139. return nil
  140. }
  141. let formatter = NumberFormatter()
  142. formatter.formatterBehavior = NumberFormatter.Behavior.behavior10_4
  143. formatter.numberStyle = .currency
  144. formatter.locale = product.priceLocale
  145. return formatter.string(from: product.price)
  146. }
  147. // public func originalPrice(for period: PremiumPeriod) -> String? {
  148. // guard let product = product(for: period) else {
  149. // return nil
  150. // }
  151. // switch period {
  152. // case .year, .lifetime:
  153. // // 5折
  154. // let price = product.price.doubleValue
  155. // let calculatePrice = price * 2
  156. // let originStr = String(format: "%.2f", calculatePrice)
  157. // let originPrice = NSDecimalNumber(string: originStr, locale: product.priceLocale)
  158. //
  159. // let formatter = NumberFormatter()
  160. // formatter.formatterBehavior = NumberFormatter.Behavior.behavior10_4
  161. // formatter.numberStyle = .currency
  162. // formatter.locale = product.priceLocale
  163. // return formatter.string(from: originPrice)
  164. // default:
  165. // return nil
  166. // }
  167. // }
  168. }
  169. // MARK: 商品 & 订阅请求
  170. extension PurchaseManager {
  171. ///请求商品
  172. public func requestProducts() {
  173. if !products.isEmpty {
  174. purchase(self, didChaged: .loadSuccess, object: nil)
  175. }
  176. purchase(self, didChaged: .loading, object: nil)
  177. let productIdentifiers = Set(purchaseProducts.map({ $0.productId }))
  178. debugPrint("PurchaseManager requestProducts = \(productIdentifiers)")
  179. let request = SKProductsRequest(productIdentifiers: productIdentifiers)
  180. request.delegate = self
  181. request.start()
  182. }
  183. public func restorePremium() {
  184. purchase(self, didChaged: .restoreing, object: nil)
  185. SKPaymentQueue.default().restoreCompletedTransactions()
  186. debugPrint("PurchaseManager restoreCompletedTransactions")
  187. }
  188. /// 购买支付
  189. public func pay(for period: PremiumPeriod) {
  190. guard SKPaymentQueue.canMakePayments() else {
  191. purchase(self, didChaged: .payFail, object: "Payment failed, please check your payment account")
  192. return
  193. }
  194. guard SKPaymentQueue.default().transactions.count <= 0 else {
  195. purchase(self, didChaged: .payFail, object: "You have outstanding orders that must be paid for before a new subscription can be placed.")
  196. restorePremium()
  197. return
  198. }
  199. if let product = product(for: period) {
  200. purchase(self, didChaged: .paying, object: nil)
  201. let payment = SKPayment(product: product)
  202. SKPaymentQueue.default().add(payment)
  203. debugPrint("PurchaseManager pay period = \(period)")
  204. }else{
  205. purchase(self, didChaged: .payFail, object: "Payment failed, no this item")
  206. }
  207. }
  208. }
  209. // MARK: 商品回调
  210. extension PurchaseManager: SKProductsRequestDelegate {
  211. public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
  212. let products = response.products
  213. self.products = products
  214. purchase(self, didChaged: .loadSuccess, object: nil)
  215. NotificationCenter.default.post(name: .kPurchasePrepared, object: nil)
  216. debugPrint("PurchaseManager productsRequest didReceive = \(products)")
  217. }
  218. public func request(_ request: SKRequest, didFailWithError error: Error) {
  219. debugPrint("PurchaseManager productsRequest error = \(error)")
  220. purchase(self, didChaged: .loadFail, object: error.localizedDescription)
  221. }
  222. }
  223. // MARK: 订阅回调
  224. extension PurchaseManager: SKPaymentTransactionObserver {
  225. public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
  226. debugPrint("PurchaseManager paymentQueue transactions.count = \(transactions.count)")
  227. // debugPrint("PurchaseManager paymentQueue transactions = \(transactions)")
  228. originalTransactionIdentifierDict.removeAll()
  229. // 因为只有订阅类的购买项
  230. for transaction in transactions {
  231. // debugPrint("PurchaseManager paymentQueue transactions transactionIdentifier original= \(transaction.original?.transactionIdentifier)")
  232. // debugPrint("PurchaseManager paymentQueue transactions transactionIdentifier = \(transaction.transactionIdentifier)")
  233. // debugPrint("PurchaseManager paymentQueue transactions transactionIdentifier productIdentifier = \(transaction.payment.productIdentifier)")
  234. switch transaction.transactionState {
  235. case .purchasing:
  236. // Transaction is being added to the server queue.
  237. purchase(self, didChaged: .paying, object: nil)
  238. case .purchased:
  239. SKPaymentQueue.default().finishTransaction(transaction)
  240. //同样的原始订单,只处理一次.
  241. guard judgeWhether(transaction: transaction) else {
  242. break
  243. }
  244. // Transaction is in queue, user has been charged. Client should complete the transaction.
  245. #if DEBUG
  246. verifyPayResult(transaction: transaction, useSandBox: true)
  247. #else
  248. verifyPayResult(transaction: transaction, useSandBox: false)
  249. #endif
  250. case .failed:
  251. SKPaymentQueue.default().finishTransaction(transaction)
  252. // Transaction was cancelled or failed before being added to the server queue.
  253. var message = "Payment Failed"
  254. if let error = transaction.error as? SKError,
  255. error.code == SKError.paymentCancelled {
  256. message = "The subscription was canceled"
  257. }
  258. purchase(self, didChaged: .payFail, object: message)
  259. case .restored:
  260. SKPaymentQueue.default().finishTransaction(transaction)
  261. //同样的原始订单,只处理一次.
  262. guard judgeWhether(transaction: transaction) else {
  263. break
  264. }
  265. // Transaction was restored from user's purchase history. Client should complete the transaction.
  266. if let original = transaction.original,
  267. original.transactionState == .purchased {
  268. #if DEBUG
  269. verifyPayResult(transaction: transaction, useSandBox: true)
  270. #else
  271. verifyPayResult(transaction: transaction, useSandBox: false)
  272. #endif
  273. } else {
  274. purchase(self, didChaged: .restoreFail, object: "Failed to restore subscribe, please try again")
  275. }
  276. case .deferred: // The transaction is in the queue, but its final status is pending external action.
  277. break
  278. @unknown default:
  279. SKPaymentQueue.default().finishTransaction(transaction)
  280. }
  281. }
  282. }
  283. public func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
  284. purchase(self, didChaged: .restoreFail, object: nil)
  285. }
  286. public func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
  287. if let trans = queue.transactions.first(where: { $0.transactionState == .purchased }) {
  288. verifyPayResult(transaction: trans, useSandBox: false)
  289. } else if queue.transactions.isEmpty {
  290. purchase(self, didChaged: .restoreFail, object: "You don't have an active subscription")
  291. }
  292. }
  293. func judgeWhether(transaction:SKPaymentTransaction) -> Bool {
  294. let id = transaction.original?.transactionIdentifier
  295. if let id = id {
  296. if let value = originalTransactionIdentifierDict[id] {
  297. return false
  298. }
  299. originalTransactionIdentifierDict[id] = "1"
  300. }
  301. return true
  302. }
  303. }
  304. extension PurchaseManager {
  305. func verifyPayResult(transaction: SKPaymentTransaction, useSandBox: Bool) {
  306. purchase(self, didChaged: .verifying, object: nil)
  307. guard let url = Bundle.main.appStoreReceiptURL,
  308. let receiptData = try? Data(contentsOf: url) else {
  309. purchase(self, didChaged: .verifyFail, object: "凭证文件为空")
  310. return
  311. }
  312. let requestContents = [
  313. "receipt-data": receiptData.base64EncodedString(),
  314. "password": AppleSharedKey,
  315. ]
  316. guard let requestData = try? JSONSerialization.data(withJSONObject: requestContents) else {
  317. purchase(self, didChaged: .verifyFail, object: "凭证文件为空")
  318. return
  319. }
  320. let verifyUrlString = useSandBox ? Config.sandBoxUrl : Config.verifyUrl
  321. postRequest(urlString: verifyUrlString, httpBody: requestData) { [weak self] data, error in
  322. guard let self = self else { return }
  323. if let data = data,
  324. let jsonResponse = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
  325. // debugPrint("PurchaseManager verifyPayResult = \(jsonResponse)")
  326. let status = jsonResponse["status"]
  327. if let status = status as? String, status == "21007" {
  328. self.verifyPayResult(transaction: transaction, useSandBox: true)
  329. } else if let status = status as? Int, status == 21007 {
  330. self.verifyPayResult(transaction: transaction, useSandBox: true)
  331. } else if let status = status as? String, status == "0" {
  332. self.handlerPayResult(transaction: transaction, resp: jsonResponse)
  333. } else if let status = status as? Int, status == 0 {
  334. self.handlerPayResult(transaction: transaction, resp: jsonResponse)
  335. } else {
  336. self.purchase(self, didChaged: .verifyFail, object: "验证结果状态码错误:\(status.debugDescription)")
  337. }
  338. } else {
  339. self.purchase(self, didChaged: .verifyFail, object: "验证结果为空")
  340. debugPrint("PurchaseManager 验证结果为空")
  341. }
  342. }
  343. /*
  344. 21000 App Store无法读取你提供的JSON数据
  345. 21002 收据数据不符合格式
  346. 21003 收据无法被验证
  347. 21004 你提供的共享密钥和账户的共享密钥不一致
  348. 21005 收据服务器当前不可用
  349. 21006 收据是有效的,但订阅服务已经过期。当收到这个信息时,解码后的收据信息也包含在返回内容中
  350. 21007 收据信息是测试用(sandbox),但却被发送到产品环境中验证
  351. 21008 收据信息是产品环境中使用,但却被发送到测试环境中验证
  352. */
  353. }
  354. func handlerPayResult(transaction: SKPaymentTransaction, resp: [String: Any]) {
  355. var isLifetime = false
  356. // 终生会员
  357. if let receipt = resp["receipt"] as? [String: Any],
  358. let in_app = receipt["in_app"] as? [[String: Any]] {
  359. if let lifetimeProductId = purchaseProducts.first(where: { $0.period == .lifetime })?.productId,
  360. let _ = in_app.filter({ ($0["product_id"] as? String) == lifetimeProductId }).first(where: { item in
  361. if let purchase_date = item["purchase_date"] as? String,
  362. !purchase_date.isEmpty {
  363. return true
  364. } else if let purchase_date_ms = item["purchase_date_ms"] as? String,
  365. !purchase_date_ms.isEmpty {
  366. return true
  367. }
  368. return false
  369. }) {
  370. updateExpireTime(lifetimeExpireTime, for: lifetimeProductId)
  371. isLifetime = true
  372. }
  373. }
  374. if !isLifetime {
  375. let info = resp["latest_receipt_info"] as? [[String: Any]]
  376. if let firstItem = info?.first,
  377. let expires_date_ms = firstItem["expires_date_ms"] as? String,
  378. let productId = firstItem["product_id"] as? String {
  379. updateExpireTime(expires_date_ms, for: productId)
  380. }
  381. }
  382. DispatchQueue.main.async {
  383. if transaction.transactionState == .restored {
  384. self.purchase(self, didChaged: .restoreSuccess, object: nil)
  385. } else {
  386. self.purchase(self, didChaged: .paySuccess, object: nil)
  387. }
  388. }
  389. }
  390. // 终生会员过期时间:100年
  391. var lifetimeExpireTime: String {
  392. let date = Date().addingTimeInterval(100 * 365 * 24 * 60 * 60)
  393. return "\(date.timeIntervalSince1970 * 1000)"
  394. }
  395. /// 发送 POST 请求
  396. /// - Parameters:
  397. /// - urlString: 请求的 URL 字符串
  398. /// - parameters: 请求的参数字典(将自动转换为 JSON)
  399. /// - timeout: 超时时间(默认 30 秒)
  400. /// - completion: 请求完成的回调,返回 `Data?` 和 `Error?`
  401. func postRequest(
  402. urlString: String,
  403. httpBody: Data?,
  404. timeout: TimeInterval = 90,
  405. completion: @escaping (Data?, Error?) -> Void
  406. ) {
  407. // 确保 URL 有效
  408. guard let url = URL(string: urlString) else {
  409. completion(nil, NSError(domain: "Invalid URL", code: -1, userInfo: nil))
  410. return
  411. }
  412. dePrint("postRequest urlString=\(urlString)")
  413. // 创建请求
  414. var request = URLRequest(url: url)
  415. request.httpMethod = "POST"
  416. request.timeoutInterval = timeout
  417. request.setValue("application/json", forHTTPHeaderField: "Content-Type")
  418. request.httpBody = httpBody
  419. // 创建数据任务
  420. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  421. completion(data, error)
  422. }
  423. // 启动任务
  424. task.resume()
  425. }
  426. }
  427. public extension PurchaseManager {
  428. func canContinue(_ requireVip: Bool) -> Bool {
  429. guard requireVip else {
  430. return true
  431. }
  432. return isVip
  433. }
  434. func purchase(_ manager: PurchaseManager, didChaged state: PremiumRequestState, object: Any?){
  435. onPurchaseStateChanged?(manager,state,object)
  436. }
  437. }
  438. /*
  439. 首先,创建SKProductsRequest对象并使用init(productIdentifiers:)初始化,传入要查询的产品标识符。
  440. 然后,调用start()方法开始请求产品信息。
  441. 当请求成功时,productsRequest(_:didReceive:)方法会被调用,在这里可以获取产品详细信息并展示给用户(如在界面上显示产品价格、名称等)。如果请求失败,productsRequest(_:didFailWithError:)方法会被调用来处理错误。
  442. 当用户决定购买某个产品后,根据产品信息(SKProduct对象)创建SKPayment对象,然后使用SKPaymentQueue的add(_:)方法将支付请求添加到支付队列。
  443. 同时,在应用启动等合适的时机,通过SKPaymentQueue的addTransactionObserver(_:)方法添加交易观察者。当支付状态发生变化时,paymentQueue(_:updatedTransactions:)方法会被调用,在这里可以根据交易状态(如购买成功、失败、恢复等)进行相应的处理。
  444. */