检查自动更新订阅是否仍然有效
问题描述:
答
下面是几种方法可以做到收据验证检查的用户授予订阅。这里有两种方法可以正确地做到这一点:
- 在本地进行收据验证,因为它被写入here。
-
远程执行收据验证,因为它的写法为here。有人提到,收据不应该发送到App Store白色的应用程序。简短摘要:
- 您的应用将收据发送到您的后端。
- 您的后端将收据发送至Apple后端进行验证。
- 你的后端从苹果获得响应。
- 您的后端将结果发送回您的应用程序的回执有效或无效。
在这两种方式,你会得到应用内购买的名单。它也包含过期的订阅。您将需要抛出所有订阅并检查到期日期。如果它仍然有效,您必须授予用户订阅权。
据我所知你使用的是SwiftyStoreKit,这里是local receipt validation的开放任务。
答
您可以使用此功能进行检查。它的作品与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)")
}
}
}
您需要验证收据的应用程序部分。请参阅Apple的应用内购买编程指南 – Paulw11