swift - 检查用户是否已经在 SwiftyStoreKit 中购买了产品

标签 swift in-app-purchase storekit swiftystorekit

我实现了应用内购买,并且正在使用 SwiftyStoreKit。 一切正常,但想检查用户是否已经购买了该产品。我希望当用户进入不适当的页面时显示一个按钮。如果购买,则显示“开盘”(如果不是“价格”)。我不太明白如何才能实现这一目标。

viewDidLoad():


let inAppPurchaseId = "iD"
    let sharedSecret = "shared secret"

override func viewDidLoad() {
        super.viewDidLoad()

        SwiftyStoreKit.retrieveProductsInfo([inAppPurchaseId]) { result in
            if let product = result.retrievedProducts.first {
                let priceString = product.localizedPrice!
                print("Product: \(product.localizedDescription), price: \(priceString)")
                self.buyBtn.setTitle("Buy guides for "+"\(priceString)", for: .normal)


                self.verifyPurchase(with: self.inAppPurchaseId, sharedSecret: self.sharedSecret)

            }
            else if let invalidProductId = result.invalidProductIDs.first {
                print("Invalid product identifier: \(invalidProductId)")
            }
            else {
                print("Error: \(String(describing: result.error))")
            }
        }

    }

这是收据验证和购买产品功能。

func purchaseProduct(with id: String) {
        SwiftyStoreKit.retrieveProductsInfo([id]) { result in
            if let product = result.retrievedProducts.first {
                SwiftyStoreKit.purchaseProduct(product, quantity: 1, atomically: true) { result in
                    switch result {
                    case .success(let product):
                        // fetch content from your server, then:
                        if product.needsFinishTransaction {
                            SwiftyStoreKit.finishTransaction(product.transaction)
                        }
                        self.buyBtn.setTitle("Open", for: .normal)
                        print("Purchase Success: \(product.productId)")
                    case .error(let error):
                        switch error.code {
                        case .unknown: print("Unknown error. Please contact support")
                        case .clientInvalid: print("Not allowed to make the payment")
                        case .paymentCancelled: break
                        case .paymentInvalid: print("The purchase identifier was invalid")
                        case .paymentNotAllowed: print("The device is not allowed to make the payment")
                        case .storeProductNotAvailable: print("The product is not available in the current storefront")
                        case .cloudServicePermissionDenied: print("Access to cloud service information is not allowed")
                        case .cloudServiceNetworkConnectionFailed: print("Could not connect to the network")
                        case .cloudServiceRevoked: print("User has revoked permission to use this cloud service")
                        default: print((error as NSError).localizedDescription)
                        }
                    }
                }
            }
        }
    }

    func verifyPurchase(with id: String, sharedSecret: String) {
        let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: sharedSecret)
        SwiftyStoreKit.verifyReceipt(using: appleValidator) { result in
            switch result {
            case .success(let receipt):
                let productId = id
                // Verify the purchase of Consumable or NonConsumable
                let purchaseResult = SwiftyStoreKit.verifyPurchase(
                    productId: productId,
                    inReceipt: receipt)

                switch purchaseResult {
                case .purchased(let receiptItem):
                    print("\(productId) is purchased: \(receiptItem)")
                case .notPurchased:
                    self.purchaseProduct(with: self.inAppPurchaseId)
                    print("The user has never purchased \(productId)")
                }
            case .error(let error):
                print("Receipt verification failed: \(error)")
            }
        }
    }

我想检查 View 何时加载按钮应具有的标题以及产品是否已购买。

最佳答案

您需要保存该产品是否已购买。示例 UserDefaults(未加密),但您可以使用 KeychainWrapper 。 首先尝试使用 UserDefaults.standard.bool 而不是 KeychainWrapper。

对于价格/打开按钮,请使用 fullPurchase 并更改标题和逻辑。

您有 2 个案例:

  1. 案例.purchased(letreceiptItem):

  2. 案例.未购买:

    var fullPurchase: bool ? { 得到 { 如果让 fullPurchasedFromKeychain = KeychainWrapper.standard.bool(forKey: FullAccessOlder) { 返回 fullPurchasedFromKeychain } } 返回错误 } 放 { KeychainWrapper.standard.set(newValue!, forKey: FullAccessOlder) }

    func verifyPurchase(with id: String, sharedSecret: String) {
            let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: sharedSecret)
            SwiftyStoreKit.verifyReceipt(using: appleValidator) { result in
                switch result {
                case .success(let receipt):
                    let productId = id
                    // Verify the purchase of Consumable or NonConsumable
                    let purchaseResult = SwiftyStoreKit.verifyPurchase(
                        productId: productId,
                        inReceipt: receipt)
    
                    switch purchaseResult {
                    case .purchased(let receiptItem):
                        print("\(productId) is purchased: \(receiptItem)")
                        self.fullPurchase = true
                    case .notPurchased:
                        self.purchaseProduct(with: self.inAppPurchaseId)
                        print("The user has never purchased \(productId)")
                        self.fullPurchase = false
                    }
                case .error(let error):
                    print("Receipt verification failed: \(error)")
                }
            }
        }
    

有关消耗品的信息会在付款时添加到收据中,并保留在收据中,直到您完成交易。完成交易后,该信息将在下次更新收据时删除(例如,用户下次购买时)。

关于swift - 检查用户是否已经在 SwiftyStoreKit 中购买了产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57093797/

相关文章:

ios - 使用 Swift 访问 JSON

Swift 包管理器和 Xcode : Retaining Xcode Settings?

ios - 加载指定初始化程序核心数据失败

Android:在应用计费中,是否使用库?

ios - Touch ID 未显示 StoreKit

ios - 新的应用内购买不会显示在 iTunes 应用程序产品页面中

ios - JSON 解析 Swift 使用 JSONPlaceholder

iphone - 如何测试可续订订阅(App Store)

ios - 如果用户在基于时间的 InApp 购买订阅中更改设备当前日期怎么办?

ios - 无法恢复非续订订阅的已完成交易