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