Receipt Validation – Parse and Decode a Receipt with Swift

The aim of this guide is to help you parse a receipt and decode it so that you have readable pieces of metadata to inspect and finalize all of the receipt validation steps.

This is a continuation of my receipt validation series. I’m assuming that…

After finishing this guide, you’ll still have to compute the GUID hash of your app to compare with the hash that’s found within the receipt. You’ll also have to inspect the receipt data to perform any app-specific verification steps. But in order to do either, you’ll need the parsed receipt metadata.

Just want the code? Here you go!

Want to understand the final ReceiptParser? Let’s get to it!

The final goal: A parsed receipt

The final goal of this guide is a parsed receipt.

What do you say we start things off by defining what one looks like?

At the end of the day, what we’d like back from the parsing process is a simple struct that contains the various pieces of metadata that are found within the extracted the PKCS #7 container. Things like…

  • the app’s bundle identifier,
  • the original app version that was purchased,
  • a collection of all the in app purchase receipts,
  • etc.

How does the following look?

 1struct ParsedReceipt {
 2    let bundleIdentifier: String?
 3    let bundleIdData: NSData?
 4    let appVersion: String?
 5    let opaqueValue: NSData?
 6    let sha1Hash: NSData?
 7    let inAppPurchaseReceipts: [ParsedInAppPurchaseReceipt]?
 8    let originalAppVersion: String?
 9    let receiptCreationDate: Date?
10    let expirationDate: Date?
11}
12
13struct ParsedInAppPurchaseReceipt {
14    let quantity: Int?
15    let productIdentifier: String?
16    let transactionIdentifier: String?
17    let originalTransactionIdentifier: String?
18    let purchaseDate: Date?
19    let originalPurchaseDate: Date?
20    let subscriptionExpirationDate: Date?
21    let cancellationDate: Date?
22    let webOrderLineItemId: Int?
23}

You may be wondering, “How’d he know what values are encoded within the extracted receipt payload?”. Apple has a very handy list of all the values that are encoded, so I listed each property out in my struct according to their documentation.

Parsing the receipt produces the most valuable piece of the whole process. Sure, it’s necessary to go through all of the other validation steps, but having a decoded receipt with actual human-readable values is, to me, a huge step.

Full disclaimer though: parsing the receipt is not very… Swifty.

We’re going to be working with all kinds of ugly things like UnsafeMutablePointers, and cryptically-named C Types.

Let’s take it one step at a time though…

Visualizing the encoded receipt’s structure

Up to now, we’ve been working only with the PKCS #7 container for the receipt. Now it’s time to dig into the container and see what it actually contains.

If you crack open the container, what you find is a long series of bytes that encode the actual structure of the receipt.

From beginning to end, the bytes should encode what’s called an “ASN.1 Set”. In fact, if you open the PKCS #7 container and it doesn’t encode an ASN.1 Set, that’d warrant a receipt validation failure…more about handling that in a minute.

Here’s a visual representation of an ASN.1 Set:
ASN.1 Set

Since we’ve just got a bunch of bytes encoding things, there’s got to be some way to say, “This byte, or these series of bytes, represent [this human understandable thing]”.

That’s exactly what we’ve got, as you can see by the visual representation.

The first byte in the receipt payload (the green box in the visualization) signals that the bytes that follow encode an ASN.1 Set.

The next bytes in the series (the blue box) encode how long the ASN.1 Set is, so that as you’re going along parsing and decoding the contents of the Set, you know when to stop.

The final series of bytes (the yellow boxes) encode chunks of information that can be decoded to give you human readable receipt attributes. Those chunks, themselves, are encoded as ASN.1 Sequences.

So what does an ASN.1 Sequence look like? Here’s a visual:

ASN.1 Sequence

When it comes to app receipts, ASN.1 Sequences are used to say, “Hey, this series of bytes encodes [the bundle identifier] or [the original app version] or [some other receipt attribute].”

Each ASN.1 Sequence has a flag (the pink box in the visualization) to signal that the bytes that follow do, in fact, encode an ASN.1 Sequence.

