TSPurchaseManager.swift 26 KB

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