<?php



class Controllerdhpay extends Controller {







	var $error = array();



/*****************************************************************************************************************************************************/



	function index() {



//		phpinfo(); exit;







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







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



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



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



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



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



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



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



		



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



			 return;}











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











		  if(!$order_info)



    	 {



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







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



			if (!$order_info)



			{



				echo "<script language=\"JavaScript\">alert(\"Update order failure, return @ catalog/controller/dhpay.php line 38\");</script>";



				return;



			}



    	 }







		 date_default_timezone_set('Asia/Hong_Kong');



		  				$china_time=date('Y-m-d H:i:s',time());



		  				$SubmitTime = str_replace(':',"",str_replace('-',"",$china_time));



		  				$SubmitTime = str_replace(' ',"",$SubmitTime);







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



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



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



	    $merchant_id="200000000118859";



		$invoice_id= str_replace('-',"",$order_info['reference']).rand(1000,9999);//substr($order_info['reference'],-5).rand(1000,9999);







		$order_no=$order_info['order_id'];



		$currency='USD'; //$order_data['currency'];



		$amount=$_POST['ApplyUSD']; //$_POST['ApplyMoney']



//		exit($amount);



		$buyer_email=$order_data['email'];



		$pos1 = strpos($buyer_email, '@');



		$pos2 = strpos($buyer_email, '.');



		if ( ($pos1 === false)|| ($pos2 === false) || empty($buyer_email)) {



			$buyer_email="invaild@email.com";



		}







		$shipping_country=$ship_country['iso_code_2'];



		$first_name=$order_data['firstname'];



		$last_name=$order_data['lastname'];



		$country = $bill_country['iso_code_2'];



		$state=$order_data['payment_zone'];



		$city=$order_data['payment_city'];



		$address_line=$order_data['payment_address_1'];



		$zipcode=trim($order_data['payment_postcode']);



		$zipcode=strlen($zipcode)<4?'12345':$zipcode;



		$zipcode=strlen($zipcode)>10?'12345':$zipcode;







		$return_url=$url->ssl('dhpay_callback'); //"https://www.beststoreitems.com/index.php?controller=dhpay_callback"; //"https://www.beststoreitems.com/payment/dhpay/dhpay_callback.php";







		$remark= substr($order_info['reference'], 0, 5); // $order_info['reference']."-".$_POST['ApplyMoney'].$order_data['currency'];



switch ($order_data['currency'])



			{



				case 'SGD':



				case 'CAD':



				case 'AUD':



//				case 'GBP':



				{



					$currency=$order_data['currency']; 



					$amount=$_POST['ApplyMoney']; 



					



					break;



				}



				default:



					break;



			}



			



		// amount合法性校验



		$amount=$amount<0?1:$amount;



//		foreach ($order_data['products'] as $product){



			$product_name="Super Light Foldable High Landspace Baby Stroller"; //$product['product_id'];



			$product_price=$amount;//number_format($product['price'], 2,'.','');



			$product_quantity=1;//$product['quantity'];



//			break;



//		}







		 $parameter = array(



				"merchant_id"	=> $merchant_id,



				"invoice_id"	=> $invoice_id,



				"order_no"	=> $order_no,



				"currency"	=> $currency,



				"amount"	=> $amount,



				"buyer_email"	=> $buyer_email,



				"shipping_country"	=> $shipping_country,



				"first_name"	=> $first_name,



				"last_name"	=> $last_name,



				"country"	=> $country,



				"state"	=> $state,



				"city"	=> $city,



				"address_line"	=> $address_line,



				"zipcode"	=> $zipcode,



				"product_name"	=> $product_name,



				"product_price"	=> $product_price,



				"product_quantity"	=> $product_quantity,



				"return_url"	=> $return_url,



				"remark"	=> $remark



		);



// ==============================================================================================================================================







		$private_key = '8LGCMgtIGMaMPluq4mNvM8a7B6DHpmJRUzk6k04IYALNMfXcAWSfcTjT0cAR';







		$hash_key = array('amount','currency','invoice_id','merchant_id');







		sort($hash_key);



		$hash_src="";



		foreach ($hash_key as $key) {



		    $hash_src .= $parameter[$key];



		}







