prime31
7/25/2012 - 6:27 PM

PHP receipt validation

PHP receipt validation

<?php

// get input
$receipt = $_POST['receipt'];
$isTest = $_POST['isTest'] == '1';


// prop the post data
$json = json_encode( array( 'receipt-data' => $receipt ) );

// NOTE: use "sandbox" instead of "buy" for testing
$url = 'https://buy.itunes.apple.com/verifyReceipt';
if( $isTest )
	$url = str_replace( 'buy', 'sandbox', $url );

$responseJson = curl( $url, $json );

// send json back to Unity where we will decode it
echo $responseJson;








function curl( $url, $postData )
{
    // is cURL installed yet?
    if( !function_exists( 'curl_init' ) )
        die( 'Sorry cURL is not installed!' );
 
    // OK cool - then let's create a new cURL resource handle
    $ch = curl_init();
 
    // Set URL to download
    curl_setopt( $ch, CURLOPT_URL, $url );
 
    // Include header in result? (0 = yes, 1 = no)
    curl_setopt( $ch, CURLOPT_HEADER, 0 );
 
    // Should cURL return or print out the data? (true = return, false = print)
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	
	// follow redirects
	curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
 
    // Timeout in seconds
    curl_setopt( $ch, CURLOPT_TIMEOUT, 10 );
	
	// post data
	if( $postData && count( $postData ) )
	{
		curl_setopt( $ch, CURLOPT_POST, true );
		curl_setopt( $ch, CURLOPT_POSTFIELDS, $postData );
	}
 
    // Download the given URL, and return output
    $output = curl_exec( $ch );
 
    // Close the cURL resource, and free system resources
    curl_close( $ch );
 
    return $output;
}