TSPurchaseManager.swift 26 KB

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