TSPurchaseManager.swift 23 KB

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