



<?php



class ControllerAmopay extends Controller { 







	var $error = array();



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



	function index() {  	



					  



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



	



	



		// 如果不是post过来的消, 或者获取不到reference值则退出函数



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



			 return;}



				 



		 	      



		 // 根据订单号在数据库查询订单



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



		 



		 // 通过订单号查找在数据库查找不到匹配。 因为当客户在checkout_comfirm.php页面的时候需要用到reference, 并且要把这个订单号绑定到tpl文件里，因此临时生成了一个随机订单号



		  if(!$order_info)



    	 {



			 // 根据订单号在order_data表里找不到订单，则生成新订单



/*			echo "<script language=\"JavaScript\">alert(\"can not find order matched with order_id or reference, checkout to save a new order @ catalog/controller/amopay.php line 36\");</script>";*/



			// 保存订单,如果数据库里有相似的最新订单,则把刷新当前order的数据到数据库,不生成新订单



    	 	$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/amopay.php line 38\");</script>";



				return;



			}



    	 } 



		  



		 // 获取商户订单号最后2位随机数substr($str, -2), 写入order_data表的reserve字段



		 $reserve=substr($_POST['MerchantOrderID'], -2);



		 $sql = "update order_data set reserve = '?' where reference='?'";



		 $database->query($database->parse($sql, $reserve, $_REQUEST['reference']));	 



		   



		// 收集提交参数



		



		$MerchantOrderID=$_POST['MerchantOrderID'];	



		$SecureHash=$_POST['SecureHash'];	



		$SecureHashUsd=$_POST['SecureHashUsd'];



		$PostSecure=$_POST['PostSecure'];



		$SubmitTime=$_POST['SubmitTime'];



		$ApplyMoney = $_POST['ApplyMoney']; // 客户币种



		$ApplyUSD = $_POST['ApplyUSD']; // 对应美金币种



		$AttachDetails=$_POST['AttachDetails'];



		



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



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



		$FirstName=$order_data['firstname'];



		$LastName=$order_data['lastname'];



		$Street2=$Street1=$order_data['payment_address_1'];			 



		$City=$order_data['payment_city'];



		$Country=$order_data['payment_country'];



		$Province=$order_data['payment_zone'];



	    $PostCode=$order_data['payment_postcode'];



		$Telephone=$order_data['payment_company'];



	    $Email=$order_data['email'];



		



		$Locale="en_US";



		$ItemInfo="";		



	    $_CompanyID="10017";//商户号  由amopay分配 



		$_NetSourceID="5589";//来源网站编号  由amopay分配	



		$_Key="c70808029e887c78b6c056937291116c";	



		$_PageReturnUrl="https://www.beststoreitems.com/payment/amopay_page_return_url.php";



		$_ServerReturnUrl = "https://www.beststoreitems.com/payment/amopay_server_return_url.php";



				



		$now_Secure =$_CompanyID.$MerchantOrderID.$ApplyMoney.$SubmitTime.$AttachDetails.$_NetSourceID.$_Key;  



//	    echo "pre_string=".$PostSecure."<br />";



//		echo "now_string=".$now_Secure."<br />";



