Skip to content

Instantly share code, notes, and snippets.

@ren6
Created June 17, 2019 14:19
Show Gist options
  • Save ren6/c028daccced54fe2c4ce1347485bee45 to your computer and use it in GitHub Desktop.
Save ren6/c028daccced54fe2c4ce1347485bee45 to your computer and use it in GitHub Desktop.
func refreshSubscriptionsStatus(callback : @escaping SuccessBlock, failure : @escaping FailureBlock){
// save blocks for further use
self.refreshSubscriptionSuccessBlock = callback
self.refreshSubscriptionFailureBlock = failure
guard let receiptUrl = Bundle.main.appStoreReceiptURL else {
refreshReceipt()
// do not call block yet
return
}
#if DEBUG
let urlString = "https://sandbox.itunes.apple.com/verifyReceipt"
#else
let urlString = "https://buy.itunes.apple.com/verifyReceipt"
#endif
let receiptData = try? Data(contentsOf: receiptUrl).base64EncodedString()
let requestData = ["receipt-data" : receiptData ?? "", "password" : self.sharedSecret, "exclude-old-transactions" : true] as [String : Any]
var request = URLRequest(url: URL(string: urlString)!)
request.httpMethod = "POST"
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
let httpBody = try? JSONSerialization.data(withJSONObject: requestData, options: [])
request.httpBody = httpBody
URLSession.shared.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
if data != nil {
if let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments){
self.parseReceipt(json as! Dictionary<String, Any>)
return
}
} else {
print("error validating receipt: \(error?.localizedDescription ?? "")")
}
self.refreshSubscriptionFailureBlock?(error)
self.cleanUpRefeshReceiptBlocks()
}
}.resume()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment