TSPurchaseManager.swift 29 KB

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