<?php



class ControllerPaypalExpress extends Controller { 







	var $error = array();



	



    var $API_USER = array();



    var $PP_SERVER  = array();



    var $is_test = 0;       // sandbox



    var $conf = array();



    



    function __construct(&$locator) {



        $this->locator =& $locator;



        $this->conf['HTTP_SERVER'] = "https://www.beststoreitems.com/";



        if($this -> is_test == 0) {                     



            $this->API_USER['API_username']  = 'minazhang100_api1.gmail.com';



            $this->API_USER['API_password']  = 'BSXP636SNL7M4MZ2';



            $this->API_USER['API_signature'] = 'Avdbaxrux.xw.6wxWP-RT..2cguYA4B0Yk5.wrkvdUf0Y2DmzJR9XOtB';



            



            $this->PP_SERVER['PP_SETEXPRESSCHECKOUT_URL'] = 'https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=';



            $this->PP_SERVER['PP_API_NVP_URL'] = 'https://api-3t.paypal.com/nvp';



            $this->PP_SERVER['PP_IPN_URL'] = 'https://www.paypal.com/cgi-bin/webscr';







        } elseif($this -> is_test == 1) {   // use sandbox



            $this->API_USER['PP_BUSINESS_USERNAME']  = '454sadas_api1.gmail.com';



            $this->API_USER['PP_BUSINESS_PASSWORD']  = '1384263877';



            $this->API_USER['PP_BUSINESS_SIGNATURE'] = 'An5ns1Kso7MWUdW4ErQKJJJ4qi4-AhrpapUZY-noiUa55OZbPf4Ene3H';



            



            $this->PP_SERVER['PP_SETEXPRESSCHECKOUT_URL'] = 'https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=';



            $this->PP_SERVER['PP_API_NVP_URL'] = 'https://api-3t.sandbox.paypal.com/nvp';



            $this->PP_SERVER['PP_IPN_URL'] = 'https://www.sandbox.paypal.com/cgi-bin/webscr';



        }



//      exit("__construct");



    }







    // 支付入口



    // index.php?controller=pp_express&action=checkout



    function checkout() {



 



        $config    = & $this->locator->get('config');



        $customer  = & $this->locator->get('customer');



        $database  = & $this->locator->get('database');



        $language  = & $this->locator->get('language');



        $order     = & $this->locator->get('order');



        $request   = & $this->locator->get('request');



        $response  = & $this->locator->get('response');



        $cart      = & $this->locator->get('cart');



        $session   = & $this->locator->get('session');



        $url       = & $this->locator->get('url');



        $currency  = & $this->locator->get('currency');



        $conf      = $this -> conf;







        $session->delete('shipping_method');      



        $session->delete('payment_method');



      



        if ( !$cart->hasProducts() || !$cart->hasStock() ) {



            $response->redirect("index.php?controller=cart");



        }



            		



        $set_data = array(



            'METHOD'             => 'SetExpressCheckout',



            'VERSION'             => 109.0,          



            'RETURNURL'          => $this->conf['HTTP_SERVER']."index.php?controller=paypal_express&action=callGetExpressCheckoutDetails",



            'CANCELURL'          => $this->conf['HTTP_SERVER']."payment/paypal/paypal_cancel.html",



            'PAYMENTREQUEST_0_PAYMENTACTION'  =>'Sale',



            'ALLOWNOTE'  =>1



            



        );



         



        $set_data = array_merge($set_data, $this->requestPaymentFields());







        $set_result = $this->execCurl($set_data);



      print_r($set_result);exit;



        /**



         * If a failed PayPal setup happens, handle it.



         */



        if (!isset($set_result['TOKEN'])) {



         



            $response->redirect($HTTP_SERVER. "index.php?controller=cart");



        }



        $session -> set('paypal_token', $set_result['TOKEN']);



        $url = $this->PP_SERVER['PP_SETEXPRESSCHECKOUT_URL'] . $set_result['TOKEN'] . '&useraction=commit';



        header('Location: ' . $url);



    }



      



    function execCurl($data) {       







    	// Append API_USER



    	$data=array_merge($data, $this->API_USER);



    	



        $defaults = array(



            CURLOPT_POST => 1,



            CURLOPT_HEADER => 0,



            CURLOPT_URL => $this->PP_SERVER['PP_API_NVP_URL'],



            CURLOPT_USERAGENT => "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1",



            CURLOPT_FRESH_CONNECT => 1,



            CURLOPT_RETURNTRANSFER => 1,



            CURLOPT_FORBID_REUSE => 1,



            CURLOPT_TIMEOUT => 0,



            CURLOPT_SSL_VERIFYPEER => 0,



            CURLOPT_SSL_VERIFYHOST => 0,



            CURLOPT_POSTFIELDS => http_build_query($data, '', "&")



        );







        $ch = curl_init();







        curl_setopt_array($ch, $defaults);







        if (!$result = curl_exec($ch)) {



            exit('error: ' . curl_error($ch) . 'cURL failed');



        }







        curl_close($ch);



//print_r($result);exit;



        return $this->parseCurlResult($result);



    }



    



   function parseCurlResult($data) {



   	



        $data = explode('&', $data);







        $arr = array();







        foreach ($data as $k=>$v) {



            $tmp = explode('=', $v);



            $arr[$tmp[0]] = urldecode($tmp[1]);



        }







        return $arr;



    }



  



