<?php namespace Pay\Lib;
use Dever;
# 苹果内购支付验证接口 代码摘自网络
class Apple extends Core
{
	/**
	 * 检测
	 */
	public function check($receipt_data, $account_id, $project_id, $uid, $username, $product_id, $name, $cash, $order_id = false)
	{
        $this->log('苹果支付-初始化', $receipt_data);
		$type = 'wechat';
		$order_id = $this->createOrder($uid, $username, $account_id, $project_id, $product_id, $name, $cash, $type, $order_id);

		if (strlen($receipt_data) < 20) {
            $this->updateOrder($order_id, $cash, '参数非法');
			Dever::alert('参数非法');
		}
		
		$result = $this->curl($receipt_data);

		//如果是沙盒数据 则验证沙盒模式  
		if ($result['status'] == 21007) {
			$result = $this->curl($receipt_data, true);    
	        $result['sandbox'] = 1;	
		}

		// 判断是否购买成功   
	    if (intval($result['status']) === 0) {
            $this->updateOrder($order_id, $cash);
            $result['yes'] = 1;
	    } else {   
	       	$this->updateOrder($order_id, $cash, 'error');
            $result['yes'] = 2;
	    }
		return $result;
	}

	private function curl($receipt_data, $sandbox = false)
	{
		//小票信息
        $input = array("receipt-data" => $receipt_data);
        $post = json_encode($input);
    
        //正式购买地址 沙盒购买地址
        $url_buy     = "https://buy.itunes.apple.com/verifyReceipt";
        $url_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt";
        $url = $sandbox ? $url_sandbox : $url_buy;
    
        //简单的curl
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        $result = curl_exec($ch);
        curl_close($ch);
        $input['url'] = $url;
        $this->log('苹果支付-调用苹果接口', $input);
        return Dever::json_decode($result);
	}
}