在Swift 3中实现收据验证

6

我正在使用Swift 3开发iOS应用程序,并尝试根据此教程实现收据验证:http://savvyapps.com/blog/how-setup-test-auto-renewable-subscription-ios-app。但是,该教程似乎是使用早期版本的Swift编写的,因此我不得不进行几个更改。这是我的receiptValidation()函数:

func receiptValidation() {
    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 postString = "receipt-data=" + receiptString! + "&password=" + SUBSCRIPTION_SECRET
        let storeURL = NSURL(string:"https://sandbox.itunes.apple.com/verifyReceipt")!
        let storeRequest = NSMutableURLRequest(url: storeURL as URL)
        storeRequest.httpMethod = "POST"
        storeRequest.httpBody = postString.data(using: .utf8)
        let session = URLSession(configuration:URLSessionConfiguration.default)
        let task = session.dataTask(with: storeRequest as URLRequest) { data, response, error in
            do{
                let jsonResponse:NSDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
                let expirationDate:NSDate = self.expirationDateFromResponse(jsonResponse: jsonResponse)!
                self.updateIAPExpirationDate(date: expirationDate)
            }
            catch{
                print("ERROR: " + error.localizedDescription)
            }
        }
        task.resume()
    }
}

当我尝试调用expirationDateFromResponse()方法时出现了问题。结果发现传递给该方法的jsonResponse仅包含:status = 21002;。我查阅资料得知,这意味着“receipt-data属性中的数据格式不正确或缺失”。但是,我测试的设备有一个有效的沙箱订阅产品,除了这个问题以外,订阅似乎运行正常。我还需要做些其他事情来确保receiptData值会被正确地读取和编码,或者存在其他可能引起此问题的问题吗?
编辑:
我尝试了一种替代设置storeRequest.httpBody的方式:
func receiptValidation() {
    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)) //.URLEncoded
        let dict = ["receipt-data":receiptString, "password":SUBSCRIPTION_SECRET] as [String : Any]
        var jsonData:Data?
        do{
            jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
        }
        catch{
            print("ERROR: " + error.localizedDescription)
        }
        let storeURL = NSURL(string:"https://sandbox.itunes.apple.com/verifyReceipt")!
        let storeRequest = NSMutableURLRequest(url: storeURL as URL)
        storeRequest.httpMethod = "POST"
        storeRequest.httpBody = jsonData!
        let session = URLSession(configuration:URLSessionConfiguration.default)
        let task = session.dataTask(with: storeRequest as URLRequest) { data, response, error in
            do{
                let jsonResponse:NSDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
                let expirationDate:NSDate = self.expirationDateFromResponse(jsonResponse: jsonResponse)!
                self.updateIAPExpirationDate(date: expirationDate)
            }
            catch{
                print("ERROR: " + error.localizedDescription)
            }
        }
        task.resume()
    }
}

然而,当我使用这段代码运行应用时,它在到达 jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) 这一行时卡住了。它甚至没有进入catch块,就停止做任何事情了。从网上看到的信息来看,其他人似乎也遇到了在Swift 3中使用JSONSerialization.data设置请求httpBody的问题。


请确保您已经对base64编码的收据中的任何+字符进行了%编码。即将+实例替换为%2b。 - Paulw11
我修改了代码,在receiptString声明之后立即进行了更改,但仍然看到相同的错误。此外,当我打印receiptString时,我注意到它包含许多“/”字符,用于分隔长的base64字符串。这是正确编码时应该的样子吗? - user3726962
我更新了我的Gist,展示了我用于检索收据和编码base64数据的代码。在我的情况下,这将被发送到我的php代码,然后发送到苹果的服务器https://gist.github.com/paulw11/fa76e10f785e055338ce06673787c6d2 - Paulw11
看了你的代码,你发送的数据不正确。你正在将收据和密码作为POST数据发送,但你需要发送一个包含收据和密码的JSON对象。如果你这样做,那么你就不需要担心%编码,这是我需要让它与我的PHP配合工作所需的。 - Paulw11
我不知道为什么,但你的代码对我来说立刻就起作用了。它仍然有待改进,但是这是一个很好的起点,可以让Swift 3上的验证工作起来。顺便说一下,在我的情况下,这是自动续订订阅。 - Vitalii
显示剩余4条评论
6个回答

