如何在iOS Swift中正确还原Inapp购买产品

时间:2019-04-25 09:36:49

标签: ios swift in-app-purchase swiftystorekit

我的产品列表中同时包含“非消耗性”和“自动更新”订阅。因此,当我尝试恢复购买时,我会完成所有购买。现在,恢复购买时应该采取什么方法。

就我而言,我有两种产品分别按月和按年收费,而另一种则是非消耗性产品,可以终身使用。因此,在测试期间,我进行了几笔交易。但是在恢复时,我注意到我得到了所有购买的交易清单,需要从中恢复该用户的有效产品。那么我怎么知道要还原哪个项目?

从文档中,我找到了一种验证订阅和产品的方法。但是从我的答复中我可以看到,我拥有每月和终身有效的产品,可以还原。我应该在这里做什么?

这是我的代码

    @IBAction func restoreButtonPressed(_ sender: Any) {
            //        SubscriptionService.shared.restorePurchases()
            if self.premium != nil {
                // contact alert
                self.showActionSheet(title: "Contact us", message: "Tell us your query at \(Settings.requestEmail)", email: Settings.requestEmail)
                return
            }

            notificationShown = false
            hud.show(in: self.view)

    //        let appleValidator = AppleReceiptValidator(service: .sandbox, sharedSecret: Payment.sharedSecret)

            SwiftyStoreKit.restorePurchases(atomically: true) { results in
                for purchase in results.restoredPurchases {
                    print("//////////////////////")
                    print(purchase.productId)
                    print("Original Transaction Date: \((purchase.originalTransaction?.transactionDate)!)")
                    print("Original Transaction State: \((purchase.originalTransaction?.transactionState)!)")
                    print("Transaction Date: \((purchase.transaction.transactionDate)!)")
                    print("Transaction State: \((purchase.transaction.transactionState))")
                    print("//////////////////////")

                    if purchase.productId == Payment.lifetime {
                        SubscriptionService.shared.verifyPurchase(productId: purchase.productId, transactionDate: purchase.originalTransaction?.transactionDate, completion: { (success) in
                            self.hud.dismiss(afterDelay: 3.0)
                            if success {
                                Premium().check().done { premium in
                                    self.premium = premium
                                    self.initiatePremiumView()
                                    self.initPurchaseButton()
                                }
                            } else {
                                if self.notificationShown == false {
                                    self.showNotification(title: "No item to restore", buttonTitle: "", type: .failure)
                                    self.notificationShown = true
                                }
                            }
                            if purchase.needsFinishTransaction {
                                SwiftyStoreKit.finishTransaction(purchase.transaction)
                            }
                        })
                    } else {
                        SubscriptionService.shared.verifySubscription(productId: purchase.productId, transactionDate: purchase.originalTransaction?.transactionDate, completion: { (success) in
                            self.hud.dismiss(afterDelay: 3.0)
                            if success {
                                Premium().check().done { premium in
                                    self.premium = premium
                                    self.initiatePremiumView()
                                    self.initPurchaseButton()
                                    }.catch { _ in }
                            } else {
                                if self.notificationShown == false {
                                    self.showNotification(title: "No item to restore", buttonTitle: "", type: .failure)
                                    self.notificationShown = true
                                }
                            }
                        })
                    }
                    if purchase.needsFinishTransaction {
                        // Deliver content from server, then:
                        SwiftyStoreKit.finishTransaction(purchase.transaction)
                    }
                }


            }
            //            self.showAlert(self.alertForRestorePurchases(results))
        }

