苹果官方购买产品服务器端验证代码PHP版

苹果官方购买产品服务器端验证代码PHP版


<?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_SSL_VERIFYPEER, FALSE);

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);   

curl_setopt($ch, CURLOPT_POST, true);   

curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);   


$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,   

'item_id'        =>  $data->receipt->item_id,   

'bid'            =>  $data->receipt->bid,   

'bvrs'           =>  $data->receipt->bvrs   

);   

}   


/**

 * 测试代码

 */

$isSandbox = true;

$receipt = base64_encode($_POST['receipt']);

try {

$info = getReceiptData($receipt, $isSandbox);  

//验证购买有效   

print_r($info);

} catch (Exception $ex) {   

print_r($ex);

//验证购买无效   

echo '无效购买凭证';

}   


你可能感兴趣的:(服务器,产品,苹果)