13

它与Swift 4正常工作

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)")
        }



    }
}

把这段代码放在哪里?AppDelegate.swift中吗?因为我在ViewController.swift中无法使它工作。 - Ghiggz Pikkoro
这只是针对自动续订的吗?还是适用于常规应用内购买? - Yaroslav Dukal
你的密码是什么? - Jeff Bootsholz
1
如果你的AppSecretKey是yourpasswordift,请在iTunes connect的应用内购买设置页面下找到它。 - Rahul Verma

9
我更新了@user3726962的代码,删除了不必要的NS和"crash operators"。现在它看起来更像Swift 3了。
在使用此代码之前,请注意苹果不建议直接进行[设备] <-> [苹果服务器]验证,并要求进行[设备] <-> [您的服务器] <-> [苹果服务器]验证。如果您不担心您的应用内购买被黑客攻击,则可以使用此代码。
更新:使函数通用:它将首先尝试使用Production验证收据,如果失败,则会重复使用Sandbox。它有点臃肿,但应该是相当自包含且独立于第三方的。
func tryCheckValidateReceiptAndUpdateExpirationDate() {
    if let appStoreReceiptURL = Bundle.main.appStoreReceiptURL,
        FileManager.default.fileExists(atPath: appStoreReceiptURL.path) {

        NSLog("^A receipt found. Validating it...")
        GlobalVariables.isPremiumInAmbiquousState = true // We will allow user to use all premium features until receipt is validated
                                                         // If we have problems validating the purchase - this is not user's fault
        do {
            let receiptData = try Data(contentsOf: appStoreReceiptURL, options: .alwaysMapped)
            let receiptString = receiptData.base64EncodedString(options: [])
            let dict = ["receipt-data" : receiptString, "password" : "your_shared_secret"] as [String : Any]

            do {
                let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)

                if let storeURL = Foundation.URL(string:"https://buy.itunes.apple.com/verifyReceipt"),
                    let sandboxURL = Foundation.URL(string: "https://sandbox.itunes.apple.com/verifyReceipt") {
                    var request = URLRequest(url: storeURL)
                    request.httpMethod = "POST"
                    request.httpBody = jsonData
                    let session = URLSession(configuration: URLSessionConfiguration.default)
                    NSLog("^Connecting to production...")
                    let task = session.dataTask(with: request) { data, response, error in
                        // BEGIN of closure #1 - verification with Production
                        if let receivedData = data, let httpResponse = response as? HTTPURLResponse,
                            error == nil, httpResponse.statusCode == 200 {
                            NSLog("^Received 200, verifying data...")
                            do {
                                if let jsonResponse = try JSONSerialization.jsonObject(with: receivedData, options: JSONSerialization.ReadingOptions.mutableContainers) as? Dictionary<String, AnyObject>,
                                    let status = jsonResponse["status"] as? Int64 {
                                        switch status {
                                        case 0: // receipt verified in Production
                                            NSLog("^Verification with Production succesful, updating expiration date...")
                                            self.updateExpirationDate(jsonResponse: jsonResponse) // Leaves isPremiumInAmbiquousState=true if fails
                                        case 21007: // Means that our receipt is from sandbox environment, need to validate it there instead
                                            NSLog("^need to repeat evrything with Sandbox")
                                            var request = URLRequest(url: sandboxURL)
                                            request.httpMethod = "POST"
                                            request.httpBody = jsonData
                                            let session = URLSession(configuration: URLSessionConfiguration.default)
                                            NSLog("^Connecting to Sandbox...")
                                            let task = session.dataTask(with: request) { data, response, error in
                                                // BEGIN of closure #2 - verification with Sandbox
                                                if let receivedData = data, let httpResponse = response as? HTTPURLResponse,
                                                    error == nil, httpResponse.statusCode == 200 {
                                                    NSLog("^Received 200, verifying data...")
                                                    do {
                                                        if let jsonResponse = try JSONSerialization.jsonObject(with: receivedData, options: JSONSerialization.ReadingOptions.mutableContainers) as? Dictionary<String, AnyObject>,
                                                            let status = jsonResponse["status"] as? Int64 {
                                                            switch status {
                                                                case 0: // receipt verified in Sandbox
                                                                    NSLog("^Verification succesfull, updating expiration date...")
                                                                    self.updateExpirationDate(jsonResponse: jsonResponse) // Leaves isPremiumInAmbiquousState=true if fails
                                                                default: self.showAlertWithErrorCode(errorCode: status)
                                                            }
                                                        } else { DebugLog("Failed to cast serialized JSON to Dictionary<String, AnyObject>") }
                                                    }
                                                    catch { DebugLog("Couldn't serialize JSON with error: " + error.localizedDescription) }
                                                } else { self.handleNetworkError(data: data, response: response, error: error) }
                                            }
                                            // END of closure #2 = verification with Sandbox
                                            task.resume()
                                        default: self.showAlertWithErrorCode(errorCode: status)
                                    }
                                } else { DebugLog("Failed to cast serialized JSON to Dictionary<String, AnyObject>") }
                            }
                            catch { DebugLog("Couldn't serialize JSON with error: " + error.localizedDescription) }
                        } else { self.handleNetworkError(data: data, response: response, error: error) }
                    }
                    // END of closure #1 - verification with Production
                    task.resume()
                } else { DebugLog("Couldn't convert string into URL. Check for special characters.") }
            }
            catch { DebugLog("Couldn't create JSON with error: " + error.localizedDescription) }
        }
        catch { DebugLog("Couldn't read receipt data with error: " + error.localizedDescription) }
    } else {
        DebugLog("No receipt found even though there is an indication something has been purchased before")
        NSLog("^No receipt found. Need to refresh receipt.")
        self.refreshReceipt()
    }
}

