TSPurchaseManager.swift 29 KB

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