检查自动续订订阅是否仍然有效

问题描述 投票:13回答:3

每当我打开应用程序时,我都想检查自动可续订订阅状态。

这是为了确保用户仍然订阅了该服务。我该如何实现这一目标?

有什么想法吗?谢谢

P.S。:我正在使用SwiftyStoreKit

ios swift storekit swiftystorekit
3个回答
7
投票

以下是几种进行收据验证以检查用户是否已授予订阅的方法。以下是正确执行此操作的两种方法:

  1. 在本地进行收据验证,因为它写成here
  2. 在签署here时远程进行收据验证。提到收据不应该发送到App Store白色应用程序。简短的摘要: 您的应用会将收据发送到您的后端。 您的后端将收据发送给Apple后端进行验证。 你的后端得到苹果的回应。 您的后端将结果发回给您的应用,收据有效或无效。

通过这两种方式,您将获得应用内购买列表。它也将包含过期的订阅。您需要完成所有订阅并检查到期日期。如果它仍然有效,您必须向用户授予订阅。

据我所知,你正在使用SwiftyStoreKit,这里是local receipt validation的开放任务。


5
投票

你可以检查这个功能。它适用于swift4

func receiptValidation() {
let SUBSCRIPTION_SECRET = "yourpasswordift"
let receiptPath = Bundle.main.appStoreReceiptURL?.path
if FileManager.default.fileExists(atPath: receiptPath!){
    var receiptData:NSData?
    do{
        receiptData = try NSData(contentsOf: Bundle.main.appStoreReceiptURL!, options: NSData.ReadingOptions.alwaysMapped)
    }
    catch{
        print("ERROR: " + error.localizedDescription)
    }
    //let receiptString = receiptData?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
    let base64encodedReceipt = receiptData?.base64EncodedString(options: NSData.Base64EncodingOptions.endLineWithCarriageReturn)

    print(base64encodedReceipt!)


    let requestDictionary = ["receipt-data":base64encodedReceipt!,"password":SUBSCRIPTION_SECRET]

    guard JSONSerialization.isValidJSONObject(requestDictionary) else {  print("requestDictionary is not valid JSON");  return }
    do {
        let requestData = try JSONSerialization.data(withJSONObject: requestDictionary)
        let validationURLString = "https://sandbox.itunes.apple.com/verifyReceipt"  // this works but as noted above it's best to use your own trusted server
        guard let validationURL = URL(string: validationURLString) else { print("the validation url could not be created, unlikely error"); return }
        let session = URLSession(configuration: URLSessionConfiguration.default)
        var request = URLRequest(url: validationURL)
        request.httpMethod = "POST"
        request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData
        let task = session.uploadTask(with: request, from: requestData) { (data, response, error) in
            if let data = data , error == nil {
                do {
                    let appReceiptJSON = try JSONSerialization.jsonObject(with: data)
                    print("success. here is the json representation of the app receipt: \(appReceiptJSON)")
                    // if you are using your server this will be a json representation of whatever your server provided
                } catch let error as NSError {
                    print("json serialization failed with error: \(error)")
                }
            } else {
                print("the upload task returned an error: \(error)")
            }
        }
        task.resume()
    } catch let error as NSError {
        print("json serialization failed with error: \(error)")
    }



}
}

2
投票

我想提供一个替代解决方案,使用RevenueCat SDK为仍然偶然发现这个问题的人。

AppDelegate.swift

使用api密钥配置RevenueCat Purchases SDK和可选的用户标识符。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    Purchases.configure(withAPIKey: "<...>", appUserID: "<...>")

    ...

    return true
}

订阅状态功能

下面的函数检查PurchaserInfo以查看用户是否仍有活动的“权利”(或者您可以直接检查活动的产品ID)。

func subscriptionStatus(completion: @escaping (Bool)-> Void) {
    Purchases.shared.purchaserInfo { (info, error) in

        // Check if the purchaserInfo contains the pro feature ID you configured
        completion(info?.activeEntitlements.contains("pro_feature_ID") ?? false)

        // Alternatively, you can directly check if there is a specific product ID
        // that is active.
        // completion(info?.activeSubscriptions.contains("product_ID") ?? false)
    }
}

获得订阅状态

您可以根据需要经常调用上述函数,因为结果由Purchases SDK缓存,它将在大多数情况下同步返回,而不需要网络请求。

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    subscriptionStatus { (subscribed) in
        if subscribed {
            // Show that great pro content
        }
    }
}

如果您使用的是SwiftyStoreKit,则RevenueCat语法非常相似,并且有一个migration guide可用于帮助切换。

© www.soinside.com 2019 - 2024. All rights reserved.