TSPurchaseManager.swift 33 KB

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