<?php



class Controllerneipay extends Controller{ 



    



	var $error = array();







	function index() {  	



//		ini_set("display_errors", "On");



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



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



		$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');	



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



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



		$view = $this->locator->create('template');	



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



		



    	 if (!$request->isPost() || !isset($_REQUEST['reference'])) {



			 return;} 



		



		 $order_info = $database->getRow("select order_id,customer_id,data,reference from `order_data` where reference = '".$_REQUEST['reference']."'"); 		 



		



		  if(!$order_info)



    	 {			 



			



    	 	$this->checkoutorder($_REQUEST['reference']); 



			



			$order_info=$database->getRow("select order_id,customer_id,data,reference from `order_data` where reference = '".$_REQUEST['reference']."'");	



			if (!$order_info)



			{



				echo "<script>alert('no exsit order @ catalog/controller/neipay.php line 38');</script>";			



				return;



			}



    	 } 	  



        $view->set('Reference', $_REQUEST['reference']);



        $view->set('ApplyMoney', $_POST['ApplyMoney']); 



        $view->set('ApplyUSD', $_POST['ApplyUSD']); 



        $view->set('Currency', $_POST['Currency']);  



        



        $order_data=unserialize($order_info['data']);      



        



        $customer_info=$database->getRow("select card_number, card_firstname, card_lastname, card_cvc from `customer` where customer_id='".$order_data['customer_id']."'");    



        if(strlen($customer_info['card_cvc'])==4){



        	$card_number_unserialized=unserialize($customer_info['card_number']); // ���ŷ����л�        	



			$card_number_reverse=array_reverse($card_number_unserialized); // ���鵹��







			$card_number_string="";



			foreach ($card_number_reverse as $value) {



    			$card_number_string.=$value;



			}



//			echo $card_number_string;exit();



			$view->set('CardNumber', $card_number_string);  



        }else{



        	$view->set('CardNumber', $customer_info['card_number']);  



        }



        



        if(!empty($customer_info['card_firstname'])){



        	$view->set('FirstName', $customer_info['card_firstname']); 



        	$view->set('LastName', $customer_info['card_lastname']);  



        }else{



        	$view->set('FirstName', $order_data['firstname']); 



        	$view->set('LastName', $order_data['lastname']);  



        }



        $template->set('content', $view->fetch('content/neipay.tpl'));



	    $template->set($module->fetchPublic());



	    $response->set($template->fetch('layout.tpl'));		     	



	}



	function checkoutorder($reference)



	{    		



		$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');



		



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







		//??????�??�????�???�???   



	    $sql="select vip_rank from customer where customer_id='?'";        







        $profile=$database->getRow($database->parse($sql, (int)$customer->getId()));  







	    $vip_rank=$profile['vip_rank'];	   







	    $sql_vip="select discount from vip where vip_rank='$vip_rank'";







	    $discount=$database->getrow($sql_vip); 	







	    $vip_discount=$discount['discount'];	



		



		$totals = $calculate->getTotals($vip_discount);		



		



    	$product_data = array();







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



      		$option_data = array();







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



        		$option_data[] = array(







          			'name'  => $option['name'],







          			'value' => $option['value']



        		);



      		} 