func refreshReceipt() {
    let request = SKReceiptRefreshRequest()
    request.delegate = self // to be able to receive the results of this request, check the SKRequestDelegate protocol
    request.start()
}

这适用于自动续订的订阅。还没有测试其他类型的订阅。如果您使用其他类型的订阅,欢迎评论告诉我是否可行。

把这段代码放在哪里?放在AppDelegate.swift文件中吗?因为我在ViewController.swift文件中无法让它正常工作。 - Ghiggz Pikkoro
哦,我明白了。我把它放在我创建的IAP服务类中,并在任何我想要的对象上调用这个方法。谢谢,现在它可以工作了。 - Ghiggz Pikkoro
@GhiggzPikkoro 好问题。简短的回答是肯定的。但你也可以在这里检查我的答案中的更新代码,它会处理“沙盒与生产环境”问题,期望并处理 21007 的代码,这意味着“该收据来自沙盒,请到那里检查它,伙计”。P.S.抱歉它仍然在Swift 3上,希望它可以转换到4。 - Vitalii
好的,谢谢你的更新答案,我会尝试一下,你帮了我很多。 - Ghiggz Pikkoro
@NikhilPandey,我现在已经添加了refreshReceipt函数。但是我不能在这里添加所有的IAP管理例程,因为代码会太多。我的代码是针对问题中特定情况的答案,对于IAP实现一般有很多教程和帖子在网络上,由比我更有经验的人准备。 - Vitalii
显示剩余6条评论

5

//太低的声望无法评论

Yasin Aktimur,谢谢您的回答,非常棒。然而,从苹果文档上看,他们建议在单独的队列上连接到iTunes。因此应该像这样:

func receiptValidation() {

    let SUBSCRIPTION_SECRET = "secret"
    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 base64encodedReceipt = receiptData?.base64EncodedString(options: NSData.Base64EncodingOptions.endLineWithCarriageReturn)
        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 queue = DispatchQueue(label: "itunesConnect")
            queue.async {
                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, options: .allowFragments) as? NSDictionary
                            print("success. here is the json representation of the app receipt: \(appReceiptJSON)")    
                        } catch let error as NSError {
                            print("json serialization failed with error: \(error)")
                        }
                    } else {
                        print("the upload task returned an error: \(error ?? "couldn't upload" as! Error)")
                    }
                }
                task.resume()
            }

        } catch let error as NSError {
            print("json serialization failed with error: \(error)")
        }
    }
}

