How do I validate receipts on the server in Swift?

Validating receipts on the server is crucial for ensuring that in-app purchases are legitimate. This example demonstrates how to validate the receipts from an iOS application using Swift and a simple server-side script.

To validate receipts, you typically send the receipt data to your server, where it checks with Apple’s servers. Below is a simple PHP script that you can use for receipt validation.

<?php // Apple receipt verification URL $verificationUrl = "https://buy.itunes.apple.com/verifyReceipt"; // Use sandbox URL for testing // Get the receipt from the request $json = file_get_contents('php://input'); $receiptData = json_decode($json)->receipt_data; // Prepare data for verification $postData = json_encode(array( 'receipt-data' => $receiptData, 'password' => 'your_shared_secret', // Your app's shared secret )); // Initialize CURL $ch = curl_init($verificationUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json' )); // Execute CURL request $response = curl_exec($ch); curl_close($ch); // Decode response $responseData = json_decode($response, true); // Check status if ($responseData['status'] === 0) { echo "Receipt is valid."; } else { echo "Receipt is invalid."; } ?>

Swift iOS receipt validation server-side validation PHP in-app purchases Apple server