Skip to content

Instantly share code, notes, and snippets.

@jay18001
Created March 3, 2019 04:37
Show Gist options
  • Save jay18001/1c2cd715769a2daa7828ec618bf59868 to your computer and use it in GitHub Desktop.
Save jay18001/1c2cd715769a2daa7828ec618bf59868 to your computer and use it in GitHub Desktop.
verifies apple app store receipt using vapor
//
// ReceiptController.swift
// App
//
// Created by Justin Anderson on 3/2/19.
//
import Foundation
import Vapor
fileprivate enum Website: String {
case reciptSandbox = "https://sandbox.itunes.apple.com/verifyReceipt"
case recipt = "https://buy.itunes.apple.com/verifyReceipt"
var url: URL {
return URL(string: self.rawValue)!
}
}
final class ReceiptController {
private static var appleJsonDecoder: JSONDecoder = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss 'Etc/'zzz"
let jsonDecoder = JSONDecoder()
jsonDecoder.dataDecodingStrategy = .base64
jsonDecoder.dateDecodingStrategy = .formatted(dateFormatter)
return jsonDecoder
}()
func verify(request: Request, receipt: ReceiptData) throws -> Future<AppleReceiptResponse> {
let website: Website = receipt.environment == .production ? .recipt : .reciptSandbox
let userAgent = UserAgentUtilites.userAgent(from: request)
let httpHeaders = HTTPHeaders([.contentType : "application/json"])
return try request.client().post(website.url, headers: httpHeaders) { (request) in
let appleRequest = ReceiptRequest(data: receipt.data)
try request.content.encode(json: appleRequest)
}.map { (receiptResponse) in
guard let body = receiptResponse.http.body.data else {
throw Abort(.failedDependency)
}
return try ReceiptController.appleJsonDecoder.decode(AppleReceiptResponse.self, from: body)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment