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

时间:2017-04-14 09:20:53

标签: ios swift storekit swiftystorekit

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

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

有什么想法?谢谢

P.S。:我正在使用SwiftyStoreKit

4 个答案:

答案 0 :(得分:6)

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

  1. 在写入here时在本地进行收据验证。
  2. 在写入here时远程执行收据验证。提到收据不应该发送到App Store白色应用程序。简短摘要:

    • 您的应用会将收据发送给您的后端。
    • 您的后端将收据发送给Apple后端进行验证。
    • 你的后端得到苹果的回复。
    • 您的后端将结果发回给您的应用,收据有效或无效。
  3. 在这两种方式中,您都会获得应用内购买列表。它也将包含过期的订阅。您需要完成所有订阅并检查到期日期。如果它仍然有效,您必须向用户授予订阅。

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

答案 1 :(得分: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 :(得分:2)

我想提供一种可供选择的解决方案,该解决方案为仍然迷惑于此问题的人使用RevenueCat SDK

AppDelegate.swift

使用api密钥和可选的用户标识符来配置RevenueCat 购买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可用于帮助切换。

答案 3 :(得分:0)

另一个使用Qonversion SDK处理可自动更新的iOS订阅的解决方案。

AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    Qonversion.launch(withKey: "yourProjectKey")
    
    
    return true
  }

获取订阅状态

将App Store订阅链接到Qonversion产品,并将该产品链接到许可。 然后,您只需要在应用程序启动时触发checkPermissions方法即可检查用户的订阅是否仍然有效。此方法将检查用户收据并返回当前权限。然后,对于仍处于活动状态的订阅,如果订阅者已关闭自动更新,处于宽限期(计费重试状态)等,则可以获取详细信息。

Qonversion.checkPermissions { (permissions, error) in
  if let error = error {
    // handle error
    return
  }
  
  if let premium = permissions["premium"], premium.isActive {
    switch premium.renewState {
       case .willRenew, .nonRenewable:
         // .willRenew is the state of an auto-renewable subscription 
         // .nonRenewable is the state of consumable/non-consumable IAPs that could unlock lifetime access
         break
       case .billingIssue:
         // Grace period: permission is active, but there was some billing issue.
         // Prompt the user to update the payment method.
         break
       case .cancelled:
         // The user has turned off auto-renewal for the subscription, but the subscription has not expired yet.
         // Prompt the user to resubscribe with a special offer.
         break
       default: break
    }
  }
}

您可以检查我们的示例应用程序,该示例应用程序演示了自动续订订阅的实现here