如何为iOS应用实施iOS自动续订订阅收据验证

gbo*_*tha 3 in-app-purchase ios auto-renewing receipt-validation swift2

我想发布一个具有自动续订订阅的iOS应用。尽管有大量有关此方面的信息,但很多信息已经过时了,因此我将陈述到目前为止所取得的成就。

  1. 我正在使用Swift 2.0,因此任何客观的C代码都无济于事。

  2. 我不会使用自己的服务器与Apple进行通讯以验证收据,因此我相信我需要使应用程序直接与Apple服务器进行通讯,或者我可以在设备上本地解析收据。

  3. 我可以使用以下代码在设备上找到收据(不确定是否有多张收据)

    func checkForReceipt() {
        let receiptUrl = NSBundle.mainBundle().appStoreReceiptURL
    
        let fileExists = NSFileManager.defaultManager().fileExistsAtPath(receiptUrl!.path!)
    
        if fileExists {
    
            let receiptData = NSData(contentsOfURL: receiptUrl!)
    
            //Now what do I do to decode the data and validate the receipt
    
        } else{
            requestReceipt()
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

但是,我无法弄清楚如何对收据进行解码,因此可以确定到期日期和其他验证步骤以确保它是有效的收据。

我不得不说,令人沮丧的是,对于开发人员来说非常重要和有用的事情必须如此难以遵循和定位。我们非常感谢您的帮助,希望对其他许多人有所帮助。

小智 5

这是我发现有帮助的链接

如果我的代码不清楚,请参考它

以下是用于检查ar-iap订阅状态的功能代码

请在下面进一步阅读以获取有关每个对应*的一些额外信息*作为注释

func checkForReceipt() {
    let receiptUrl = NSBundle.mainBundle().appStoreReceiptURL

    let fileExists = NSFileManager.defaultManager().fileExistsAtPath(receiptUrl!.path!)

    if fileExists {

        let receiptData = NSData(contentsOfURL: receiptUrl!)

        let receiptToString = receiptData!.base64EncodedStringWithOptions([])
        let dict = ["receipt-data" : receiptToString, "password" : "YOUR SHARED SECRET"] //**
        do {
            let request = try NSJSONSerialization.dataWithJSONObject(dict, options: []) as NSData!
            let storeURL = NSURL(string:"https://sandbox.itunes.apple.com/verifyReceipt")! //***
            let storeRequest = NSMutableURLRequest(URL: storeURL)
            storeRequest.HTTPMethod = "POST"
            storeRequest.HTTPBody = request

            let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
            let dataTask = session.dataTaskWithRequest(storeRequest, completionHandler: { (data: NSData?, response: NSURLResponse?, connection: NSError?) -> Void in
                do {
                    let jsonResponse: NSDictionary = try (NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary)!
                    //****
                    let expDate: NSDate = self.expirationDateFromResponse(jsonResponse)!
                    print(expDate)
                } catch {
                     //handle NSJSONSerialization errors
                }

            })
            dataTask.resume()
        } catch {
            //handle NSJSONSerialization errors
        }
    } else {
        requestReceipt()
    }
}
Run Code Online (Sandbox Code Playgroud)

**您可以从iTunes Connect帐户获取共享密钥:转到MyApps>“您的应用名称”>功能>查看共享密钥>生成共享密钥,然后将您生成的密钥插入dict的密码字段中

*** 投入生产时,请确保将storeURL更改为“ https://buy.itunes.apple.com/verifyReceipt

**** expirationDateFromResponse(jsonResponse:NSDictionary)-> NSDate?是读取苹果的json响应并返回ar iap的到期日期的函数