IAP实际验证收据(Swift) [英] IAPs actually validating the receipt (Swift)

查看:141
本文介绍了IAP实际验证收据(Swift)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在我的spritekit游戏中实现收据验证。我一直在关注各种教程,基本上结束了这段代码

I have been trying to implement receipt validation in my spritekit game. I have been following various tutorial and basically ended up with this code

enum RequestURL: String {
   case production = "https://buy.itunes.apple.com/verifyReceipt"
   case sandbox = "https://sandbox.itunes.apple.com/verifyReceipt"
   case myServer = "my server address"
}

enum ReceiptStatusCode: Int {

// Not decodable status
case unknown = -2

// No status returned
case none = -1

// valid status
case valid = 0

// The App Store could not read the JSON object you provided.
case JSONNotReadable = 21000

// The data in the receipt-data property was malformed or missing.
case malformedOrMissingData = 21002

// The receipt could not be authenticated.
case receiptCouldNotBeAuthenticated = 21003

// The shared secret you provided does not match the shared secret on file for your account.
// Only returned for iOS 6 style transaction receipts for auto-renewable subscriptions.
case sharedSecretNotMatching = 21004

// The receipt server is currently not available.
case receiptServerUnavailable = 21005

// This receipt is valid but the subscription has expired. When this status code is returned to your server, the receipt data is also decoded and returned as part of the response.
// Only returned for iOS 6 style transaction receipts for auto-renewable subscriptions.
case subscriptionExpired = 21006

//  This receipt is from the test environment, but it was sent to the production environment for verification. Send it to the test environment instead.
case testReceipt = 21007

// This receipt is from the production environment, but it was sent to the test environment for verification. Send it to the production environment instead.
case productionEnvironment = 21008
 }

  func validateReceipt(forTransaction transaction: SKPaymentTransaction) {

    guard let receiptURL = NSBundle.mainBundle().appStoreReceiptURL else { return }

    guard let receipt = NSData(contentsOfURL: receiptURL) else { return }

    let receiptData = receipt.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
    let payload = ["receipt-data": receiptData]

    var receiptPayloadData: NSData?

    do {
        receiptPayloadData = try NSJSONSerialization.dataWithJSONObject(payload, options: NSJSONWritingOptions(rawValue: 0))
    }
    catch let error as NSError {
        print(error.localizedDescription)
        return
    }

    guard let payloadData = receiptPayloadData else { return }
    guard let requestURL = NSURL(string: RequestURL.sandbox.rawValue) else { return }

    let request = NSMutableURLRequest(URL: requestURL)
    request.HTTPMethod = "POST"
    request.HTTPBody = payloadData

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
         if let error = error {
            print(error.localizedDescription)
            return
        }  
         guard let data = data else { return }          

         do {
            let jsonData = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves) as? NSDictionary

            guard let json = jsonData else { return }

            // Correct ?
            guard let status = json["status"] as? Int where status == ReceiptStatusCode.valid.rawValue else { return }

            // Unlock product here?
            // Other checks needed?
        }

        catch let error as NSError {
            print(error.localizedDescription)
            return
        }
     }

    task.resume()
}

这是漂亮的锅炉板代码,可以作为预期。我现在的问题是我不知道如何在最后一步(标记线)实际验证收据。
我相信我现在必须进行5次左右的检查以验证收据。我不知道他们中的大部分将如何在swift中完成。大多数教程都是旧的,不包括这一步或不是用swift编写的。

It is pretty boiler plate code and works as expected. My issue now is that I dont know how to actually validate the receipt at last step (marked line). I believe I have to now carry 5 or so checks to validate the receipt. I just have no idea how most of them would be done in swift. The majority of tutorials are either old, dont include this step or are not written in swift.

如果有人成功使用收据验证可以帮助我朝着正确的方向前进非常感谢。非常感谢

If anyone that successfully uses receipt validation could help me get going in the right direction it would be much appreciated. Thank you very much

更新:

在JSA986I和cbartel得到很好的答案后,我把它变成了一个帮手在github上。非常感谢您的帮助

After the great answers from JSA986I and cbartel I turned this into a helper on github. Many thanks for the help

https://github.com / crashoverride777 / SwiftyReceiptValidator

推荐答案

这就是您将收据作为JSON返回并可以访问它的地方。 ie

Thats is where you return your receipt as JSON and can access it. ie

if parseJSON["status"] as? Int == 0 {
                       println("Sucessfully returned purchased receipt data")
                    }

会告诉您是否已成功收到收据,因为 [status] 0 表示已退回确定

Will tell you if you have successfully got the receipt because ["status"] 0 means its been returned ok

您可以进一步查询和使用收据数据来查找和使用JSON响应中的项目。在这里你可以打印最新的收据信息

You can further query and use the receipt data to find and use items from the JSON response. Here you can print the latest receipt info

if let receiptInfo: NSArray = parseJSON["latest_receipt_info"] as? NSArray {
                       let lastReceipt = receiptInfo.lastObject as! NSDictionary

                        // Get last receipt
                        println("LAST RECEIPT INFORMATION \n",lastReceipt)
}

现在你要使用你的json数据

Now you have your json data to use

你现在可以查询那些数据,在这个例子中我们是从JSOn回复中查找订阅到期的自动续订订阅

You can now query that data, in this example we are finding out when the subscription expires of an auto renew subscription form the JSOn response

 // Format date
 var formatter = NSDateFormatter()
 formatter.dateFormat = "yyyy-MM-dd HH:mm:ss VV"
 formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")

 // Get Expiry date as NSDate
 let subscriptionExpirationDate: NSDate = formatter.dateFromString(lastReceipt["expires_date"] as! String) as NSDate!
  println("\n   - DATE SUBSCRIPTION EXPIRES = \(subscriptionExpirationDate)")

发布上面的代码

if let parseJSON = json {
                println("Receipt \(parseJSON)")

这篇关于IAP实际验证收据(Swift)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