		$hash_src = $private_key . $hash_src;







		$hash = hash('sha256', $hash_src);



		



  		$parameter['hash']=$hash;



  		



/*	foreach ($parameter as $key => $value) {



	    echo $key."=>".$value."<br/>";



	}exit; */







	



//$param=unicode_decode($url_parameter);







    $pay_way=0;



    



		if($pay_way){



			



			$sHtml = "<form id='dhpaysubmit' name='dhpaysubmit' action='https://www.dhpay.com/merchant/web/cashier' method='post'>";



			while (list ($key, $value) = each ($parameter)) {



	            $sHtml.= "<input type='hidden' name='".$key."' value='".$value."'/>";



	        }



			$sHtml.="<script>document.forms['dhpaysubmit'].submit();</script></form>";



			echo($sHtml);



			exit;  	



			



		}else{



			$dhpay_url_parameter=("https://www.dhpay.com/merchant/web/cashier/iframe/before?".'merchant_



	id='.$parameter['merchant_id'].'&invoice_id='.$parameter['invoice_id'].'&order_no='.$parameter['order_no'].'&currency='.$parameter['currency'].'&amount='.$parameter['amount'].'&buyer_email='.$parameter['buyer_email'].'&return_url='.$parameter['return_url'].'&remark='.$parameter['remark'].'&shipping_country='.$parameter['shipping_country'].'&first_name='.$parameter['first_name'].'&last_name='.$parameter['last_name'].'&product_name='.$parameter['product_name'].'&product_price='.$parameter['product_price'].'&product_quantity='.$parameter['product_quantity'].'&address_line='.$parameter['address_line'].'&city='.$parameter['city'].'&country='.$parameter['country'].'&state='.$parameter['state'].'&zipcode='.$parameter['zipcode'].'&zipcode='.$parameter['zipcode'].'&hash='.$parameter['hash'].'&payname=dhpay');	



			



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



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



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



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



        $view->set('DHPAY_CASHIER_URL', $dhpay_url_parameter);



        



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



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



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



	 }	



  }



 



    function unicode_decode($name)  



    {  



        $name = strtolower($name);  



        // 转换编码，将Unicode编码转换成可以浏览的utf-8编码  



        $pattern = '/([\w]+)|(\\\u([\w]{4}))/i';  



        preg_match_all($pattern, $name, $matches);  



        if (!empty($matches))  



        {  



            $name = '';  



            for ($j = 0; $j < count($matches[0]); $j++)  



            {  



                $str = $matches[0][$j];  



                if (strpos($str, '\\u') === 0)  



                {  



                    $code = base_convert(substr($str, 2, 2), 16, 10);  



                    $code2 = base_convert(substr($str, 4), 16, 10);  



                    $c = chr($code).chr($code2);  



                    $c = iconv('UCS-2', 'UTF-8', $c);  



                    $name .= $c;  



                }  



                else  



                {  



                    $name .= $str;  



                }  



            }  



        }  



        return $name;  



    }  



    function utf8_unicode($name){  



        $name = iconv('UTF-8', 'UCS-2', $name);  



        $len  = strlen($name);  



        $str  = '';  



        for ($i = 0; $i < $len - 1; $i = $i + 2){  



            $c  = $name[$i];  



            $c2 = $name[$i + 1];  



            if (ord($c) > 0){   //两个字节的文字  



                $str .= '\u'.base_convert(ord($c), 10, 16).str_pad(base_convert(ord($c2), 10, 16), 2, 0, STR_PAD_LEFT);  



                //$str .= base_convert(ord($c), 10, 16).str_pad(base_convert(ord($c2), 10, 16), 2, 0, STR_PAD_LEFT);  



            } else {  



                $str .= '\u'.str_pad(base_convert(ord($c2), 10, 16), 4, 0, STR_PAD_LEFT);  



                //$str .= str_pad(base_convert(ord($c2), 10, 16), 4, 0, STR_PAD_LEFT);  



            }  



        }  



        $str = strtoupper($str);//转换为大写  



        return $str;  



    }  



  	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_html', $email->fetch('content/checkout_email.tpl'));







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







 }



 /*****************************************************************************************************************************************************/



}







?>