//		echo "hash_string=".$SecureHash."<br />";



		switch ($Currency)



			{



				case 'USD':



				case 'SGD':



				case 'AUD':



				case 'CAD':



				case 'NZD':



				{



					$Submit_Currency=$Currency;



					$Submit_ApplyMoney=$ApplyMoney;



					$Sumbit_MD5=$SecureHash;



					



					break;



				}



				default:



				{



					$Submit_Currency='USD';



					$Submit_ApplyMoney=$ApplyUSD;



					$Sumbit_MD5=$SecureHashUsd;



					break;



				}



			}



			



		 $parameter = array(



				"SourceTypeID" => 4, //0:跳转，4:内嵌



				"PayID" => 1, // 1:VISA 2:MasterCard 3:JCB



				"CompanyID"	=> $_CompanyID,



				"MerchantOrderID"	=> $MerchantOrderID,



				"ApplyMoney"	=> $Submit_ApplyMoney,



				"SubmitTime"	=> $SubmitTime,



				"AttachDetails"	=> $AttachDetails,



				"NetSourceID"	=> $_NetSourceID,



				"SecureHash"	=> $Sumbit_MD5,



				"PageReturnUrl"	=> $_PageReturnUrl,				



				"ServerReturnUrl"	=> $_ServerReturnUrl,



				"Currency"	=> $Submit_Currency,



				"FirstName"	=> $FirstName,



				"LastName"	=> $LastName,



				"Street1"	=> $Street1,



				"Street2"	=> $Street2,



				"City"	=> $City,



				"Country"	=> $Country,



				"Province"	=> $Province,



				"PostCode"	=> $PostCode,



				"Telephone"	=> $Telephone,



				"Email"	=> $Email,



				"Locale"	=> $Locale



		); 



	



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



// 新支付接口



/*



$MemberId="401130";



$TerminalId="20021";



$MemberTransId=$MerchantOrderID;



$OrderMoney=$ApplyMoney; // $ApplyUSD;



$TradeDate=$SubmitTime;



$AdditionInfo=$AttachDetails;



$_Key="g49wsrqb3uc6gyl5";



$MARK = "|";



$Signature= md5($MemberId.$MARK.$TerminalId.$MARK.$MemberTransId.$MARK.$OrderMoney.$MARK.$TradeDate.$MARK.urlencode(iconv("gb2312", "UTF-8", $AdditionInfo)).$MARK.$Currency.$MARK.$_Key);







$InterfaceVersion="4.0";



$ReturnUrl=utf8_encode("https://www.beststoreitems.com/amopay/return_url.php");



$PageUrl=utf8_encode("https://www.beststoreitems.com/amopay/page_url.php");







$BillFirstName=utf8_encode($order_data['firstname']);



$BillLastName=utf8_encode($order_data['lastname']);



$BillStree1=$BillStree2=utf8_encode($order_data['payment_address_1']);



$BillCity=utf8_encode($order_data['payment_city']);



$BillCountry=utf8_encode($order_data['payment_country']);



$BillProvince=utf8_encode($order_data['payment_zone']);



$BillPostCode=utf8_encode($order_data['payment_postcode']);



$BillTelephone=utf8_encode($order_data['payment_company']);



$BillEmail=utf8_encode($order_data['email']);







		  $parameter = array(



				"MemberId" => $MemberId,



				"TerminalId"	=> $TerminalId,				



				"MemberTransId" => $MemberTransId,



				"Currency"	=> $Currency,				



				"OrderMoney"	=> $OrderMoney,				



				"TradeDate"	=> $TradeDate,				



				"Signature"	=> $Signature,				



				"InterfaceVersion"	=> $InterfaceVersion,



				"NoticeType"	=> 1,



				"Locale"	=> $Locale,				



				"ReturnUrl"	=> $ReturnUrl,				



				"PageUrl"	=> $PageUrl,



				"AdditionInfo"	=> $AdditionInfo,				



				"BillFirstName"	=> $BillFirstName,



				"BillLastName"	=> $BillLastName,



				"BillStreet1"	=> $BillStree1,



				"BillStreet2"	=> $BillStree2,



				"BillCity"	=> $BillCity,



				"BillCountry"	=> $BillCountry,



				"BillProvince"	=> $BillProvince,



				"BillPostCode"	=> $BillPostCode,



				"BillTelephone"	=> $BillTelephone,



				"BillEmail"	=> $BillEmail



		); 		*/



		 



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



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



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



}



echo "<script>alert('Check Parameters');</script>"; */







	 $sHtml = "<form id='amopaysubmit' name='amopaysubmit' action='https://pay.amopay.com/pay.aspx' method='post'>";



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



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



        }		



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



		echo($sHtml);



		exit;			



	}







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



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



     



 }



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



}







?>











