---
slug: "iOSInAppPurchaseのレシート検証手順"
title: "Steps for Verifying iOS In-App Purchase Receipts"
description: "\n\n\nProcessing on iOS Devices\nIn SKPaymentTransactionObserver's"
url: "https://www.ytyng.com/en/blog/iOSInAppPurchaseのレシート検証手順"
publish_date: "2015-06-30T00:30:51Z"
created: "2015-06-30T00:30:51Z"
updated: "2026-02-27T10:44:39.777Z"
categories: ["iOS"]
keywords: ""
featured_image_url: "https://media.ytyng.com/resize/20230812/2bd80d3f381d458c87c8c871101fb584.png.webp?width=768"
has_video: false
has_music: false
video_urls: []
music_urls: []
lang: "en"
---

# Steps for Verifying iOS In-App Purchase Receipts

<div class="document">

<div class="section" id="ios">
<h3>Processing on iOS Devices</h3>
<p>In SKPaymentTransactionObserver's</p>
<pre class="literal-block">- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
</pre>
<p>If
transaction.transactionState == SKPaymentTransactionStatePurchased
is reached, it means the transaction with Apple has been completed.
(transaction is an element of transactions)</p>
<pre class="literal-block">#pragma mark - SKPaymentTransactionObserver

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
    for (SKPaymentTransaction *transaction in transactions) {
        switch (transaction.transactionState) {
            case SKPaymentTransactionStatePurchasing:
                // Purchasing process
                ...
                break;
            case SKPaymentTransactionStatePurchased:
                // Purchase complete
                [queue finishTransaction:transaction];
                [self purchaseProcedure:transaction];
                break;
            case SKPaymentTransactionStateFailed:
                // Purchase failed
                ...
                [queue finishTransaction:transaction];
                break;
            case SKPaymentTransactionStateRestored:
                // Purchase restored
                ...
                [queue finishTransaction:transaction];
                break;
            default:
                // Leave alone
                [queue finishTransaction:transaction];
                break;
        }
    }
}
</pre>
<p>Upon purchase completion, send the receipt to the server for processing.</p>
<p>There are two types of logs to send to the server:</p>
<pre class="literal-block">- (void)purchaseProcedure:(SKPaymentTransaction *)transaction {
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
    NSString *base64receiptData = [receiptData base64EncodedStringWithOptions:0];

    // Deprecated, but send it just in case
    NSString *base64TransactionReceipt = [transaction.transactionReceipt base64EncodedStringWithOptions:0];
</pre>
<p>Thus, we can create the following strings:</p>
<ul class="simple">
<li>base64receiptData (hereafter referred to as receiptData)</li>
<li>base64TransactionReceipt (hereafter referred to as transactionReceipt)</li>
</ul>
<p>Send these to the server along with transaction.transactionIdentifier.</p>
</div>
<div class="section" id="id1">
<h3>Server-side Processing</h3>
<p>When the server receives these receipt details, it will request Apple for validation.</p>
<p>The code for the receipt validation request looks like this (Python):</p>
<pre class="literal-block">import requests
import json

class AppleReceiptVerifyStatusError(Exception):
    pass

class AppleReceipt(object):
    @staticmethod
    def verify_request(receipt_data):
        url = 'https://buy.itunes.apple.com/verifyReceipt'

        data = {'receipt-data': receipt_data}
        headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
        r = requests.post(url, data=json.dumps(data), headers=headers)
        # print(r.content)
        if r.status_code == 200:
            parsed = json.loads(r.content.decode('utf-8'))
            if parsed['status'] == 21007:
                // It was a test environment transaction
                return AppleReceipt.verify_request_sandbox(receipt_data)
            return parsed
        else:
            raise AppleReceiptVerifyStatusError(r.status_code)

    @staticmethod
    def verify_request_sandbox(receipt_data):
        url = 'https://sandbox.itunes.apple.com/verifyReceipt'

        data = {'receipt-data': receipt_data}
        headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
        r = requests.post(url, data=json.dumps(data), headers=headers)
        # print(r.content)
        if r.status_code == 200:
            return json.loads(r.content.decode('utf-8'))
        else:
            raise AppleReceiptVerifyStatusError(r.status_code)
</pre>
<div class="section" id="receiptdata">
<h4>Validating receiptData</h4>
<p>Replace ' ' with '+' in the receiptData received from the iOS device, and pass it to AppleReceipt.verify_request().</p>
<pre class="literal-block">verify_result = AppleReceipt.verify_request(
    post_data['receiptData'].replace(' ', '+'))
</pre>
<p>Check the following content in the returned verify_result:</p>
<ul class="simple">
<li>verify_result['status'] == 0</li>
<li>verify_result['receipt']['in_app'] is an array with at least one element</li>
</ul>
<p>For elements of verify_result['receipt']['in_app']:</p>
<ul class="simple">
<li>All elements' ['product_id'] should match the products of your app</li>
</ul>
<p>One of the elements should satisfy the following condition:</p>
<ul class="simple">
<li>['transaction_id'] matches the transactionIdentifier at the time of sale</li>
</ul>
<p>If the purchase is not a restore,</p>
<ul class="simple">
<li>['original_transaction_id'] matches the transactionIdentifier at the time of sale</li>
</ul>
<p>* original_transaction_id appears to contain the actual transactionIdentifier at the time of purchase during a restore. I haven't confirmed this since I've only sold non-consumable items.</p>
</div>
<div class="section" id="transactionreceipt">
<h4>Validating transactionReceipt</h4>
<p>This method is deprecated and may become unusable in the future, but it's still possible, so we do it just in case.</p>
<pre class="literal-block">verify_result = AppleReceipt.verify_request(
    post_data['transactionReceipt'])
</pre>
<p>Check the following content in the returned verify_result:</p>
<ul class="simple">
<li>verify_result['status'] == 0</li>
<li>verify_result['receipt']['product_id'] matches the products of your app</li>
<li>verify_result['receipt']['transaction_id'] matches the transactionIdentifier at the time of sale</li>
</ul>
<p>If the purchase is not a restore,</p>
<ul class="simple">
<li>verify_result['receipt']['original_transaction_id'] matches the transactionIdentifier at the time of sale</li>
</ul>
</div>
<div class="section" id="id2">
<h4>Other</h4>
<p>Ensure that the transactionIdentifier is not one that has already been processed (not a replay attack).</p>
</div>
</div>
<div class="section" id="id3">
<h3>Supplement</h3>
<p>Receipt Validation Programming Guide (TP40010573 0.0.0) - ValidateAppStoreReceipt.pdf
<a class="reference external" href="https://developer.apple.com/jp/documentation/ValidateAppStoreReceipt.pdf">https://developer.apple.com/jp/documentation/ValidateAppStoreReceipt.pdf</a></p>
<p>Be careful of tools that crack in-app purchases. Requests from these tools occasionally appear.</p>
<p>There seems to be a tool circulating that can crack in-app purchases and pass Apple's server authentication - @Yoski Hatena Separate Room
<a class="reference external" href="http://yoski.hatenablog.com/entry/2013/03/22/Apple%E3%81%AE%E3%82%B5%E3%83%BC%E3%83%90%E3%83%BC%E8%AA%8D%E8%A8%BC%E3%82%92%E9%80%9A%E9%81%8E%E3%81%99%E3%82%8B%E3%82%A2%E3%83%97%E3%83%AA%E5%86%85%E8%AA%B2%E9%87%91%E3%81%AE%E3%82%AF%E3%83%A9%E3%83%83_">http://yoski.hatenablog.com/entry/2013/03/22/Apple%E3%81%AE%E3%82%B5%E3%83%BC%E3%83%90%E3%83%BC%E8%AA%8D%E8%A8%BC%E3%82%92%E9%80%9A%E9%81%8E%E3%81%99%E3%82%8B%E3%82%A2%E3%83%97%E3%83%AA%E5%86%85%E8%AA%B2%E9%87%91%E3%81%AE%E3%82%AF%E3%83%A9%E3%83%83_</a></p>
</div>
</div>