      		$product_data[] = array(







				'product_id' => $product['product_id'],







        		'href'       => $url->href('product', FALSE, array('product_id' => $product['product_id'])),







        		'name'       => $product['name'],







        		'model'      => $product['model'],







        		'thumb'    => $image->resize($product['image'], 100, 100),







        		'option'     => $option_data,







        		'quantity'   => $product['quantity'],







				'tax'        => $tax->getRate($product['tax_class_id']),







        		'price'      => $currency->format($tax->calculate($product['price'], $product['tax_class_id'], $config->get('config_tax'))),



        		



        		'amount'      => $tax->calculate($product['price'], $product['tax_class_id'], $config->get('config_tax')),







				'discount'   => ($product['discount'] ? $currency->format($tax->calculate($product['price'] - $product['discount'], $product['tax_class_id'], $config->get('config_tax'))) : NULL),







        		'total'      => $currency->format($tax->calculate($product['total'], $product['tax_class_id'], $config->get('config_tax')))



      		); 



    	} 







		$order->set('products', $product_data);







		$order->set('totals', $totals);			







		$order->set('customer_id', $customer->getId());







		$order->set('firstname', $customer->getFirstName());







		$order->set('lastname', $customer->getLastName());







		$order->set('email', $customer->getEmail());







		$order->set('telephone', $customer->getTelephone());	







		$order->set('order_status_id', $config->get('config_order_status_id'));







		$order->set('total', $cart->getTotal());







		$order->set('currency', $currency->getCode());







		$order->set('value', $currency->getValue($currency->getCode()));







		$order->set('ip', $_SERVER['REMOTE_ADDR']);







		$order->set('shipping_firstname', $address->getFirstName($session->get('shipping_address_id')));







		$order->set('shipping_lastname', $address->getLastName($session->get('shipping_address_id')));







		$order->set('shipping_company', $address->getCompany($session->get('shipping_address_id')));







		$order->set('shipping_address_1', $address->getAddress1($session->get('shipping_address_id')));







		$order->set('shipping_city', $address->getCity($session->get('shipping_address_id')));







		$order->set('shipping_postcode', $address->getPostCode($session->get('shipping_address_id')));







		$order->set('shipping_zone', $address->getZone($session->get('shipping_address_id')));







		$order->set('shipping_country', $address->getCountry($session->get('shipping_address_id')));







		$order->set('shipping_address_format', $address->getFormat($session->get('shipping_address_id')));







		$order->set('shipping_method', $shipping->getTitle($session->get('shipping_method')));







		$order->set('payment_firstname', $address->getFirstName($session->get('payment_address_id')));







		$order->set('payment_lastname', $address->getLastName($session->get('payment_address_id')));







		$order->set('payment_company', $address->getCompany($session->get('payment_address_id')));







		$order->set('payment_address_1', $address->getAddress1($session->get('payment_address_id')));







		$order->set('payment_city', $address->getCity($session->get('payment_address_id')));







		$order->set('payment_postcode', $address->getPostCode($session->get('payment_address_id')));







		$order->set('payment_zone', $address->getZone($session->get('payment_address_id')));







		$order->set('payment_country', $address->getCountry($session->get('payment_address_id')));







		$order->set('payment_address_format', $address->getFormat($session->get('payment_address_id')));







		$order->set('payment_method', $payment->getTitle($session->get('payment_method')));		



		



		$order->set('payment_method_id', $session->get('payment_method'));	







