原文地址:http://blog.csdn.net/toss156/article/details/7043304
<?php
//服務器二次驗證代碼
function getReceiptData($receipt, $isSandbox = false)
{
if ($isSandbox) {
$endpoint = 'https://sandbox.itunes.apple.com/verifyReceipt';
}
else {
$endpoint = 'https://buy.itunes.apple.com/verifyReceipt';
}
$postData = json_encode(
array('receipt-data' => $receipt)
);
$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0); //這兩行一定要加,不加會報SSL 錯誤
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$errmsg = curl_error($ch);
curl_close($ch);
//判斷時候出錯,拋出異常
if ($errno != 0) {
throw new Exception($errmsg, $errno);
}
$data = json_decode($response);
//判斷返回的數據是否是對象
if (!is_object($data)) {
throw new Exception('Invalid response data');
}
//判斷購買時候成功
if (!isset($data->status) || $data->status != 0) {
throw new Exception('Invalid receipt');
}
//返回產品的信息
return array(
'quantity' => $data->receipt->quantity,
'product_id' => $data->receipt->product_id,
'transaction_id' => $data->receipt->transaction_id,
'purchase_date' => $data->receipt->purchase_date,
'app_item_id' => $data->receipt->app_item_id,
'bid' => $data->receipt->bid,
'bvrs' => $data->receipt->bvrs
);
}
//獲取 App 發送過來的數據,設置時候是沙盒狀態
$receipt = $_GET['data'];
$isSandbox = true;
//開始執行驗證
try
{
$info = getReceiptData($receipt, $isSandbox);
// 通過product_id 來判斷是下載哪個資源
switch($info['product_id']){
case 'com.application.xxxxx.xxxx':
Header("Location:xxxx.zip");
break;
}
}
//捕獲異常
catch(Exception $e)
{
echo 'Message: ' .$e->getMessage();
}
?>