Skip to content

Getting the receipt with the latest expiration date

Pablo Rivera edited this page Jul 12, 2016 · 5 revisions

You might have an issue where the receipt you get by using receipt.last_in_app is not the one with the latest expiration date. To solve that, simply iterate over the receipts and get the one with the latest expiration date. The function below does it for you.

This code is added for context:

with itunesiap.env.sandbox:
    request = itunesiap.Request(receipt, password)
    response = request.verify()

The parameter receipts is the value from the key latest_receipt_info. It contains a python list of receipts as dictionaries.

response._.get('latest_receipt_info')

Its important that you use the _ (underscore) because that is how you can access the object data as a dictionary.

def get_newest_receipt(receipts):
    """
    returns the newest receipt (last purchase)

    newest_receipt type is dict
    """
    # extracts the newest receipt
    # from field latest_receipt_info
    # that field has all the raw receipt as dict
    # code uses library utilities to convert dates
    # into native datetime objects
    newest_receipt = None

    for receipt in receipts:

        if not newest_receipt:
            if receipt.get('expires_date'):
                newest_receipt = receipt
                continue

        if receipt.get('expires_date'):
            #compares two datetime native objects to see which receipt expires last
            if _to_datetime(receipt.get('expires_date')) > _to_datetime(newest_receipt.get('expires_date')):
                newest_receipt = receipt

    return newest_receipt

The code above uses the _to_datetime() function from here. This function loads the string datetime into a Python native datetime object.

Now simply do:

newest_receipt = get_newest_receipt(response._.get('latest_receipt_info'))

Remember that the dates in the newest_receipt will be strings. Use the function _to_datetime() to convert them to native python datetime objects.

Example:

expires_date = _to_datetime(newest_receipt.get('expires_date'))