Then, just like an ASN.1 Set, the next bytes in line (the blue box) encode how long the Sequence is. Then comes what we’re really after in all this Set/Sequence talk:

The type of attribute (bundle identifier, for example) is encoded next in the series of bytes as an ASN.1 Integer (note that this isn’t a Swift Int…yet…we’ll decode it soon). Each attribute type has a unique ASN.1 Integer value, kind of like an ID. Apple’s documentation is helpful in figuring out which ASN.1 Integer value maps to which receipt attribute.

After the attribute type comes some bytes that encode an “attribute version”, also as an ASN.1 Integer. At the time of this guide’s publication, “attribute version” isn’t used for anything. Nonetheless, the series of bytes right after the attribute type within the ASN.1 Sequence is reserved and will always represent the “attribute version”.

The remaining bytes in the ASN.1 Sequence encode the actual value of the attribute as an ASN.1 Octet String (don’t let the word “Octet String” trick you into thinking that it’s actually a String… they’re bytes that we’ll have to decode shortly…)

Knowing how the receipt payload is structured will help us formulate a strategy around parsing it. Let’s imagine a simple algorithm to do it now.

Receipt parsing strategy

Let’s take it step by step. What if we approach parsing the receipt like this:

1) Do some preliminary checks to ensure that the receipt payload is in the correct structural format (it should be an ASN.1 Set, for example).

2) For each ASN.1 Sequence within the ASN.1 Set, check to see what type of attribute it is.

3) Decode its Octet String value into actual, human-readable values. The decoded values would be represented by Swift Types (Int, String, Date are sufficient to cover all of the possibilities for receipts). The final decoded value depends on what type of attribute it is.

4) Create and return a ParsedReceipt instance as the final product.

If at any point the receipt payload fails to live up to the expected structure, receipt validation will fail, and we can signal that by throwing an error.

A note on in-app purchase receipts

As we follow the receipt parsing strategy steps that I just described, there’s going to come a point where we run into the ASN.1 Sequence that encodes the in-app purchase receipts.

These are special.

In-app purchase receipts are encoded as ASN.1 Sets (with ASN.1 Sequences within) inside the primary ASN.1 Set receipt payload. In other words, they’re nested ASN.1 Sets within the overall ASN.1 Set that encodes the whole receipt. The nested Set contains the in-app purchase receipt attributes.

So in order to decode these, we’ll have to apply the receipt parsing strategy within the receipt parsing strategy. Fun, huh? We’ll only have to do it for the in-app purchase receipt attributes though.

Preparation step: Helper decoding functions

If you saw the ParsedReceipt struct that I proposed earlier in the guide, you’ll notice that there are essentially four Swift Types that the receipt attributes (and in-app purchase receipt attributes) get decoded into:

  • Int?
  • String?
  • NSData?
  • Date?

NSData has a constructor that can work with UnsafeRawPointers directly, but Int?, String?, and Date? need some help converting from the ASN.1 versions of those Types to the Swift versions of those Types.

Let me put the code before you and follow up with what I’m doing here:

 1func DecodeASN1Integer(startOfInt intPointer: inout UnsafePointer<UInt8>?, length: Int) -> Int? {
 2    // These will be set by ASN1_get_object
 3    var type = Int32(0)
 4    var xclass = Int32(0)
 5    var intLength = 0
 6    
 7    ASN1_get_object(&intPointer, &intLength, &type, &xclass, length)
 8    
 9    guard type == V_ASN1_INTEGER else {
10        return nil
11    }
12    
13    let integer = c2i_ASN1_INTEGER(nil, &intPointer, intLength)
14    let result = ASN1_INTEGER_get(integer)
15    ASN1_INTEGER_free(integer)
16    
17    return result
18}
19
20func DecodeASN1String(startOfString stringPointer: inout UnsafePointer<UInt8>?, length: Int) -> String? {
21    // These will be set by ASN1_get_object
22    var type = Int32(0)
23    var xclass = Int32(0)
24    var stringLength = 0
25
26    ASN1_get_object(&stringPointer, &stringLength, &type, &xclass, length)
27    
28    if type == V_ASN1_UTF8STRING {
29        let mutableStringPointer = UnsafeMutableRawPointer(mutating: stringPointer!)
30        return String(bytesNoCopy: mutableStringPointer, length: stringLength, encoding: String.Encoding.utf8, freeWhenDone: false)
31    }
32    
33    if type == V_ASN1_IA5STRING {
34        let mutableStringPointer = UnsafeMutableRawPointer(mutating: stringPointer!)
35        return String(bytesNoCopy: mutableStringPointer, length: stringLength, encoding: String.Encoding.ascii, freeWhenDone: false)
36    }
37    
38    return nil
39}
40
41func DecodeASN1Date(startOfDate datePointer: inout UnsafePointer<UInt8>?, length: Int) -> Date? {
42    // Date formatter code from https://www.objc.io/issues/17-security/receipt-validation/#parsing-the-receipt
43    let dateFormatter = DateFormatter()
44    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
45    dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
46    dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
47    
48    if let dateString = DecodeASN1String(startOfString: &datePointer, length:length) {
49        return dateFormatter.date(from: dateString)
50    }
51    
52    return nil
53}

