Browse Source

优化订阅流程

100Years 3 months ago
parent
commit
e5c7b80027

+ 1 - 1
TSLiveWallpaper/Business/TSMineVC/TSMineVC.swift

@@ -126,7 +126,7 @@ class TSMineVC: TSBaseVC {
                 guard let self = self else { return }
 
                 let httpAppStoreLink = "https://apps.apple.com/app/id\(TSConfig.appid)"
-                let text = "I'm using Sweeter to decorate my phone, there are not only themes, wallpapers, widgets, but also dynamic island and super useful tools, come and try with me!".localized
+                let text = ""
                 let url = URL(string: httpAppStoreLink)!
                 let image = UIImage(named: "App-Icon")!
                 let vc = UIActivityViewController(activityItems: [image, text, url], applicationActivities: nil)

+ 7 - 4
TSLiveWallpaper/Business/TSPurchaseMembershipVC/TSPurchaseVC.swift

@@ -7,7 +7,7 @@
 
 import Combine
 import SwiftUI
-//import SwiftUIX
+
 class PurchaseViewModel : ObservableObject{
     
     @Published var selectedType: PremiumPeriod = .lifetime
@@ -48,9 +48,7 @@ class TSPurchaseVC: TSBaseVC {
         
         contentView.addSubview(hostVc.view)
         hostVc.view.snp.makeConstraints { make in
-            make.top.equalTo(contentView.safeAreaLayoutGuide.snp.top)
-            make.bottom.equalTo(contentView.safeAreaLayoutGuide.snp.bottom)
-            make.leading.trailing.top.equalToSuperview()
+            make.leading.trailing.bottom.top.equalToSuperview()
         }
     }
     
@@ -176,6 +174,11 @@ class TSPurchaseVC: TSBaseVC {
         TSToastShared.hideLoading()
         self.dismiss(animated: true)
     }
+    
+    
+    deinit {
+        cancellabel.removeAll()
+    }
 }
 
 

+ 41 - 0
TSLiveWallpaper/Business/TSPurchaseMembershipVC/TSViewTool/PhotoManager.swift

@@ -103,4 +103,45 @@ class PhotoManager {
             completion(success, error)
         }
     }
+    
+    
+    
+    /// 保存图片到相册
+    /// - Parameters:
+    ///   - image: 要保存的 UIImage
+    ///   - completion: 保存结果的回调,返回成功与否和错误信息
+    func saveImageToAlbum(_ image: UIImage, completion: @escaping (Bool, Error?) -> Void) {
+        // 检查相册权限
+        PHPhotoLibrary.requestAuthorization { status in
+            DispatchQueue.main.async {
+                switch status {
+                case .authorized:
+                    // 权限已授权,保存图片
+                    self.save(image: image, completion: completion)
+                case .limited:
+                    // 在受限权限下保存图片
+                    self.save(image: image, completion: completion)
+                case .denied, .restricted:
+                    // 权限被拒绝或受限
+                    completion(false, NSError(domain: "PhotoSaver", code: 1, userInfo: [NSLocalizedDescriptionKey: "Photo Library access is denied."]))
+                case .notDetermined:
+                    // 不会进入这个分支,因为已经请求了权限
+                    completion(false, NSError(domain: "PhotoSaver", code: 2, userInfo: [NSLocalizedDescriptionKey: "Photo Library access not determined."]))
+                @unknown default:
+                    completion(false, NSError(domain: "PhotoSaver", code: 3, userInfo: [NSLocalizedDescriptionKey: "Unknown authorization status."]))
+                }
+            }
+        }
+    }
+
+    /// 保存图片到相册的具体实现
+    private func save(image: UIImage, completion: @escaping (Bool, Error?) -> Void) {
+        PHPhotoLibrary.shared().performChanges({
+            PHAssetChangeRequest.creationRequestForAsset(from: image)
+        }) { success, error in
+            DispatchQueue.main.async {
+                completion(success, error)
+            }
+        }
+    }
 }

+ 1 - 1
TSLiveWallpaper/Common/NetworkManager/TSNetworkManager.swift

@@ -24,7 +24,7 @@ class TSNetworkManager {
             completion(nil, NSError(domain: "Invalid URL", code: -1, userInfo: nil))
             return
         }
-        debugPrint("postRequest urlString=%@",urlString)
+        debugPrint("postRequest urlString=",urlString)
         // 创建请求
         var request = URLRequest(url: url)
         request.httpMethod = "POST"

+ 40 - 11
TSLiveWallpaper/Common/Purchase/TSPurchaseManager.swift

