<?php
// +----------------------------------------------------------------------
// | Sunnyi 多语商城建站系统 (Build on ThinkPHP)
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://www.sunnyi.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 商易网络(admin@sunnyi.cn)
// +----------------------------------------------------------------------

// 贝宝支付模型
class PaypalPayment extends Think implements Payment {

	public function getPaymentCode($payment_log_id, $money, $payment_id, $currency_id)
	{
		$payment_info = D("Payment")->getById($payment_id);
		$payment_info['config'] = unserialize($payment_info['config']);
		$currency = M("Currency")->where("id=".$currency_id)->find();
		C("URL_MODEL",0);
		$data_return_url = "http://".$_SERVER['SERVER_NAME'].U("Payment/response",array('payment_name'=>'Paypal'));
		$data_notify_url = "http://".$_SERVER['SERVER_NAME'].U("Payment/response",array('payment_name'=>'Paypal'));
		$cancel_return = "http://".$_SERVER['SERVER_NAME'].U("Payment/cancel",array('payment_name'=>'Paypal'));
		$cancel_return = '';

		$payment_log = M("PaymentLog")->getById($payment_log_id);
		$data_sn = D($payment_log['rec_module'])->where("id=".$payment_log['rec_id'])->getField("sn");  //数据的单号
		
		$def_url  = '<form style="text-align:center;" action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank">' .   // 不能省略
            "<input type='hidden' name='cmd' value='_xclick'>" .                             // 不能省略
            "<input type='hidden' name='business' value='".$payment_info['config']['paypal_account']."'>" .                 // 贝宝帐号
            "<input type='hidden' name='item_name' value='".$data_sn."'>" .                 // payment for
            "<input type='hidden' name='amount' value='".$money."'>" .                        // 订单金额
            "<input type='hidden' name='currency_code' value='".$payment_info['config']['paypal_currency']."'>" .            // 货币
            "<input type='hidden' name='return' value='$data_return_url'>" .                    // 付款后页面
            "<input type='hidden' name='invoice' value='".$payment_log_id."'>" .                      // 订单号
            "<input type='hidden' name='charset' value='utf-8'>" .                              // 字符集
            "<input type='hidden' name='no_shipping' value='1'>" .                              // 不要求客户提供收货地址
            "<input type='hidden' name='no_note' value=''>" .                                  // 付款说明
            "<input type='hidden' name='notify_url' value='$data_notify_url'>" .
            "<input type='hidden' name='rm' value='2'>" .
            "<input type='hidden' name='cancel_return' value='$cancel_return'>" .
            "<input type='submit' value='" . L("PAYPAL_PAYMENT_BUTTON") . "'>" .                      // 按钮
            "</form>";
		$def_url.="<br />".L("TOTAL_PRICE").":".$currency['unit']." ".number_format($money,2);
		return $def_url;
	}
	
	public function dealResult($get,$post,$request)
	{
		
		  //验证功能存在bug，善未实现
//        $req = 'cmd=_notify-validate';
//        foreach ($post as $key => $value)
//        {
//            $value = urlencode(stripslashes($value));
//            $req .= "&$key=$value";
//        }
//        echo $req."<br /><br />"; 
//		 // post back to PayPal system to validate
//        $header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
//        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
//        $header .= "Content-Length: " . strlen($req) ."\r\n\r\n";
//        $fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30);
//        if (!$fp)
//        {
//            fclose($fp);
//            return false;
//        }
//        else
//        {
//            fputs($fp, $header . $req);
//            while (!feof($fp))
//            {
//                $res = fgets($fp, 1024);
//                dump($res);               
//            }
//             fclose($fp);
//        }
//        exit;
        
		
		$return_res = array(
			'info'=>'',
			'status'=>false,
		);
		$payment   =  D("Payment")->where("class_name='Paypal'")->find();   
    	$payment['config'] = unserialize($payment['config']);
        $merchant_id    = $payment['config']['paypal_account'];               ///获取商户编号
        $currency_radio = D("Currency")->where("id=".$payment['currency'])->getField("radio");
        
        // assign posted variables to local variables
        $item_name = $post['item_name'];
        $item_number = $post['item_number'];
        $payment_status = $post['payment_status'];
        $payment_amount = floatval($post['mc_gross']);
        $payment_currency = $post['mc_currency'];
        $txn_id = $post['txn_id'];
        $receiver_email = $post['receiver_email'];
        $payer_email = $post['payer_email'];
        $data_id = $post['invoice'];


        $payment_log_info = M("PaymentLog")->getById($data_id);
        //开始查询金额
		switch($payment_log_info['rec_module'])
		{
			case 'UserIncharge':
				$field = 'money';
				break;
			case 'Order':
				$field = 'order_total_price';
				break;
		}
		$total_price = D($payment_log_info['rec_module'])->where("id=".$payment_log_info['rec_id'])->getField($field);
		$total_price *= $currency_radio;
        
        //开始初始化参数
        $payment_log_id = $data_id;
    	$money = $payment_amount;
    	$payment_id = $payment['id'];
    	$currency_id = $payment['currency']; 

		if ($payment_status != 'Completed' && $payment_status != 'Pending')
	         {
				$return_res['info'] = L("PAYMENT_NO_SUCCESS");	
	         }
	    elseif ($receiver_email != $merchant_id)
	         {
	             $return_res['info'] = L("PAYMENT_ACCOUNT_NOT_MATCH");	
	         }         
	    elseif (number_format($total_price,2)!=number_format($payment_amount,2))
	         {         	
	             $return_res['info'] = L("PAYMENT_AMOUNT_ERROR");	
	         }
	    elseif ($payment['config']['paypal_currency'] != $payment_currency)
	         {
	             $return_res['info'] = L("PAYMENT_AMOUNT_ERROR");
	         }
	    else
	    {
	    	return order_paid($payment_log_id,$money,$payment_id,$currency_id);   
	    }
        
         return $return_res;           
	}
}
?>