Each of these decoding functions are dealing with the receipt attribute value portion of the ASN.1 Sequence that we’re working on at the time. Recall the structure:
ASN.1 Sequence

So we take in a pointer that’s pointing to the start of one of the attribute values (a yellow box). The yellow box’s ASN.1 Octet String encodes either an integer, a string, or a date. (Okay, technically I guess you could include NSData, but this doesn’t need to be “decoded” really. And the in-app purchase receipts will be parsed and decoded into the stated Types as well, so it all boils down to the three I just mentioned…thus the reason for only three helper functions).

The strategy for the first two functions is basically to take what we’re pointing to, and call ASN1_get_object.

This function call gets us enough information to decode the bytes from the start of the object to the end of the object into either an Int? or a String?. If it fails, nil is returned.

Decoding dates simply involves initializing a DateFormatter with the appropriate locale and date format. The datePointer parameter actually points to an encoded string, so the strategy is to use the DecodeASN1String function we made, and pass the date string to the date formatter.

So long as the string can be decoded, the date formatter instance is used to create an actual Date? instance and return it. Otherwise, nil is returned.

Handling error conditions

The kinds of errors that can occur when parsing the receipt payload all have to do with unexpected structure.

For example, if we’re expecting to be stepping through an ASN.1 Payload or an ASN.1 Sequence but instead find that it’s not what we expect, this is a situation where reeipt validation should fail, because there’s no way to decode the receipt attributes if the bytes of the payload don’t conform to the expected structure.

In situations where the receipt payload or one of its in-app purchase receipt payloads is “malformed” in some way, we can throw an Error.

I’ve highlighted two new ReceiptValidationError cases here:

1enum ReceiptValidationError : Error {
2    case couldNotFindReceipt
3    case emptyReceiptContents
4    case receiptNotSigned
5    case appleRootCertificateNotFound
6    case receiptSignatureInvalid
7    case malformedReceipt
8    case malformedInAppPurchaseReceipt
9}

Implenting ReceiptParser

OK! We’ve got a few helper functions to decode the receipt attributes, and we’ve got some ReceiptValidationError cases to throw in case parsing fails.