func verifySubscription(productId: String, transactionDate: Date?, completion: @escaping (Bool) -> ()) {
        let appleValidator = AppleReceiptValidator(service: .sandbox, sharedSecret: Payment.sharedSecret)

        SwiftyStoreKit.verifyReceipt(using: appleValidator, forceRefresh: false) { result in
            switch result {
            case .success(let receipt):
//                print(receipt.count)
                if receipt.count > 0 {
                    let purchaseResult = SwiftyStoreKit.verifySubscription(
                        ofType: .autoRenewable, // or .nonRenewing (see below)
                        productId: productId,
                        inReceipt: receipt)

                    switch purchaseResult {
                    case .purchased(let expiryDate, let items):
                        // give premium access
                        let premium = Premium(hasFullAccess: true, subscribedProduct: productId, expires: expiryDate, purchaseDate: transactionDate)
                        premium.giveFullAccess().done { result in
                            // show full access Dialog
                            completion(true)
                            }.catch { error in
                                // give error msg
                                completion(false)
//                                print("hell no")
                        }
//                        print("\(productId) is valid until \(expiryDate)\n\n")
                    case .expired(let expiryDate, let items):
                        // remove premium access
                        completion(false)
                        Premium().removePremiumAccess().done {_ in }.catch {_ in }
//                        print("\(productId) is expired since \(expiryDate)\n\n")
                    case .notPurchased:
                        // remove premium access
                        completion(false)
                        Premium().removePremiumAccess().done {_ in }.catch {_ in }
//                        print("The user has never purchased \(productId)")
                    }
                }
            //                print("Verify receipt success: \(receipt)")
            case .error(let error):
                print("Verify receipt failed: \(error)")
            }
        }
    }

    func verifyPurchase(productId: String, transactionDate: Date?, completion: @escaping (Bool) -> ()) {
        let appleValidator = AppleReceiptValidator(service: .sandbox, sharedSecret: Payment.sharedSecret)

        SwiftyStoreKit.verifyReceipt(using: appleValidator, forceRefresh: false) { result in
            switch result {
            case .success(let receipt):
                if receipt.count > 0 {
                    let purchaseResult = SwiftyStoreKit.verifyPurchase(
                        productId: productId,
                        inReceipt: receipt)

                    switch purchaseResult {
                    case .purchased(let receiptItem):
                        let premium = Premium(hasFullAccess: true, subscribedProduct: productId, expires: nil, purchaseDate: transactionDate)
                        premium.giveFullAccess().done { result in
                            // show full access Dialog
                            completion(true)
                            }.catch { error in
                                // give error msg
                                completion(false)
//                                print("hell no")
                        }
//                        print("\(productId) is purchased: \(receiptItem)")
                    case .notPurchased:
                        completion(false)
                        Premium().removePremiumAccess().done {_ in }.catch {_ in }
                    }                    
                }
            //                print("Verify receipt success: \(receipt)")
            case .error(let error):
                print("Verify receipt failed: \(error)")
            }
        }
    }

**还原时的完整购买的产品列表:**

//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-23 13:32:35 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-24 06:39:38 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-23 13:17:35 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-24 09:35:03 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-24 06:29:08 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-25 07:10:37 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-24 09:09:36 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-25 07:20:37 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-24 10:52:29 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: yearly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-23 12:14:35 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-24 09:30:01 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: yearly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-23 12:17:35 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-24 09:14:36 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-23 13:22:35 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-23 13:27:35 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-24 06:44:38 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-24 06:34:38 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-25 07:25:37 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-24 06:17:10 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-24 06:22:55 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-24 09:25:01 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-25 07:30:37 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-24 10:31:38 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: lifetime
Original Transaction Date: 2019-04-24 11:06:13 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-25 09:23:14 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-24 09:20:01 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-25 07:05:37 +0000
Transaction State: restored
//////////////////////
//////////////////////
Product Id: monthly
Original Transaction Date: 2019-04-23 12:14:36 +0000
Original Transaction State: purchased
Transaction Date: 2019-04-25 07:15:37 +0000
Transaction State: restored
//////////////////////

1 个答案:

答案 0 :(得分:0)

您应检查按最新排序的活动订阅,如果活动订阅处于活动状态,则将其解锁。 这取决于您的订阅逻辑

  

就我而言,我检查以下订单。

     

a)如果购买了终身计划,则该计划将被解锁   一生。

     

b)如果没有终身购买,则将在   对购买清单进行排序,找出是否有任何有效的订阅   对其进行解锁。

此外,我检查是否有未完成的购买,然后解锁内容并在解锁后将其标记为完成。