     function callGetExpressCheckoutDetails() {



     	



        $config    = & $this->locator->get('config');



        $customer  = & $this->locator->get('customer');



        $database  = & $this->locator->get('database');



        $language  = & $this->locator->get('language');



        $order     = & $this->locator->get('order');



        $request   = & $this->locator->get('request');



        $response  = & $this->locator->get('response');



        $cart      = & $this->locator->get('cart');



        $session   = & $this->locator->get('session');



        $url       = & $this->locator->get('url');



        $currency  = & $this->locator->get('currency');



        $conf      = $this -> conf;



        /**



         * This is the url when PayPal has completed the payment authorization.



         *



         * you should get the buyer's infomation by appending extra fields



         */



        $get_data = array(



            'METHOD' => 'GetExpressCheckoutDetails',



            'TOKEN'  => $session -> get('paypal_token'),



        );







        $get_result = $this->execCurl($get_data);



//        $session->set('paypal_payerid', $get_result['PAYERID']);







		// show the confirmation page for customer



     



    }







    function callDoExpressCheckoutPayment(){



    	



    	   $do_data = array(



            'METHOD'                     => 'DoExpressCheckoutPayment',



            'TOKEN'                      => $session -> get('paypal_token'),



            'PAYERID'                    => $get_result['PAYERID'],



            'PAYMENTREQUEST_0_AMT'=> 100,



            'PAYMENTREQUEST_0_CURRENCYCODE' =>'USD',



            'RETURNFMFDETAILS'           => 1,



            'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale'



        );



       



        $do_result = $this->execCurl($do_data);



        



        if ($do_result['ACK'] == 'Success') {



            //handle order status



            switch($do_result['PAYMENTINFO_0_PAYMENTSTATUS']) {



                case 'Canceled_Reversal':



                    $order_status_id = 1;



                    break;



                case 'Completed':



                    $order_status_id = 2;



                    break;



                case 'Denied':



                    $order_status_id = 3;



                    break;



                case 'Expired':



                    $order_status_id = 4;



                    break;



                case 'Failed':



                    $order_status_id = 5;



                    break;



                case 'Pending':



                    $order_status_id = 6;



                    break;



                case 'Processed':



                    $order_status_id = 7;



                    break;



                case 'Refunded':



                    $order_status_id = 8;



                    break;



                case 'Reversed':



                    $order_status_id = 9;



                    break;



                case 'Voided':



                    $order_status_id = 10;



                    break;



            }



           $session -> delete('paypal_token');



           $cart->clear();







            $response->redirect('https://www.beststoreitems.com/payment/paypal/paypal_success.html');



            if (isset($result['REDIRECTREQUIRED']) && $result['REDIRECTREQUIRED'] == true) {



                //- handle german redirect here



                $this->response->redirect('https://www.paypal.com/cgi-bin/webscr?cmd=_complete-express-checkout&token=' . $session -> get('paypal_token'));



            }



        }



    }







    function requestPaymentFields() {



   	



        $address   =& $this->locator->get('address');







        $calculate =& $this->locator->get('calculate');







        $cart      =& $this->locator->get('cart');







        $config    =& $this->locator->get('config');







        $coupon   =& $this->locator->get('coupon');







        $currency  =& $this->locator->get('currency');







        $customer  =& $this->locator->get('customer');







        $database  =& $this->locator->get('database');







        $language  =& $this->locator->get('language');







        $module    =& $this->locator->get('module');







        $order     =& $this->locator->get('order');







        $payment   =& $this->locator->get('payment');







        $request   =& $this->locator->get('request');







        $session   =& $this->locator->get('session');







        $shipping  =& $this->locator->get('shipping');







        $tax       =& $this->locator->get('tax');







        $template  =& $this->locator->get('template');







        $url       =& $this->locator->get('url');   







        $currency_code='USD'; 



        $item_total=0;



        $total=0;



         switch ($currency->getCode())



			{



				case 'USD':



				case 'DKK':



				case 'ILS':



				case 'RUB':



				case 'CAD':



			    case 'HUF':



			    case 'MXN':



			    case 'NOK':



			    case 'CZK':



			    case 'SGD':



			    case 'NZD':



			    case 'JPY':



			    case 'EUR':



			    case 'PLN':



			    case 'THB':



			    case 'AUD':



			    case 'SEK':	



			    case 'CHF':



			    case 'GBP':



			    case 'PHP':						   



				{



					$currency_code=$currency->getCode();



					$currency_info=$database->getRow("select value from currency where code ='".$currency->getCode()."'");



        		    $item_total=number_format($calculate->getTotalUsd()*$currency_info['value'], 2, '.', ''); 



									



					break;



				}



				default:



				{



					$currency_code='USD'; 



					$item_total=$calculate->getTotalUsd();



					break;



				}



			}



				



		 $total = $item_total;



    



        $data['PAYMENTREQUEST_0_CURRENCYCODE'] = $currency_code;       



        $data['PAYMENTREQUEST_0_ITEMAMT']   =  $item_total;



 		$data['PAYMENTREQUEST_0_AMT']   =  $total;



      



        $products = $cart->getProducts();



        $i=0;



        foreach ($cart->getProducts() as $product) {       



        	    



           $data['L_PAYMENTREQUEST_0_DESC' . $i]='';



           



      		foreach ($product['option'] as $option) {



      			$data['L_PAYMENTREQUEST_0_DESC' . $i] .= ($option['name'].': '.$option['value']);      			



      		}     			



        		



            $data['L_PAYMENTREQUEST_0_NAME' . $i] = $product['name'];



            $data['L_PAYMENTREQUEST_0_NUMBER' . $i] = $product['product_id'];



            $data['L_PAYMENTREQUEST_0_AMT' . $i] = $product['product_id'];           



            $data['L_PAYMENTREQUEST_0_QTY' . $i] = $product['quantity'];



            $data['L_PAYMENTREQUEST_0_ITEMURL' . $i] = 'https://www.beststoreitems.com/index.php?controller=product&product_id='.$product['product_id'];         



            $i++;



        }      







        return $data;



   }  







}



?>