@@ -88,6 +88,8 @@ public class PurchaseManager: NSObject {
     // 免费使用会员转 livew的次数
     var freeNum:Int = 0
     
+    //原始订单交易id dict
+    var originalTransactionIdentifierDict:[String:String] = [:]
     
     override init() {
         super.init()
@@ -287,28 +289,41 @@ extension PurchaseManager: SKProductsRequestDelegate {
 
 extension PurchaseManager: SKPaymentTransactionObserver {
     public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
-        debugPrint("PurchaseManager paymentQueue transactions = \(transactions)")
+        debugPrint("PurchaseManager paymentQueue transactions.count = \(transactions.count)")
+//        debugPrint("PurchaseManager paymentQueue transactions = \(transactions)")
+        
+        originalTransactionIdentifierDict.removeAll()
         // 因为只有订阅类的购买项
         for transaction in transactions {
-//            if transaction.transactionState != .purchasing {
-//                SKPaymentQueue.default().finishTransaction(transaction)
-//                continue
-//            }
+
+//            debugPrint("PurchaseManager paymentQueue transactions transactionIdentifier original= \(transaction.original?.transactionIdentifier)")
+//            debugPrint("PurchaseManager paymentQueue transactions transactionIdentifier = \(transaction.transactionIdentifier)")
+//            debugPrint("PurchaseManager paymentQueue transactions transactionIdentifier productIdentifier = \(transaction.payment.productIdentifier)")
+            
             switch transaction.transactionState {
             case .purchasing:
                 // Transaction is being added to the server queue.
                 purchase(self, didChaged: .paying, object: nil)
 
             case .purchased:
+                SKPaymentQueue.default().finishTransaction(transaction)
+                //同样的原始订单,只处理一次.
+                guard judgeWhether(transaction: transaction) else {
+                    break
+                }
+                
                 // Transaction is in queue, user has been charged.  Client should complete the transaction.
                 #if DEBUG
                     verifyPayResult(transaction: transaction, useSandBox: true)
                 #else
                     verifyPayResult(transaction: transaction, useSandBox: false)
                 #endif
+                
+                
             case .failed:
-                // Transaction was cancelled or failed before being added to the server queue.
+                
                 SKPaymentQueue.default().finishTransaction(transaction)
+                // Transaction was cancelled or failed before being added to the server queue.
                 var message = "Payment Failed"
                 if let error = transaction.error as? SKError,
                    error.code == SKError.paymentCancelled {
@@ -317,6 +332,12 @@ extension PurchaseManager: SKPaymentTransactionObserver {
                 purchase(self, didChaged: .payFail, object: message)
 
             case .restored:
+                SKPaymentQueue.default().finishTransaction(transaction)
+                //同样的原始订单,只处理一次.
+                guard judgeWhether(transaction: transaction) else {
+                    break
+                }
+                
                 // Transaction was restored from user's purchase history.  Client should complete the transaction.
                 if let original = transaction.original,
                    original.transactionState == .purchased {
@@ -327,9 +348,8 @@ extension PurchaseManager: SKPaymentTransactionObserver {
                     #endif
                 } else {
                     purchase(self, didChaged: .restoreFail, object: "Failed to restore subscribe, please try again")
-                    SKPaymentQueue.default().finishTransaction(transaction)
                 }
-
+                
             case .deferred: // The transaction is in the queue, but its final status is pending external action.
                 break
             @unknown default:
@@ -349,6 +369,17 @@ extension PurchaseManager: SKPaymentTransactionObserver {
             purchase(self, didChaged: .restoreFail, object: "You don't have an active subscription")
         }
     }
+    
+    func judgeWhether(transaction:SKPaymentTransaction) -> Bool {
+        let id = transaction.original?.transactionIdentifier
+        if let id = id {
+            if let value = originalTransactionIdentifierDict[id] {
+                return false
+            }
+            originalTransactionIdentifierDict[id] = "1"
+        }
+        return true
+    }
 }
 
 extension PurchaseManager {
@@ -375,7 +406,7 @@ extension PurchaseManager {
             guard let self = self else { return }
             if let data = data,
                let jsonResponse = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
-                debugPrint("PurchaseManager verifyPayResult = \(jsonResponse)")
+//                debugPrint("PurchaseManager verifyPayResult = \(jsonResponse)")
                 let status = jsonResponse["status"]
                 if let status = status as? String, status == "21007" {
                     self.verifyPayResult(transaction: transaction, useSandBox: true)
@@ -436,8 +467,6 @@ extension PurchaseManager {
             }
         }
 
-        SKPaymentQueue.default().finishTransaction(transaction)
-
         DispatchQueue.main.async {
             if transaction.transactionState == .restored {
                 self.purchase(self, didChaged: .restoreSuccess, object: nil)