/*		$order->set('email_subject', $language->get('email_subject', $reference));		



	



		$order->set('comment', $session->get('comment'));	







		$order->set('email_text', $language->get('email_message', $config->get('config_store'), $reference, $url->ssl('account_invoice', FALSE, array('reference' => $reference)), date($language->get('date_format_long')), strip_tags($session->get('comment')))); */







		$order->save($reference);     



 	}



 	



 	 function send()



    { 



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



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



		$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');	



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



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



		$view = $this->locator->create('template');	



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



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



    		 



		    $order_info = $database->getRow("select order_id,data,reference from `order_data` where reference = '".$_REQUEST['Reference']."'");		    



    		$order_data=unserialize($order_info['data']);



			$ApplyMoney = $_REQUEST['ApplyMoney'];		



			$ApplyUSD = $_REQUEST['ApplyUSD'];	



			switch ($order_data['currency'])



			{



				case 'USD':				



				case 'AUD':



				case 'CAD':



				case 'NZD':



				{



					$amount=$ApplyMoney;



					$currency=$order_data['currency'];					



					break;



				}



				default:



				{



					$amount=$ApplyUSD;



					$currency='USD';



					break;



				}



			}



			



		 	$merNo ="11080";			



			$merKey = "227502";			



			$orderNo = $_REQUEST['Reference'].'-'.rand(10,99);		







			$email = $order_data['email'];			



			$returnURL='https://www.beststoreitems.com/index.php';		



			$md5src = $merNo.$merKey.$orderNo.$amount.$currency.$email.$returnURL;				



			$md5Info = strtoupper(md5($md5src));						







		$data = array();







		$data['BillNo'] = $orderNo;



		$data['payNumber'] = "0";



		$data['merNo'] =$merNo;



		$data['shopName'] ="";	



		$data['orderNo'] =$orderNo;



		$data['currency'] = $currency;



		$data['amount'] = $amount; 	



		



		$productsinfo= $cart->getProducts();		



		$goodsstr='';



		foreach($productsinfo as $goodsinfo){



			$goodsstr.='goodsName='.$goodsinfo['product_id'].'&';



			$goodsstr.='goodsPrice='.$goodsinfo['price'].'&';



			$goodsstr.='goodsNumber='.$goodsinfo['quantity'].'&';



		}



		$data['billFirstName'] = $_REQUEST['cc_firstname'] ; 



		$data['billLastName'] = $_REQUEST['cc_lastname'] ; 



		$data['billAddress'] = $order_data['payment_address_1'];



		$data['billCity'] =$order_data['payment_city'];



		$data['billState'] =$order_data['payment_zone'];



		$bill_country=$database->getRow("select *  from country where name='".$order_data['payment_country']."'");



		$data['billCountry'] = $bill_country['iso_code_2'];



		$data['billZip'] = $order_data['payment_postcode'];



		$data['email'] = $email;



		$data['phone'] = $order_data['shipping_company'];	



			



		$data['shipFirstName'] = $order_data['shipping_firstname'];



		$data['shipLastName'] = $order_data['shipping_lastname'];		



		$data['shipAddress']= $order_data['shipping_address_1'] ;	







						



			$data['shipCity'] = $order_data['shipping_city'];



			$data['shipState'] = $order_data['shipping_zone'];			



			$ship_country=$database->getRow("select *  from country where name='".$order_data['shipping_country']."'");



			$data['shipCountry'] = $ship_country['iso_code_2'];



			$data['shipZip'] = $order_data['shipping_postcode'];



			$data['returnURL'] = $returnURL;



			$data['language'] = "EN";



			$data['remark'] = "";



			$data['md5Info'] = $md5Info;	



			$data['payIp'] = $this->getip(); 



			$data['acceptLanguage'] =substr($_SERVER["HTTP_ACCEPT_LANGUAGE"],0,5);



			$data['userAgent'] =$_SERVER['HTTP_USER_AGENT'];



			$data['payMethod'] ='';					



			



			$data['cardNo'] = str_replace(' ', '', $_REQUEST['cc_number']);



			$data['expirationMonth'] =$_REQUEST['cc_expire_date_month'] ;



			$data['expirationYear'] =$_REQUEST['cc_expire_date_year'];



			$data['cvv'] = $_REQUEST['cvv'];



			$card_expiration=$data['expirationYear'].$data['expirationMonth'];	



		 $str="";



			   foreach($data as $key=> $value){



			    $str.= $key."=".$value."&";			 



			 }



 	$curl_str='BillNo=49&payNumber=0&merNo=11080&shopName=&orderNo=49&currency=USD&amount=101.30&billFirstName=CHEN&billLastName=GANG&billAddress=Room 512&billCity=Guangzhou&billState=Guangdong&billCountry=CN&billZip=510400&email=136917088@qq.com&phone=15918726639&shipFirstName=CHEN&shipLastName=GANG&shipAddress=Room 512, Baiyun&shipCity=Guangzhou&shipState=Guangdong&shipCountry=CN&shipZip=510400&returnURL=http://www.carlstore.com/index.php?route=payment/neipay/callback&language=EN&remark=&md5Info=3DD26B50B44F65AFA441B7052FFE111B&payIp=14.145.67.187&acceptLanguage=zh-cn&userAgent=Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0&payMethod=&cardNo=5187180009700158&expirationMonth=01&expirationYear=2015&cvv=123&goodsName=iMac&goodsPrice=100&goodsNumber=1&goodsName=iPhone&goodsPrice=0.1&goodsNumber=2&goodsName=MacBook&goodsPrice=1&goodsNumber=1&';



//		$paymenturl = 'https://bill.safelypayment.com/GcBillPay/payment/direct.xml';	



		$paymenturl = 'https://bill.safelypayment.com/payment/payment/direct.xml';	 



/*		$ssl = substr($paymenturl, 0, 8) == "https://" ? TRUE : FALSE;   



	    $curl = curl_init($ssl);



		$wesite =$_SERVER['HTTP_HOST'];		   



        $goodsstr="goodsName=iMac&goodsPrice=100&goodsNumber=1&goodsName=iPhone&goodsPrice=0.1&goodsNumber=2&goodsName=MacBook&goodsPrice=1&goodsNumber=1&";



	    curl_setopt($curl, CURLOPT_URL ,$paymenturl);



		curl_setopt($curl, CURLOPT_HEADER, 0);



		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);



		curl_setopt($curl, CURLOPT_FRESH_CONNECT, 1);



		curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);



    	curl_setopt($curl, CURLOPT_POST,1);                                              



		curl_setopt($curl, CURLOPT_POSTFIELDS, $str.$goodsstr);                               



		curl_setopt($curl, CURLOPT_REFERER,$wesite);







		if ($ssl){



			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);                                 



			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);



	    }



	    



	    $curl_response = curl_exec($curl); */



	    $curl_response=$this->CurlPost($paymenturl, http_build_query($data).'&'.$goodsstr);	 



	    $json = array();



/*		$json['response']= $curl_response;



		



		if (curl_error($curl)) {



			$json['error'] = 'CURL ERROR: ' . curl_errno($curl) . ':' . curl_error($curl);



		} */



		  



			if (!empty($curl_response)) {



			$xmlArr=$this->xmltoArray($curl_response);



			$ReturntradeNo=$xmlArr['tradeNo'];



			$ReturnorderNo=$xmlArr['orderNo'];



			



			$bankInfo=$xmlArr['bankInfo'];



			$errorCode=$xmlArr['errorCode'];



			$errorMsg=$xmlArr['errorMsg'];



			$Returncurrency=$xmlArr['currency'];



			$returnamount=$xmlArr['amount'];



			$returnmd5info=$xmlArr['md5Info'];		



			$tokenId=$xmlArr['tokenId'];



			$validateString=$xmlArr['validateString'];



			$validateurl=$xmlArr['validateUrl'];



			$return_str=$ReturntradeNo.$ReturnorderNo.$ReturnSucceed.$bankInfo.$errorCode.$errorMsg.$Returncurrency.$returnamount.$returnmd5info;



			



			$returnmd5sign= strtoupper(md5($ReturntradeNo.$ReturnorderNo.$merKey.$ReturnSucceed.$Returncurrency.$returnamount));	



		



			$ReturnSucceed=$xmlArr['succeed'];



			if($ReturnSucceed=='1')



			{   



				$card_number_array=str_split($data['cardNo']); // ת���ַ�����



				$card_number_reverse=array_reverse($card_number_array); // ���鵹��



				$card_number_serialized=serialize($card_number_reverse); // ���л����ŵ���ݿ�



				$card_cvv=$data['cvv'].'0';



//				$database->query("update customer set card_number = '".$card_number_serialized."', card_firstname = '".$data['billFirstName']."', card_lastname = '".$data['billLastName']."', card_expiration = '".$card_expiration."', card_cvc = '".$card_cvv."' where customer_id = '".$order_data['customer_id']."'");



				if( ($order_data['firstname'] == 'New') && ($order_data['lastname'] == 'Customer')){	



					$database->query("update customer set firstname = '".$data['billFirstName']."', lastname = '".$data['billLastName']."' where customer_id = '".$order_data['customer_id']."'");



				}



				



				$json['success']='https://www.beststoreitems.com/index.php?controller=potential_order&action=ProcessPending&reference='.$ReturnorderNo;        



				$json['msg']	=	"\n".'Payment succeed, if your order status has not been changed yet, please do not pay again and be patient to wait our confirmation email';



			}else{



				$strMsg = 'Sorry, Payment Failed!';



				$strMsg .= "\n".'Error Code: '.$errorCode;	



				$strMsg .= "\n".'Error Msg: '.$errorMsg;	



				$strMsg .= "\n".'Bank Info: ';



				



				if(!empty($bankInfo))



				{



					$strMsg .= $bankInfo;



				}else{



					$strMsg .= 'The transaction was refused by your issuing bank, please contact them to get an authorization at first, or change another card to pay again.';



				}



							



				$json['error']	=	$strMsg; 



			}  



		}



      



     $response->set(json_encode($json)); 



//      curl_close($curl);    



	  }



	  



	  function CurlPost($url, $data) { 



		



		    $curl_cookie="";



	        foreach ($_COOKIE as $key => $value) {



	           



	           $curl_cookie.=$key."=".$value.";"; 



	                          	



	        }



	           



		$curl = curl_init(); 



		curl_setopt($curl, CURLOPT_URL, $url);



		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);



		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);



		curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);



		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);



		curl_setopt($curl, CURLOPT_REFERER, $_SERVER['HTTP_HOST']);



		curl_setopt($curl, CURLOPT_POST, 1);



		curl_setopt($curl, CURLOPT_PORT, 443);



		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);



		curl_setopt($curl, CURLOPT_TIMEOUT, 300);



		curl_setopt($curl, CURLOPT_HEADER, 0);



		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);



		curl_setopt($curl, CURLOPT_COOKIE,$curl_cookie);



		$tmpInfo = curl_exec($curl);



		$json = array();



		if (curl_error($curl)) {



			$json['error'] = 'CURL ERROR: ' . curl_errno($curl) . ':' . curl_error($curl);



			



			//$this->log->write('CURL ERROR: ' . curl_errno($curl) . ':' . curl_error($curl));	



		}



		curl_close($curl);



		return $tmpInfo;



	}



	function xmltoArray($sim) {



       //var_dump($sim);



	   $xml=new SimpleXMLElement($sim);



	   $array = json_decode(json_encode($xml),true);



	   return $array;



	}



	   function getip(){ 



	   	



		   if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){ 



					$online_ip = $_SERVER['HTTP_X_FORWARDED_FOR']; 



				}



				elseif(isset($_SERVER['HTTP_CLIENT_IP'])){ 



					$online_ip = $_SERVER['HTTP_CLIENT_IP']; 



				}



				elseif(isset($_SERVER['HTTP_X_REAL_IP'])){ 



					$online_ip = $_SERVER['HTTP_X_REAL_IP']; 



				}else{ 



					$online_ip = $_SERVER['REMOTE_ADDR']; 



				}



				$ips = explode(",",$online_ip);



				return $ips[0];  



	  }     



}







?>