At a very high level, the ReceiptParser will take the following skeletal structure:

 1struct ReceiptParser {
 2    func parse(_ PKCS7Container: UnsafeMutablePointer<PKCS7>) throws -> ParsedReceipt {
 3        var bundleIdentifier: String?
 4        var bundleIdData: NSData?
 5        var appVersion: String?
 6        var opaqueValue: NSData?
 7        var sha1Hash: NSData?
 8        var inAppPurchaseReceipts = [ParsedInAppPurchaseReceipt]()
 9        var originalAppVersion: String?
10        var receiptCreationDate: Date?
11        var expirationDate: Date?
12        
13        // Parse the receipt, setting each variable
14        
15        return ParsedReceipt(bundleIdentifier: bundleIdentifier,
16                             bundleIdData: bundleIdData,
17                             appVersion: appVersion,
18                             opaqueValue: opaqueValue,
19                             sha1Hash: sha1Hash,
20                             inAppPurchaseReceipts: inAppPurchaseReceipts,
21                             originalAppVersion: originalAppVersion,
22                             receiptCreationDate: receiptCreationDate,
23                             expirationDate: expirationDate)
24    }
25    
26    func parseInAppPurchaseReceipt(currentInAppPurchaseASN1PayloadLocation: inout UnsafePointer<UInt8>?, payloadLength: Int) throws -> ParsedInAppPurchaseReceipt {
27        var quantity: Int?
28        var productIdentifier: String?
29        var transactionIdentifier: String?
30        var originalTransactionIdentifier: String?
31        var purchaseDate: Date?
32        var originalPurchaseDate: Date?
33        var subscriptionExpirationDate: Date?
34        var cancellationDate: Date?
35        var webOrderLineItemId: Int?
36        
37        // Parse the in-app purchase receipt, setting each variable
38        
39        return ParsedInAppPurchaseReceipt(quantity: quantity,
40                                          productIdentifier: productIdentifier,
41                                          transactionIdentifier: transactionIdentifier,
42                                          originalTransactionIdentifier: originalTransactionIdentifier,
43                                          purchaseDate: purchaseDate,
44                                          originalPurchaseDate: originalPurchaseDate,
45                                          subscriptionExpirationDate: subscriptionExpirationDate,
46                                          cancellationDate: cancellationDate,
47                                          webOrderLineItemId: webOrderLineItemId)
48    }

So a total of two functions: one to parse the overall receipt, and one to parse each in-app purchase receipt nested within the overall receipt.

Now comes the hard part. Actually doing all the decoding. Don’t forget the strategy we’re going to take! That’ll help you walk through this code without getting insanely overwhelmed (hopefully).

parse function implementation

First, the implementation of parse(_:) with comments throughout to help you find where each step of the strategy is being implemented:

  1func parse(_ PKCS7Container: UnsafeMutablePointer<PKCS7>) throws -> ParsedReceipt {
  2    var bundleIdentifier: String?
  3    var bundleIdData: NSData?
  4    var appVersion: String?
  5    var opaqueValue: NSData?
  6    var sha1Hash: NSData?
  7    var inAppPurchaseReceipts = [ParsedInAppPurchaseReceipt]()
  8    var originalAppVersion: String?
  9    var receiptCreationDate: Date?
 10    var expirationDate: Date?
 11    
 12    // Strategy Step 1: Preliminary structure checks
 13
 14    // Must have data to work with
 15    guard let contents = PKCS7Container.pointee.d.sign.pointee.contents, let octets = contents.pointee.d.data else {
 16        throw ReceiptValidationError.malformedReceipt
 17    }
 18    
 19    // Determine the start and end of the receipt payload
 20    var currentASN1PayloadLocation = UnsafePointer(octets.pointee.data)
 21    let endOfPayload = currentASN1PayloadLocation!.advanced(by: Int(octets.pointee.length))
 22    
 23    var type = Int32(0)
 24    var xclass = Int32(0)
 25    var length = 0
 26    
 27    ASN1_get_object(&currentASN1PayloadLocation, &length, &type, &xclass,Int(octets.pointee.length))
 28    
 29    // Payload must be an ASN1 Set
 30    guard type == V_ASN1_SET else {
 31        throw ReceiptValidationError.malformedReceipt
 32    }
 33    
 34    // Decode Payload
 35    // Strategy Step 2: Walk through payload (ASN1 Set) and parse each ASN1 Sequence 
 36    // within (ASN1 Sets contain one or more ASN1 Sequences)
 37    while currentASN1PayloadLocation! < endOfPayload {
 38        
 39        // Get next ASN1 Sequence
 40        ASN1_get_object(&currentASN1PayloadLocation, &length, &type, &xclass, currentASN1PayloadLocation!.distance(to: endOfPayload))
 41        
 42        // ASN1 Object type must be an ASN1 Sequence
 43        guard type == V_ASN1_SEQUENCE else {
 44            throw ReceiptValidationError.malformedReceipt
 45        }
 46        
 47        // Attribute type of ASN1 Sequence must be an Integer
 48        guard let attributeType = DecodeASN1Integer(startOfInt: &currentASN1PayloadLocation, length: currentASN1PayloadLocation!.distance(to: endOfPayload)) else {
 49            throw ReceiptValidationError.malformedReceipt
 50        }
 51        
 52        // Attribute version of ASN1 Sequence must be an Integer
 53        guard DecodeASN1Integer(startOfInt: &currentASN1PayloadLocation, length: currentASN1PayloadLocation!.distance(to: endOfPayload)) != nil else {
 54            throw ReceiptValidationError.malformedReceipt
 55        }
 56        
 57        // Get ASN1 Sequence value
 58        ASN1_get_object(&currentASN1PayloadLocation, &length, &type, &xclass, currentASN1PayloadLocation!.distance(to: endOfPayload))
 59        
 60        // ASN1 Sequence value must be an ASN1 Octet String
 61        guard type == V_ASN1_OCTET_STRING else {
 62            throw ReceiptValidationError.malformedReceipt
 63        }
 64        
 65        // Strategy Step 3: Decode attributes
 66        switch attributeType {
 67        case 2:
 68            var startOfBundleId = currentASN1PayloadLocation
 69            bundleIdData = NSData(bytes: startOfBundleId, length: length)
 70            bundleIdentifier = DecodeASN1String(startOfString: &startOfBundleId, length: length)
 71        case 3:
 72            var startOfAppVersion = currentASN1PayloadLocation
 73            appVersion = DecodeASN1String(startOfString: &startOfAppVersion, length: length)
 74        case 4:
 75            let startOfOpaqueValue = currentASN1PayloadLocation
 76            opaqueValue = NSData(bytes: startOfOpaqueValue, length: length)
 77        case 5:
 78            let startOfSha1Hash = currentASN1PayloadLocation
 79            sha1Hash = NSData(bytes: startOfSha1Hash, length: length)
 80        case 17:
 81            var startOfInAppPurchaseReceipt = currentASN1PayloadLocation
 82            let iapReceipt = try parseInAppPurchaseReceipt(currentInAppPurchaseASN1PayloadLocation: &startOfInAppPurchaseReceipt, payloadLength: length)
 83            inAppPurchaseReceipts.append(iapReceipt)
 84        case 12:
 85            var startOfReceiptCreationDate = currentASN1PayloadLocation
 86            receiptCreationDate = DecodeASN1Date(startOfDate: &startOfReceiptCreationDate, length: length)
 87        case 19:
 88            var startOfOriginalAppVersion = currentASN1PayloadLocation
 89            originalAppVersion = DecodeASN1String(startOfString: &startOfOriginalAppVersion, length: length)
 90        case 21:
 91            var startOfExpirationDate = currentASN1PayloadLocation
 92            expirationDate = DecodeASN1Date(startOfDate: &startOfExpirationDate, length: length)
 93        default:
 94            break
 95        }
 96        
 97        currentASN1PayloadLocation = currentASN1PayloadLocation?.advanced(by: length)
 98    }
 99    
100    // Strategy Step 4: Return ParsedReceipt
101    return ParsedReceipt(bundleIdentifier: bundleIdentifier,
102                            bundleIdData: bundleIdData,
103                            appVersion: appVersion,
104                            opaqueValue: opaqueValue,
105                            sha1Hash: sha1Hash,
106                            inAppPurchaseReceipts: inAppPurchaseReceipts,
107                            originalAppVersion: originalAppVersion,
108                            receiptCreationDate: receiptCreationDate,
109                            expirationDate: expirationDate)
110}

Aside from the work with pointers and the Open SSL function names, the strategy is pretty straight-forward when you look it from a bird’s-eye point of view.

Once again, if you’re curious about how I knew to map each case within the switch to the correct receipt attribute, I simply got them from Apple’s documentation.

parseInAppPurchaseRectipt function implementation

Now it’s time to see how to parse an in-app purchase receipt payload. Take a look:

  1func parseInAppPurchaseReceipt(currentInAppPurchaseASN1PayloadLocation: inout UnsafePointer<UInt8>?, payloadLength: Int) throws -> ParsedInAppPurchaseReceipt {
  2    var quantity: Int?
  3    var productIdentifier: String?
  4    var transactionIdentifier: String?
  5    var originalTransactionIdentifier: String?
  6    var purchaseDate: Date?
  7    var originalPurchaseDate: Date?
  8    var subscriptionExpirationDate: Date?
  9    var cancellationDate: Date?
 10    var webOrderLineItemId: Int?
 11    
 12    // Find the end of the in-app purchase receipt payload
 13    let endOfPayload = currentInAppPurchaseASN1PayloadLocation!.advanced(by: payloadLength)
 14    var type = Int32(0)
 15    var xclass = Int32(0)
 16    var length = 0
 17    
 18    ASN1_get_object(&currentInAppPurchaseASN1PayloadLocation, &length, &type, &xclass, payloadLength)
 19    
 20    // Payload must be an ASN1 Set
 21    guard type == V_ASN1_SET else {
 22        throw ReceiptValidationError.malformedInAppPurchaseReceipt
 23    }
 24    
 25    // Decode Payload
 26    // Step through payload (ASN1 Set) and parse each ASN1 Sequence within (ASN1 Sets contain one or more ASN1 Sequences)
 27    while currentInAppPurchaseASN1PayloadLocation! < endOfPayload {
 28        
 29        // Get next ASN1 Sequence
 30        ASN1_get_object(&currentInAppPurchaseASN1PayloadLocation, &length, &type, &xclass, currentInAppPurchaseASN1PayloadLocation!.distance(to: endOfPayload))
 31        
 32        // ASN1 Object type must be an ASN1 Sequence
 33        guard type == V_ASN1_SEQUENCE else {
 34            throw ReceiptValidationError.malformedInAppPurchaseReceipt
 35        }
 36        
 37        // Attribute type of ASN1 Sequence must be an Integer
 38        guard let attributeType = DecodeASN1Integer(startOfInt: &currentInAppPurchaseASN1PayloadLocation, length: currentInAppPurchaseASN1PayloadLocation!.distance(to: endOfPayload)) else {
 39            throw ReceiptValidationError.malformedInAppPurchaseReceipt
 40        }
 41        
 42        // Attribute version of ASN1 Sequence must be an Integer
 43        guard DecodeASN1Integer(startOfInt: &currentInAppPurchaseASN1PayloadLocation, length: currentInAppPurchaseASN1PayloadLocation!.distance(to: endOfPayload)) != nil else {
 44            throw ReceiptValidationError.malformedInAppPurchaseReceipt
 45        }
 46        
 47        // Get ASN1 Sequence value
 48        ASN1_get_object(&currentInAppPurchaseASN1PayloadLocation, &length, &type, &xclass, currentInAppPurchaseASN1PayloadLocation!.distance(to: endOfPayload))
 49        
 50        // ASN1 Sequence value must be an ASN1 Octet String
 51        guard type == V_ASN1_OCTET_STRING else {
 52            throw ReceiptValidationError.malformedInAppPurchaseReceipt
 53        }
 54        
 55        // Decode attributes
 56        switch attributeType {
 57        case 1701:
 58            var startOfQuantity = currentInAppPurchaseASN1PayloadLocation
 59            quantity = DecodeASN1Integer(startOfInt: &startOfQuantity , length: length)
 60        case 1702:
 61            var startOfProductIdentifier = currentInAppPurchaseASN1PayloadLocation
 62            productIdentifier = DecodeASN1String(startOfString: &startOfProductIdentifier, length: length)
 63        case 1703:
 64            var startOfTransactionIdentifier = currentInAppPurchaseASN1PayloadLocation
 65            transactionIdentifier = DecodeASN1String(startOfString: &startOfTransactionIdentifier, length: length)
 66        case 1705:
 67            var startOfOriginalTransactionIdentifier = currentInAppPurchaseASN1PayloadLocation
 68            originalTransactionIdentifier = DecodeASN1String(startOfString: &startOfOriginalTransactionIdentifier, length: length)
 69        case 1704:
 70            var startOfPurchaseDate = currentInAppPurchaseASN1PayloadLocation
 71            purchaseDate = DecodeASN1Date(startOfDate: &startOfPurchaseDate, length: length)
 72        case 1706:
 73            var startOfOriginalPurchaseDate = currentInAppPurchaseASN1PayloadLocation
 74            originalPurchaseDate = DecodeASN1Date(startOfDate: &startOfOriginalPurchaseDate, length: length)
 75        case 1708:
 76            var startOfSubscriptionExpirationDate = currentInAppPurchaseASN1PayloadLocation
 77            subscriptionExpirationDate = DecodeASN1Date(startOfDate: &startOfSubscriptionExpirationDate, length: length)
 78        case 1712:
 79            var startOfCancellationDate = currentInAppPurchaseASN1PayloadLocation
 80            cancellationDate = DecodeASN1Date(startOfDate: &startOfCancellationDate, length: length)
 81        case 1711:
 82            var startOfWebOrderLineItemId = currentInAppPurchaseASN1PayloadLocation
 83            webOrderLineItemId = DecodeASN1Integer(startOfInt: &startOfWebOrderLineItemId, length: length)
 84        default:
 85            break
 86        }
 87        
 88        currentInAppPurchaseASN1PayloadLocation = currentInAppPurchaseASN1PayloadLocation!.advanced(by: length)
 89    }
 90    
 91    return ParsedInAppPurchaseReceipt(quantity: quantity,
 92                                        productIdentifier: productIdentifier,
 93                                        transactionIdentifier: transactionIdentifier,
 94                                        originalTransactionIdentifier: originalTransactionIdentifier,
 95                                        purchaseDate: purchaseDate,
 96                                        originalPurchaseDate: originalPurchaseDate,
 97                                        subscriptionExpirationDate: subscriptionExpirationDate,
 98                                        cancellationDate: cancellationDate,
 99                                        webOrderLineItemId: webOrderLineItemId)
100}

As you can see, parsing an in-app purchase receipt uses the same strategy as parsing the overall receipt does.

A receipt may contain zero or more in-app purchase receipts, so this function may get called zero, one, or many times, depending on what your app offers as in-app purchases, and of course, what your users have actually purchased.

Final ReceiptParser

I realize that breaking the code apart like I’ve done is good for teaching purposes, but perhaps not so much for “I just wanna copy-paste and use this” purposes.

I’ll spare you having to scroll through all that code again. If you’d like to see the full ReceiptParser, check out the Swifty Local Receipt Validator repo on GitHub.

Using ReceiptParser

I initialize an instance of ReceiptParser in my ReceiptValidator struct, and then call the parse(_:) function from validateReceipt():

 1enum ReceiptValidationResult {
 2    case success(ParsedReceipt) // Now has ParsedReceipt for an associated value
 3    case error(ReceiptValidationError)
 4}
 5
 6struct ReceiptValidator {
 7    let receiptLoader = ReceiptLoader()
 8    let receiptExtractor = ReceiptExtractor()
 9    let receiptSignatureValidator = ReceiptSignatureValidator()
10    let receiptParser = ReceiptParser()
11    
12    func validateReceipt() -> ReceiptValidationResult {
13        do {
14            let receiptData = try receiptLoader.loadReceipt()
15            let receiptContainer = try receiptExtractor.extractPKCS7Container(receiptData)
16            
17            try receiptSignatureValidator.checkSignaturePresence(receiptContainer)
18            try receiptSignatureValidator.checkSignatureAuthenticity(receiptContainer)
19            
20            let parsedReceipt = try receiptParser.parse(receiptContainer)
21            return .success(parsedReceipt)
22        } catch {
23            return .error(error as! ReceiptValidationError)
24        }
25    }
26}

Preparing to finish receipt validation!

What a journey this has been! We’re almost done with this receipt validation process.

What’s left? After this guide, you still need to…

  • Compute the GUID hash of your app to compare with the hash that’s found within the receipt.
  • You’ll also have to inspect the receipt data to perform any app-specific verification steps.

We’re that much closer now though! See you next time.

comments powered by Disqus