Implementing Receipt Validation in Swift 3

后端 未结 6 690
没有蜡笔的小新
没有蜡笔的小新 2020-12-24 09:59

I am developing an iOS app in Swift 3 and trying to implement receipt validation following this tutorial: http://savvyapps.com/blog/how-setup-test-auto-renewable-subscriptio

6条回答
  •  醉梦人生
    2020-12-24 10:32

    //too low rep to comment

    Yasin Aktimur, thanks for your answer, it's awesome. However, looking at Apple documentation on this, they say to connect to iTunes on a separate Queue. So it should look like this:

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

提交回复
热议问题