ios 8, Swift, receipt validation for IAP

喜夏-厌秋 提交于 2019-12-04 14:43:36

So. You problem is simple. You watch on response header instead body. Watch data. Also instead response method better use .responseJSON(options: [], completionHandler:) method, see my code

func validateReceipt() {
    if let receipt =  NSBundle.mainBundle().appStoreReceiptURL {
        if let data = NSData(contentsOfURL: receipt) {
            let requestContents:[String:String] = ["receipt-data":data.base64EncodedStringWithOptions([]), "password": "YOU_SHARED_SECRET"]
            let requestData = try! NSJSONSerialization.dataWithJSONObject(requestContents,options: [])
            let request = NSMutableURLRequest(URL: NSURL(string: "https://sandbox.itunes.apple.com/verifyReceipt")!)
            request.HTTPMethod = "POST"
            request.HTTPBody = requestData
            let (param, _) = Alamofire.ParameterEncoding.URL.encode(request, parameters: nil)

            Alamofire.request(param)
                .responseJSON(options: [], completionHandler: { (result) -> Void in
                    print(result)
                })
        }
    }
}

Thanks @R00We

Swift 5 , and Alamofire (5.0.0-beta.7)

  func validateReceipt() {
        guard let receiptURL = Bundle.main.appStoreReceiptURL, let data = try? Data(contentsOf: receipt ) else {
              return
        }

        let model = ApplePayModel(receipt: data.base64EncodedString(options: []), "password": "YOU_SHARED_SECRET")

        AF.request( "https://sandbox.itunes.apple.com/verifyReceipt" , method: HTTPMethod.post, parameters: model, encoder: JSONParameterEncoder.prettyPrinted, headers: <Your Header, maybe be nil > ).response { (response: DataResponse<Data?>) in

            if let data = response.data{
                 // JSONSerialization it
            }

        }
 }

Use request<Parameters: Encodable>,

struct ApplePayModel: Encodable{
    let receipt: String
    let order_id: String


    private enum CodingKeys: String, CodingKey {
        case receipt = "receipt-data", order_id
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!