我做了很多关于自动续订订阅的阅读,但我对如何检查用户是否有有效订阅有疑问。
这就是我收到收据的方式
func validateRecipt(callback:(receipt:NSDictionary?)->()){
let recuptUrl = NSBundle.mainBundle().appStoreReceiptURL
if let receipt: NSData = NSData(contentsOfURL:recuptUrl!) {
//https://sandbox.itunes.apple.com/verifyReceipt //TEST ENVIRONMENT
//https://buy.itunes.apple.com/verifyReceipt //PRODUCTION ENVIRONMENT
let request = NSMutableURLRequest(URL: NSURL(string: "https://sandbox.itunes.apple.com/verifyReceipt")!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 10)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
let receiptdata:NSString = receipt.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let payload:NSDictionary = {["receipt-data" : receiptdata, "password" : "mySharedKey"]}()
//, password\" : \"" + EGConstants.sharedSecret + "\" }"
do {
let payloadData:NSData = try(NSJSONSerialization.dataWithJSONObject(payload, options: NSJSONWritingOptions(rawValue: 0)))
request.HTTPBody = payloadData
let task = session.dataTaskWithRequest(request) { (data, response, err) in
do {
let json = try(NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary)
if(err != nil) {
print(err!.localizedDescription)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
callback(receipt: nil)
}
else {
if let parseJSON = json {
callback(receipt: parseJSON)
}
else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Recipt Error: \(jsonStr)")
callback(receipt: nil)
}
}
} catch {
}
}
task.resume()
} catch {}
}
}
我的问题是:
1.如何使用Receipt检查用户是否有有效订阅? (我是否需要解析收据并获取expires_date
上次交易的最后product subscription
?)
2.每次启动应用程序时刷新收据是否正常?(这样我可以检查用户是否取消了他的订阅),如果不是,我什么时候需要刷新收据?
PS。如果我有错误的概念或问题,请引导我走正确的道路。提前致谢
答案 0 :(得分:0)
对于答案来说可能为时已晚,但最后,我一直在研究类似的问题。但是,我必须在本地解析并验证收据,这在我看来更好,因为您不需要额外进行http呼叫。
我已经实施了一个小型库,以简化在本地使用应用内收据。
随意使用。 Github link
以下是解决问题的示例:
import TPInAppReceipt
do {
let receipt = try InAppReceiptManager.shared.receipt()
//retrive active auto renewable subscription for a specific product and date
let purchase = receipt.activeAutoRenewableSubscriptionPurchases(ofProductIdentifier: "ProductName", forDate: Date())
//retrive all auto renewable subscription purchases for a specific product
let allAutoRenewableSubscriptionPurchases = receipt.purchases(ofProductIdentifier: "productName").filter({ return $0.isRenewableSubscription })
} catch {
print(error)
}