把这段代码放在哪里?放在AppDelegate.swift文件中吗?因为我在ViewController.swift文件中无法让它正常工作。 - Ghiggz Pikkoro
好的,我应该问我的朋友谷歌什么,帮我构造一个句子,我的英语很糟糕,翻译器也无法帮助我。 - Ghiggz Pikkoro
你会从多个类中调用这个函数吗?如果是的话,将此函数公开到一个单独的文件中,以保持代码整洁。如果不是,则将其放在你的类中,在购买完成后调用它一次即可。 - Not Batman

2
我曾为同样的问题苦恼过。问题出在这行代码上:
let receiptString = receiptData?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))

返回一个可选的并且可能为null的对象。
jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)

无法处理可选项。因此,要修复它,只需将第一行代码替换为以下内容:

let receiptString:String = receiptData?.base64EncodedString(options: NSData.Base64EncodingOptions.lineLength64Characters) as String!

一切都将像魔法般运作!


这很奇怪,但是你的解决方案返回错误21002,而问题中给出的原始代码却可以完美运行(即使receiptString是可选的)。我没有投反对票,因为根据购买类型或其他我尚未了解的事项可能会有一些微妙的差异,所以某人仍然可能会发现这个答案有用。 - Vitalii
@VitaliiTymoshenko 在原问题中,receiptData 是可选的,不能传递给 JSONSerialization.data(...)。也许你的问题是另一个。 - Pablo Romeu
您建议的代码使用了.lineLength64Characters。我已经仔细检查过,使用此选项从Data获取String会对我产生21002错误。我同意原始代码中有Optional(我在调试时清楚地看到了它),但我也很惊讶它在某种程度上居然能正常工作。因此,最终我使用了默认的编码方法-receiptData.base64EncodedString(options: [])。请在我的下面回答中查看完整的代码。 - Vitalii
把这段代码放在哪里?放在AppDelegate.swift文件中吗?因为我在ViewController.swift文件中无法让它正常工作。 - Ghiggz Pikkoro
@GhiggzPikkoro,请阅读原始问题。原始代码位于:https://savvyapps.com/blog/how-setup-test-auto-renewable-subscription-ios-app - Pablo Romeu
这是浪费时间的大事。 - JBarros35

1

我喜欢您的答案,我为那些像我一样使用C#的人重新编写了它,因为我没有找到一个好的解决方案来源。 再次感谢 对于可消耗性IAP

void ReceiptValidation()
    {
        var recPath = NSBundle.MainBundle.AppStoreReceiptUrl.Path;
        if (File.Exists(recPath))
        {
            NSData recData;
            NSError error;

            recData = NSData.FromUrl(NSBundle.MainBundle.AppStoreReceiptUrl, NSDataReadingOptions.MappedAlways, out error);

            var recString = recData.GetBase64EncodedString(NSDataBase64EncodingOptions.None);

            var dict = new Dictionary<String,String>();
            dict.TryAdd("receipt-data", recString);

            var dict1 = NSDictionary.FromObjectsAndKeys(dict.Values.ToArray(), dict.Keys.ToArray());
            var storeURL = new NSUrl("https://sandbox.itunes.apple.com/verifyReceipt");
            var storeRequest = new NSMutableUrlRequest(storeURL);
            storeRequest.HttpMethod = "POST";

            var jsonData = NSJsonSerialization.Serialize(dict1, NSJsonWritingOptions.PrettyPrinted, out error);
            if (error == null)
            {
                storeRequest.Body = jsonData;
                var session = NSUrlSession.FromConfiguration(NSUrlSessionConfiguration.DefaultSessionConfiguration);
                var tsk = session.CreateDataTask(storeRequest, (data, response, err) =>
                {
                    if (err == null)
                    {
                        var rstr = NSJsonSerialization.FromObject(data);

                    }
                    else
                    {
                        // Check Error
                    } 
                });
                tsk.Resume();
            }else
            {
                // JSON Error Handling
            }
        }
    }

0
最终,我通过让我的应用程序调用一个用Python编写的Lambda函数来解决了问题,如this答案所示。我仍然不确定我的Swift代码出了什么问题,或者如何完全在Swift 3中完成这个任务,但无论如何,Lambda函数都得到了期望的结果。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接