swift 在App Purchase Helper中

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 在App Purchase Helper中相关的知识,希望对你有一定的参考价值。

import Foundation
import SwiftyStoreKit

struct IAPurchaseHelper {
    enum productID: String {
        case TIER_ONE = "YOUR_PRODUCT_ID"
        case TIER_TWO = "YOUR_PRODUCT_ID"
        case TIER_THREE = "YOUR_PRODUCT_ID"
    }
    static let shared = IAPurchaseHelper()
    typealias SubscriptionStatus = (subscribed: Bool, expireDate: Date?, subscriptionType: SubscriptionType)
    
    /// Retrieves back product info. It's only returning the first product INFO. Need to update for all three
    func getProductInfo(_ completion: @escaping (_ price: String) -> Void) {
        SwiftyStoreKit.retrieveProductsInfo([productID.TIER_ONE.rawValue, productID.TIER_TWO.rawValue, productID.TIER_THREE.rawValue]) { result in
            if let product = result.retrievedProducts.first {
                let priceString = product.localizedPrice!
                print("Product: \(product.localizedDescription), price: \(priceString)")
                completion(priceString)
            } else if let invalidProductId = result.invalidProductIDs.first {
                print("Invalid product identifier: \(invalidProductId)")
                completion("$4.99 USD")
            }
            else {
                completion("$4.99 USD")
            }
        }
    }
    
    func purchaseSubscription(productId: productID, _ completion: @escaping (_ purchased: Bool) -> Void) {
        SwiftyStoreKit.purchaseProduct(productId.rawValue, quantity: 1, atomically: true) { result in
            switch result {
            case .success(let purchase):
                print("PURCHAINSG!!!!!", purchase.productId)
                completion(true)
                self.verifiySubscription()
            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")
                }
            }
        }
    }
    
    
    private func verifySubscriptionStatusFromReceipt(_ receipt: ReceiptInfo, productId: productID, subscriptionType: SubscriptionType) -> SubscriptionStatus {
        var status = SubscriptionStatus(subscribed: false, expireDate: nil, subscriptionType: subscriptionType)
        let productIDString = productId.rawValue
        
        // Verify the purchase of a Subscription
        let purchaseResult = SwiftyStoreKit.verifySubscription(
            ofType: .autoRenewable,
            productId: productIDString,
            inReceipt: receipt)
        
        switch purchaseResult {
        case .purchased(let expiryDate, let items):
            print("\(productId) is valid until \(expiryDate)\n\(items)\n")
            status.expireDate = expiryDate
            status.subscribed = true
            return status
        case .expired(let expiryDate, let items):
            print("\(productId) is expired since \(expiryDate)\n\(items)\n")
            status.expireDate = expiryDate
            return status
        case .notPurchased:
            print("The user has never purchased \(productId). Do Nothing")
            return status
        }
    }
    
    func verifiySubscription() {
        let appleValidator = AppleReceiptValidator(service: ApplicationHelper.shared.getRecieptValidationStatus(), sharedSecret: ApplicationHelper.shared.getSharedSecret())
        SwiftyStoreKit.verifyReceipt(using: appleValidator) { result in
            switch result {
            case .success(let receipt):
                let tierOneStatus = self.verifySubscriptionStatusFromReceipt(receipt, productId: .TIER_ONE, subscriptionType: .tierOne)
                let tierTwoStatus = self.verifySubscriptionStatusFromReceipt(receipt, productId: .TIER_TWO, subscriptionType: .tierTwo)
                let tierThreeStatus = self.verifySubscriptionStatusFromReceipt(receipt, productId: .TIER_THREE, subscriptionType: .tierThree)
                
                
                
                
            case .error(let error):
                print("Receipt verification failed: \(error)")
            }
        }
    }
}

以上是关于swift 在App Purchase Helper中的主要内容,如果未能解决你的问题,请参考以下文章

Flutter in_app_purchase '_enablePendingPurchases':必须在调用 startConnection 之前调用 enablePendingPurchases(

Flutter:如何在 in_app_purchase 中调用 Apple pay bottom sheet?

如何停止在 iOS 上跟踪 in_app_purchase Firebase 事件?

Flutter In-App-Purchase,每次重启应用如何查看是不是已购买?

加载产品详细信息时,Cordova iOS In App Purchase 崩溃

In App Purchase沙盒问题