Ejemplo n.º 1
0
    protected function _ConstructPostData($postData)
    {
        // PaymentExpress accepts payments in cents
        $ccname = $postData['name'];
        $cctype = $postData['cctype'];
        $ccissueno = $postData['ccissueno'];
        $ccissuedatem = $postData['ccissuedatem'];
        $ccissuedatey = $postData['ccissuedatey'];
        $ccnum = $postData['ccno'];
        $ccexpm = $postData['ccexpm'];
        $ccexpy = $postData['ccexpy'];
        $cccvd = $postData['cccvd'];
        $transactionid = $this->GetCombinedOrderId();
        $currency = GetDefaultCurrency();
        $xml = '<Txn>
						<PostUsername>' . $this->GetValue('username') . '</PostUsername>
						<PostPassword>' . $this->GetValue('merchantpassword') . '</PostPassword>
						<CardHolderName>' . $ccname . '</CardHolderName>
						<CardNumber>' . $ccnum . '</CardNumber>
						<Amount>' . number_format($this->GetGatewayAmount(), 2, '.', '') . '</Amount>
						<DateExpiry>' . $ccexpm . $ccexpy . '</DateExpiry>
						<Cvc2>' . $cccvd . '</Cvc2>
						<InputCurrency>' . $currency['currencycode'] . '</InputCurrency>
						<TxnType>Purchase</TxnType>
						<TxnId>' . $transactionid . '</TxnId>
						<MerchantReference>' . $transactionid . '</MerchantReference>
					</Txn>';
        return $xml;
    }
 public function IsSupported()
 {
     $currency = GetDefaultCurrency();
     // Check if the default currency is supported by the payment gateway
     if (!in_array($currency['currencycode'], $this->_currenciesSupported)) {
         $currencies = '';
         if (count($this->_currenciesSupported) == 1) {
             $currencies = implode(',', $this->_currenciesSupported);
         } else {
             foreach ($this->_currenciesSupported as $currency) {
                 if ($currency == $this->_currenciesSupported[count($this->_currenciesSupported) - 1]) {
                     $currencies .= ' and ' . $currency;
                 } else {
                     $currencies .= $currency . ', ';
                 }
             }
         }
         $this->SetError(sprintf(GetLang($this->_languagePrefix . 'CurrecyNotSupported'), $currencies));
     }
     // Check if SSL is required and exists
     if ($this->RequiresSSL()) {
         if (!GetConfig('UseSSL')) {
             $this->SetError(GetLang($this->_languagePrefix . 'NoSSLError'));
         }
     }
     if ($this->_requiresCurl && !function_exists("curl_exec")) {
         $this->SetError(GetLang('CreditCardCurlRequired'));
     }
     if ($this->HasErrors()) {
         return false;
     } else {
         return true;
     }
 }
Ejemplo n.º 3
0
 /**
  * Send the order notification email
  */
 public function SendNotification()
 {
     $emails = array();
     $this->_message = $this->BuildEmailMessage();
     $this->_email = $this->GetValue("emailaddress");
     if (empty($this->_email)) {
         return;
     }
     $emails = preg_split('#[,\\s]+#si', $this->_email, -1, PREG_SPLIT_NO_EMPTY);
     // Create a new email object through which to send the email
     $store_name = GetConfig('StoreName');
     require_once ISC_BASE_PATH . "/lib/email.php";
     $obj_email = GetEmailClass();
     $obj_email->Set('CharSet', GetConfig('CharacterSet'));
     $obj_email->From(GetConfig('OrderEmail'), $store_name);
     $obj_email->Set("Subject", sprintf(GetLang('NEmailSubjectLine'), $this->GetOrderId(), $store_name, FormatPrice($this->GetOrderTotal(), false, true, false, GetDefaultCurrency())));
     $obj_email->AddBody("html", $this->_message);
     // Add all recipients
     foreach ($emails as $email) {
         $obj_email->AddRecipient($email, "", "h");
     }
     $email_result = $obj_email->Send();
     if ($email_result['success']) {
         $result = array("outcome" => "success", "message" => sprintf(GetLang('EmailNotificationSentUser'), implode("<br />", $emails)));
     } else {
         $result = array("outcome" => "fail", "message" => GetLang('NEmailSendingFailed'));
     }
     return $result;
 }
	public function initializeAdmin()
	{
		$quantity = 1;

		if (isset($GLOBAL['var_orders'])) {
			$quantity = $GLOBAL['var_orders'];
		}

		// If we're using a cart quantity drop down, load that
		if (GetConfig('TagCartQuantityBoxes') == 'dropdown') {
			$GLOBALS['SelectId'] = "orders";
			$GLOBALS['Qty0'] = Interspire_Template::getInstance('admin')->render('Snippets/DiscountItemQtySelect.html');
		// Otherwise, load the textbox
		} else {
			$GLOBALS['SelectId'] = "orders";
			$GLOBALS['Qty0'] = Interspire_Template::getInstance('admin')->render('Snippets/DiscountItemQtyText.html');
		}

		if (!isset($GLOBALS['var_ps'])) {
			$GLOBALS['var_ps'] = GetLang('ChooseAProduct');
		}

		$currency = GetDefaultCurrency();
		if ($currency['currencystringposition'] == "LEFT") {
			$GLOBALS['CurrencyLeft'] = $currency['currencystring'];
		}
		else {
			$GLOBALS['CurrencyRight'] =  $currency['currencystring'];
		}
	}
Ejemplo n.º 5
0
 protected function _ConstructPostData($postData)
 {
     // Realex accepts payments in cents
     $ccname = $postData['name'];
     $cctype = strtolower($postData['cctype']);
     $ccissueno = $postData['ccissueno'];
     $ccissuedatem = $postData['ccissuedatem'];
     $ccissuedatey = $postData['ccissuedatey'];
     $ccnum = $postData['ccno'];
     $ccexpm = $postData['ccexpm'];
     $ccexpy = $postData['ccexpy'];
     $cccvd = $postData['cccvd'];
     $timestamp = strftime("%Y%m%d%H%M%S");
     $amount = number_format($this->GetGatewayAmount() * 100, 0, '', '');
     $account = $this->GetValue('account');
     $currency = GetDefaultCurrency();
     $currency = $currency['currencycode'];
     $orderid = $this->GetCombinedOrderId();
     $merchantid = $this->GetValue('merchantid');
     $merchantsecret = $this->GetValue('merchantsecret');
     $hash = sha1("{$timestamp}.{$merchantid}.{$orderid}.{$amount}.{$currency}.{$ccnum}");
     $hash = sha1("{$hash}.{$merchantsecret}");
     $order_desc = sprintf(GetLang('YourOrderFrom'), $GLOBALS['StoreName']);
     $xml = "<request type='auth' timestamp='{$timestamp}'>\n\t\t\t\t\t\t<merchantid>{$merchantid}</merchantid>";
     if (!empty($account)) {
         $xml .= "<account>{$account}</account>";
     }
     $xml .= "<orderid>{$orderid}</orderid>\n\t\t\t\t\t\t<amount currency='{$currency}'>{$amount}</amount>\n\t\t\t\t\t\t<card>\n\t\t\t\t\t\t\t<number>{$ccnum}</number>\n\t\t\t\t\t\t\t<expdate>{$ccexpm}{$ccexpy}</expdate>\n\t\t\t\t\t\t\t<type>{$cctype}</type>\n\t\t\t\t\t\t\t<chname>{$ccname}</chname>\n\t\t\t\t\t\t\t";
     if ($this->GetValue("cardcode") == "YES") {
         $xml .= "\t<cvn>\n\t\t\t\t\t\t\t\t<number>{$cccvd}</number>\n\t\t     \t\t\t\t\t<presind>1</presind>\n\t\t    \t\t\t\t</cvn>";
     }
     $xml .= "\t</card>\n\t\t\t\t\t\t<autosettle flag='1' />\n\t\t\t\t\t\t<sha1hash>{$hash}</sha1hash>\n\t\t\t\t\t</request>";
     return $xml;
 }
Ejemplo n.º 6
0
	public function IsSupported()
	{
		$currencycode = GetDefaultCurrency();
		$currencycode = $currencycode['currencycode'];

		if (!in_array($currencycode, $this->_currenciesSupported)) {
			$this->SetError(GetLang('AmazonFpsCurrecyNotSupported'));
		}

		if ($this->RequiresSSL()) {
			if(!GetConfig('UseSSL')) {
				$this->SetError(GetLang('AmazonFpsNoSSLError'));
			}
		}

		if(!function_exists("curl_exec")) {
			$this->SetError(GetLang('CreditCardCurlRequired'));
		}

		if($this->HasErrors()) {
			return false;
		}
		else {
			return true;
		}
	}
Ejemplo n.º 7
0
		/**
		* Build and format the message to be sent
		*/
		private function BuildSmsMessage()
		{
			if($this->testMode == true) {
				return urlencode('SMSMessageTest');
			}
			else {
				$message = sprintf(GetLang('SMSMessageContents'), $this->_orderid, $GLOBALS['StoreName'], $this->_ordernumitems, FormatPrice($this->_ordertotal, false, true, false, GetDefaultCurrency()), $this->_orderpaymentmethod);
				return urlencode($message);
			}
		}
	public function initializeAdmin()
	{
		$currency = GetDefaultCurrency();
		if ($currency['currencystringposition'] == "LEFT") {
			$GLOBALS['CurrencyLeft'] = $currency['currencystring'];
		}
		else {
			$GLOBALS['CurrencyRight'] =  $currency['currencystring'];
		}
	}
Ejemplo n.º 9
0
 /**
  * Get the currency code of the default currency for the store
  *
  * @return void
  **/
 public function GetDefaultCurrencyCode()
 {
     static $code = '';
     if ($code != '') {
         return $code;
     }
     $defaultCurrency = GetDefaultCurrency();
     $code = $defaultCurrency['currencycode'];
     return $code;
 }
Ejemplo n.º 10
0
		/**
		* Build and format the message to be sent
		*/
		private function BuildMsnMessage()
		{
			if($this->testMode) {
				return GetLang('MSNMessageTest');
			}
			else {
				$store_name = GetConfig('StoreName');
				$message = sprintf(GetLang('MSNMessageContents'), $this->_orderid, $store_name, $this->_ordernumitems, FormatPrice($this->_ordertotal, false, true, false, GetDefaultCurrency()), $this->_orderpaymentmethod, $GLOBALS['ShopPath'], $this->_orderid);
				return str_replace("{NL}", chr(10), $message);
			}
		}
Ejemplo n.º 11
0
 protected function _ConstructPostData($postData)
 {
     $currency = GetDefaultCurrency();
     $currencycode = strtolower($currency['currencycode']);
     switch ($postData['cctype']) {
         case 'VISA':
             $cctype = '001';
             break;
         case 'MC':
             $cctype = '002';
             break;
         case 'AMEX':
             $cctype = '003';
             break;
         case 'DISCOVER':
             $cctype = '004';
             break;
         case 'DINERS':
             $cctype = '005';
             break;
         default:
             $cctype = '000';
             break;
     }
     $amount = $this->GetGatewayAmount();
     $billingDetails = $this->GetBillingDetails();
     $timestamp = getmicrotime();
     $transactionid = $this->GetCombinedOrderId();
     $signatureData = getMerchantID() . $amount . $currencycode . $timestamp . 'sale';
     $cybersourcePost['merchantID'] = getMerchantID();
     $cybersourcePost['billTo_firstName'] = htmlentities($billingDetails['ordbillfirstname']);
     $cybersourcePost['billTo_lastName'] = $billingDetails['ordbilllastname'];
     $cybersourcePost['billTo_street1'] = $billingDetails['ordbillstreet1'];
     $cybersourcePost['billTo_city'] = $billingDetails['ordbillsuburb'];
     $cybersourcePost['billTo_state'] = $billingDetails['ordbillstate'];
     $cybersourcePost['billTo_postalCode'] = $billingDetails['ordbillzip'];
     $cybersourcePost['billTo_country'] = $billingDetails['ordbillcountry'];
     $cybersourcePost['billTo_email'] = $billingDetails['ordbillemail'];
     $cybersourcePost['card_cardType'] = $cctype;
     $cybersourcePost['card_accountNumber'] = $postData['ccno'];
     $cybersourcePost['card_expirationMonth'] = $postData['ccexpm'];
     $cybersourcePost['card_expirationYear'] = '20' . $postData['ccexpy'];
     $cybersourcePost['orderPage_timestamp'] = $timestamp;
     $cybersourcePost['orderPage_signaturePublic'] = hopHash($signatureData, getPublicKey());
     $cybersourcePost['orderPage_serialNumber'] = getSerialNumber();
     $cybersourcePost['orderPage_version'] = '4';
     $cybersourcePost['orderPage_transactionType'] = 'sale';
     $cybersourcePost['amount'] = $amount;
     $cybersourcePost['currency'] = $currencycode;
     $cybersourcePost['hash'] = md5($this->GetValue("accessid") . $transactionid . $_COOKIE['SHOP_ORDER_TOKEN'] . $amount);
     $cybersourcePost['orderid'] = $transactionid;
     $cybersourcePost['iscsessionid'] = $_COOKIE['SHOP_ORDER_TOKEN'];
     return $cybersourcePost;
 }
Ejemplo n.º 12
0
 public function IsSupported()
 {
     $currencycode = GetDefaultCurrency();
     $currencycode = $currencycode['currencycode'];
     if (!in_array($currencycode, $this->_currenciesSupported)) {
         $this->SetError(GetLang($this->_languagePrefix . 'CurrecyNotSupported'));
     }
     if ($this->HasErrors()) {
         return false;
     } else {
         return true;
     }
 }
Ejemplo n.º 13
0
 public function IsSupported()
 {
     $currency = GetDefaultCurrency();
     // Check if the default currency is supported by the payment gateway
     if (!in_array($currency['currencycode'], $this->_currenciesSupported)) {
         $this->SetError(sprintf(GetLang($this->_languagePrefix . 'CurrecyNotSupported'), implode(',', $this->_currenciesSupported)));
     }
     if ($this->HasErrors()) {
         return false;
     } else {
         return true;
     }
 }
Ejemplo n.º 14
0
 /**
  * Check if this checkout module can be enabled or not.
  *
  * @return boolean True if this module is supported on this install, false if not.
  */
 public function IsSupported()
 {
     $currency = GetDefaultCurrency();
     $supportedCurrencies = array('USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'MXP');
     // Check if the default currency is supported by the payment gateway
     if (!in_array($currency['currencycode'], $supportedCurrencies)) {
         $this->SetError(sprintf(GetLang('PayPalExpressCurrecyNotSupported'), implode(',', $supportedCurrencies)));
     }
     if ($this->HasErrors()) {
         return false;
     } else {
         return true;
     }
 }
Ejemplo n.º 15
0
	/**
	*	Redirect the customer to PayMate's site to enter their payment details
	*/
	public function TransferToProvider()
	{
		$payMateCurrency = '';
		$defaultCurrency = GetDefaultCurrency();

		if (isset($defaultCurrency['currencycode']) && trim($defaultCurrency['currencycode']) !== '') {
			$payMateCurrency = $defaultCurrency['currencycode'];
		}

		// Default the default currency code to AUD if we have none or if we have an unsupported one
		if ($payMateCurrency == '' || !$this->checkSupportedCurrencies($payMateCurrency)) {
			$payMateCurrency = 'AUD';
		}

		$payMateUsername = trim($this->GetValue("username"));

		if($this->GetValue("testmode") == "YES") {
			$payMateURL = sprintf("https://www.paymate.com.au/PayMate/TestExpressPayment?mid=%s", $payMateUsername);
		}
		else {
			$payMateURL = sprintf("https://www.paymate.com/PayMate/ExpressPayment?mid=%s", $payMateUsername);
		}

		$billingDetails = $this->GetBillingDetails();
		$hiddenFields = array(
			'currency'				=> $payMateCurrency,
			'amt'					=> $this->GetGatewayAmount(),
			'amt_editable'			=> 'N',
			'ref'					=> $_COOKIE['SHOP_ORDER_TOKEN'],
			'return'				=> $GLOBALS['ShopPathSSL'].'/finishorder.php',
			'popup'					=> 'false',

			// Customer details
			'pmt_contact_firstname'	=> $billingDetails['ordbillfirstname'],
			'pmt_contact_surname'	=> $billingDetails['ordbilllastname'],
			'pmt_sender_email'		=> $billingDetails['ordbillemail'],
			'pmt_contact_phone'		=> $billingDetails['ordbillphone'],
			'pmt_country'			=> GetCountryISO2ByName($billingDetails['ordbillcountry']),
			'regindi_address1'		=> $billingDetails['ordbillstreet1'],
			'regindi_address2'		=> $billingDetails['ordbillstreet2'],
			'regindi_pcode'			=> $billingDetails['ordbillzip'],
			'regindi_sub'			=> $billingDetails['ordbillsuburb'],
			'regindi_state'			=> $billingDetails['ordbillstate']
		);

		$this->RedirectToProvider($payMateURL, $hiddenFields);
	}
Ejemplo n.º 16
0
 protected function _ConstructPostData($postData)
 {
     $transactionid = $this->GetCombinedOrderId();
     $ccname = $postData['name'];
     $cctype = $postData['cctype'];
     $ccissueno = $postData['ccissueno'];
     $ccissuedatem = $postData['ccissuedatem'];
     $ccissuedatey = $postData['ccissuedatey'];
     $ccnum = $postData['ccno'];
     $ccexpm = $postData['ccexpm'];
     $ccexpy = $postData['ccexpy'];
     $cccvd = $postData['cccvd'];
     $amount = number_format($this->GetGatewayAmount(), 0, '', '');
     $ccnum = $postData['ccno'];
     $currency = GetDefaultCurrency();
     $billingDetails = $this->GetBillingDetails();
     $this->identifier = substr(sha1(time()), 0, 10);
     $this->_testmode = $this->GetValue("testmode") == "YES";
     if ($this->_testmode) {
         $test = 'true';
     } else {
         $test = 'false';
     }
     switch ($cctype) {
         case 'VISA':
             $cctype = 'Visa';
             break;
         case 'MC':
             $cctype = 'Master Card';
             break;
         case 'MAESTRO':
             $cctype = 'Maestro';
             break;
         case 'AMEX':
             $cctype = 'American Express';
             break;
         case 'DINERS':
             $cctype = 'Diners Card';
             break;
         case 'JCB':
             $cctype = 'JCB';
             break;
     }
     $gatewayData = array('mid' => $this->GetValue('mid'), 'vpn_pswd' => $this->GetValue('password'), 'trans_id' => $transactionid, 'name' => $ccname, 'card_number' => $ccnum, 'amount' => $amount, 'expiry_date' => $ccexpm . $ccexpy, 'issue_number' => $ccissueno, 'start_date' => $ccissuedatem . $ccissuedatey, 'order' => "", 'shipping' => "", 'billing' => "", 'options' => "test_status=" . $test . ",dups=false,card_type=" . $cctype, 'returnVariable' => "authResponse");
     return array('gatewayData' => $gatewayData, 'soapAction' => $this->soapAction);
 }
Ejemplo n.º 17
0
	public function IsSupported()
	{
		$currency = GetDefaultCurrency();

		// Check if the default currency is supported by the payment gateway
		if (!in_array($currency['currencycode'], $this->_currenciesSupported)) {
			$this->SetError(sprintf(GetLang('IdealCurrecyNotSupported'), implode(',',$this->_currenciesSupported)));
		}

		// check for openssl support
		if (!function_exists('openssl_pkey_new') || !function_exists('openssl_csr_new')) {
			$this->SetError(GetLang('IdealOpenSSLRequired'));
		}

		// check for writable files and folders
		include_once(ISC_BASE_PATH.'/lib/class.file.php');
		$f = new FileClass();

		// check config file is writable
		if (file_exists($this->_configFile) && !$f->CheckFileWritable($this->_configFile)) {
			$this->SetError(GetLang('IdealConfigFileNotWritable', array("configFile" => $this->_configFile)));
		}

		// check the security folder is writable
		$securityFolder = dirname(__FILE__) . "/lib/includes/security";
		if (!$f->CheckDirWritable($securityFolder)) {
			$this->SetError(GetLang('IdealSecurityFolderNotWritable', array("securityFolder" => $securityFolder)));
		}

		// check key file is writable if it exists
		if (file_exists($this->_keyFile) && !$f->CheckFileWritable($this->_keyFile)) {
			$this->SetError(GetLang('IdealKeyFileNotWritable', array("keyFile" => $this->_keyFile)));
		}

		// check certificate file is writable if it exists
		if (file_exists($this->_certFile) && !$f->CheckFileWritable($this->_certFile)) {
			$this->SetError(GetLang('IdealCertFileNotWritable', array("certFile" => $this->_certFile)));
		}

		if($this->HasErrors()) {
			return false;
		}
		else {
			return true;
		}
	}
Ejemplo n.º 18
0
		public function TransferToProvider()
		{
			$url = 'https://securetrading.net/authorize/form.cgi';
			$currency = GetDefaultCurrency();
			$currency = $currency['currencycode'];

			$billingDetails = $this->GetBillingDetails();

			$merchantid = $this->GetValue('MerchantId');
			$merchantemail = $this->GetValue('MerchantEmail');
			$callbackid = $this->GetValue('CallbackId');

			$amount = number_format($this->GetGatewayAmount()*100, 0, '','');

			$stform['merchant'] = $merchantid;
			$stform['orderref'] = $this->GetCombinedOrderId();
			$stform['orderinfo'] = sprintf(GetLang($this->_languagePrefix.'YourOrderFromX'), $GLOBALS['StoreName']);
			$stform['amount'] = $amount;
			$stform['currency'] = $currency;
			$stform['merchantemail'] = $merchantemail;
			$stform['callbackurl'] = $callbackid;
			$stform['failureurl'] = $callbackid;
			$stform['formref'] = $callbackid;
			$stform['customeremail'] = $billingDetails['ordbillemail'];
			$stform['settlementday'] = 1;

			$stform['ordertoken'] = $_COOKIE['SHOP_ORDER_TOKEN'];
			$stform['sessiontoken'] = $_COOKIE['SHOP_SESSION_TOKEN'];
			$stform['provider'] = $this->GetId();
			$stform['hash'] = md5($this->GetValue('SecretWord').$this->GetCombinedOrderId().$merchantid.$amount.$currency);

			$stform['name'] = $billingDetails['ordbillfirstname'] . ' '. $billingDetails['ordbilllastname'];
			$stform['address'] = $billingDetails['ordbillstreet1'] . ' '. $billingDetails['ordbillstreet2'];
			$stform['town'] = $billingDetails['ordbillsuburb'];
			$stform['county'] = $billingDetails['ordbillstate'];
			$stform['postcode'] = $billingDetails['ordbillzip'];

			$stform['country'] = $billingDetails['ordbillcountry'];
			$stform['telephone'] = $billingDetails['ordbillphone'];
			$stform['email'] = $billingDetails['ordbillemail'];

			header('Location: ' . $url . '?'. http_build_query($stform));
		}
Ejemplo n.º 19
0
 protected function _ConstructPostData($postData)
 {
     // PaymentExpress accepts payments in cents
     $ccname = $postData['name'];
     $cctype = $postData['cctype'];
     $ccissueno = $postData['ccissueno'];
     $ccissuedatem = $postData['ccissuedatem'];
     $ccissuedatey = $postData['ccissuedatey'];
     $ccnum = $postData['ccno'];
     $ccexpm = $postData['ccexpm'];
     $ccexpy = $postData['ccexpy'];
     $cccvd = $postData['cccvd'];
     $currency = GetDefaultCurrency();
     $billingDetails = $this->GetBillingDetails();
     $chronoPayPostData['opcode'] = 1;
     $chronoPayPostData['product_id'] = $this->GetValue('productid');
     $chronoPayPostData['fname'] = $billingDetails['ordbillfirstname'];
     $chronoPayPostData['lname'] = $billingDetails['ordbilllastname'];
     $chronoPayPostData['cardholder'] = $ccname;
     $chronoPayPostData['zip'] = $billingDetails['ordbillzip'];
     $chronoPayPostData['street'] = $billingDetails['ordbillstreet1'] . ' ' . $billingDetails['ordbillstreet2'];
     $chronoPayPostData['city'] = $billingDetails['ordbillsuburb'];
     if ($billingDetails['ordbillcountryid'] == '38' || $billingDetails['ordbillcountryid'] == '226') {
         $chronoPayPostData['state'] = GetStateISO2ByName($billingDetails['ordbillstate']);
     }
     $chronoPayPostData['country'] = GetCountryISO3ById($billingDetails['ordbillcountryid']);
     $chronoPayPostData['email'] = $billingDetails['ordbillemail'];
     $chronoPayPostData['phone'] = $billingDetails['ordbillemail'];
     $chronoPayPostData['ip'] = $_SERVER['REMOTE_ADDR'];
     $chronoPayPostData['card_no'] = $ccnum;
     $chronoPayPostData['cvv'] = $cccvd;
     $chronoPayPostData['expirey'] = "20" . $ccexpy;
     $chronoPayPostData['expirem'] = $ccexpm;
     $chronoPayPostData['amount'] = $this->GetGatewayAmount();
     $chronoPayPostData['currency'] = $currency['currencycode'];
     $hash = md5($this->GetValue('sharedsecret') . $chronoPayPostData['opcode'] . $chronoPayPostData['product_id'] . $chronoPayPostData['fname'] . $chronoPayPostData['lname'] . $chronoPayPostData['street'] . $chronoPayPostData['ip'] . $chronoPayPostData['card_no'] . $chronoPayPostData['amount']);
     $chronoPayPostData['hash'] = $hash;
     return http_build_query($chronoPayPostData);
 }
Ejemplo n.º 20
0
/**
 * Format the price
 *
 * Function will format the price based on the currency record that is provided. The default currency record will be the
 * one stored in the current session
 *
 * @access public
 * @param float $price The price to format
 * @param array $currency The currency record. Default is the one stored within the currency session
 * @return string The formatted price
 */
function FormatPrice($price, $strip_decimals=false, $add_token=true, $strip_thousandsep=false, $currency=null, $includeCurrencyCode=false)
{
	// Because we're going to have prices come as floats, we're likely to have
	// precision issues. Round everything to 4 decimal places before formatting
	// a price, because that's the max internally storable in the DB anyway.
	// Better yet would be to store prices in cents, rather than dollars but
	// this is not feasible at the moment.
	$price = round($price, 4);

	if (is_null($currency)) {
		if(!isset($GLOBALS['CurrentCurrency'])) {
			$defaultCurrency = GetDefaultCurrency();
			$GLOBALS['CurrentCurrency'] = $defaultCurrency['currencyid'];
		}
		$currency = GetCurrencyById($GLOBALS['CurrentCurrency']);
	}

	if(!is_array($currency)) {
		$currency = GetCurrencyById($currency);
	}

	if(!isset($currency['currencyid'])) {
		$currency = GetDefaultCurrency();
	}

	if ($strip_thousandsep) {
		$currency['currencythousandstring'] = '';
	}

	$negative = false;
	if($price < 0) {
		$negative = true;
		$price = substr($price, 1);
	}

	$num = number_format($price, $currency['currencydecimalplace'], $currency['currencydecimalstring'], $currency['currencythousandstring']);
	// Do we strip decimal places? If so just return the whole number portion
	if ($strip_decimals) {
		$tmp = explode($currency['currencydecimalstring'], $num);
		$num = $tmp[0];
	}

	if ($add_token) {
		if (strtolower($currency['currencystringposition']) == "left") {
			$num = $currency['currencystring'] . $num;
		}
		else {
			$num = $num . $currency['currencystring'];
		}
	}

	if($includeCurrencyCode == true) {
		$num .= ' '.$currency['currencycode'];
	}

	if($negative) {
		$num = '-'.$num;
	}

	return $num;
}
 private function GetPriceFormats()
 {
     SetupCurrency();
     $currency = GetDefaultCurrency();
     $price = number_format(1543.987, $currency['currencydecimalplace'], $currency['currencydecimalstring'], '');
     $formats = array("number" => $price, "formatted" => FormatPriceInCurrency(1543.987));
     return $formats;
 }
Ejemplo n.º 22
0
 private function EditCurrency()
 {
     $currency = GetDefaultCurrency();
     $GLOBALS['FormAction'] = "SettingsSaveUpdatedCurrency";
     $GLOBALS['CurrencyTitle'] = GetLang('EditCurrency');
     $GLOBALS['CancelMessage'] = GetLang('CancelEditCurrency');
     $GLOBALS['CurrencyConverterBox'] = sprintf(GetLang('CurrencyConverterBox'), $currency['currencycode']);
     $GLOBALS['CurrencyExchangeRateHelp'] = sprintf(GetLang('CurrencyExchangeRateHelp'), $currency['currencycode'], GetConfig('DefaultCurrencyRate'));
     $GLOBALS['OriginListSize'] = ' size="2"';
     if (isset($_GET['currencyId'])) {
         $currencyId = (int) $_GET['currencyId'];
         $query = "SELECT * FROM [|PREFIX|]currencies WHERE currencyid='" . $currencyId . "'";
         $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
         $GLOBALS['hiddenFields'] = sprintf("<input type='hidden' name='currencyid' value='%d' />", $currencyId);
         if ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
             $GLOBALS['CurrencyName'] = isc_html_escape($row['currencyname']);
             $GLOBALS['CurrencyCode'] = isc_html_escape($row['currencycode']);
             $GLOBALS['CurrencyString'] = isc_html_escape($row['currencystring']);
             $GLOBALS['CurrencyDecimalString'] = isc_html_escape($row['currencydecimalstring']);
             $GLOBALS['CurrencyThousandString'] = isc_html_escape($row['currencythousandstring']);
             $GLOBALS['CurrencyDecimalPlace'] = isc_html_escape($row['currencydecimalplace']);
             $GLOBALS['CurrencyExchangeRate'] = isc_html_escape((double) $row['currencyexchangerate']);
             $GLOBALS['ConverterList'] = $this->_getCurrencyConverterAsItems($row['currencyconvertercode']);
             $GLOBALS['OriginListSize'] = '';
             if (strtolower($row['currencystringposition']) == "left") {
                 $GLOBALS['CurrencyLocationIsLeft'] = 'selected="selected"';
             } else {
                 $GLOBALS['CurrencyLocationIsRight'] = 'selected="selected"';
             }
             if (isId($row['currencycountryid'])) {
                 $GLOBALS['CurrencyOriginType'] = "country";
             } else {
                 if (isId($row['currencycouregid'])) {
                     $GLOBALS['CurrencyOriginType'] = "region";
                 }
             }
             $GLOBALS['OriginList'] = $this->_getCurrencyOriginOptions($row['currencycountryid'], $row['currencycouregid']);
             if ($row['currencystatus'] == 1) {
                 $GLOBALS['CurrencyEnabled'] = 'checked="checked"';
             }
             if ($row['currencyisdefault']) {
                 $GLOBALS['HideOnDefault'] = " style='display:none;'";
             }
             $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("currency.form");
             $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate();
         } else {
             $this->ManageCurrencySettings();
         }
     } else {
         $this->ManageCurrencySettings();
     }
 }
Ejemplo n.º 23
0
function xmlrpc_GetDefaultCurrency($xmlrpcmsg)
{
    ob_start('ob_file_callback');
    /*x*/
    if ($xmlrpcmsg->getNumParams() == 2) {
        /*x*/
        $rtn = new xmlrpcresp(php_xmlrpc_encode(GetDefaultCurrency($xmlrpcmsg->getParam(0)->scalarval(), $xmlrpcmsg->getParam(1)->scalarval())));
        /*x*/
    } else {
        /*e*/
        $rtn = new xmlrpcresp(php_xmlrpc_encode(GetDefaultCurrency('', '')));
        /*x*/
    }
    ob_end_flush();
    return $rtn;
}
Ejemplo n.º 24
0
				/**
		 * Process the PayPal IPN ping back.
		 */
		public function ProcessGatewayPing()
		{
			//make it only work for echeck pings
			if($_POST['payment_type'] != 'echeck' || $_POST['payment_status']== 'Pending') {
				exit;
			}

			if(!isset($_POST['custom'])) {
				exit;
			}

			$sessionToken = explode('_', $_REQUEST['custom'], 2);

			$this->SetOrderData(LoadPendingOrdersByToken($sessionToken[0]));

			$amount = number_format($this->GetGatewayAmount(), 2, '.', '');

			if($amount == 0) {
				exit;
			}

			// Perform a post back to PayPal with exactly what we received in order to validate the request
			$queryString = array();
			$queryString[] = "cmd=_notify-validate";
			foreach($_POST as $k => $v) {
				$queryString[] = $k."=".urlencode($v);
			}
			$queryString = implode('&', $queryString);

			$testMode = $this->GetValue('testmode');
			if($testMode == 'YES') {
				$verifyURL = 'http://www.sandbox.paypal.com/cgi-bin/webscr';
			}
			else {
				$verifyURL = 'http://www.paypal.com/cgi-bin/webscr';
			}

			$response = PostToRemoteFileAndGetResponse($verifyURL, $queryString);

			// This pingback was not valid
			if($response != "VERIFIED") {
				// Bad order details
				$GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang('PayPalErrorInvalid'), "RESPONSE : "  .$response);
				return false;
			}

			// If we're still here, the ping back was valid, so we check the payment status and everything else match up


			$paypalEmail = $this->GetValue('email');

			if(!isset($_POST['receiver_email']) || !isset($_POST['mc_gross']) || !isset($_POST['payment_status'])) {
				// Bad order details
				$GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang('PayPalErrorInvalid'), print_r($_POST, true));
				return false;
			}

			// The values passed don't match what we expected
			if(($_POST['mc_gross'] != $amount && !in_array($_POST['payment_status'], array('Reversed', 'Refunded', 'Canceled_Reversed')))) {
				$errorMsg = sprintf(GetLang('PayPalErrorInvalidMsg'), $_POST['mc_gross'], $amount, $_POST['receiver_email'], $paypalEmail, $_POST['payment_status']);
				$GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang('PayPalErrorInvalid'), $errorMsg);
				return false;
			}

			$currency = GetDefaultCurrency();

			if($_POST['mc_currency'] != $currency['currencycode']) {
				$errorMsg = sprintf(GetLang('PayPalErrorInvalidMsg3'), $currency['currencycode'], $_POST['mc_currency']);
				$GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang('PayPalErrorInvalid'), $errorMsg);
				return false;
			}

			// Has the transaction been processed before? If so, we can't process it again
			$transaction = GetClass('ISC_TRANSACTION');

			$newTransaction = array(
				'providerid' => $this->GetId(),
				'transactiondate' => time(),
				'transactionid' => $_POST['txn_id'],
				'orderid' => array_keys($this->GetOrders()),
				'message' => '',
				'status' => '',
				'amount' => $_POST['mc_gross'],
				'extrainfo' => array()
			);

			$orderPaymentStatus = '';
			switch($_POST['payment_status']) {
				case "Completed":
					$orderPaymentStatus = 'captured';
					$newTransaction['status'] = TRANS_STATUS_COMPLETED;
					$newOrderStatus = ORDER_STATUS_AWAITING_FULFILLMENT;
					break;
				case "Pending":
					if($_POST['payment_type'] != 'echeck') {
						$orderPaymentStatus = 'authorized';
					}
					$newTransaction['status'] = TRANS_STATUS_PENDING;
					$newOrderStatus = ORDER_STATUS_AWAITING_PAYMENT;
					$newTransaction['extrainfo']['reason'] = $_POST['pending_reason'];
					break;
				case "Denied":
					$newTransaction['status'] = TRANS_STATUS_DECLINED;
					$newOrderStatus = ORDER_STATUS_DECLINED;
					break;
				case "Failed":
					$newTransaction['status'] = TRANS_STATUS_FAILED;
					$newOrderStatus = ORDER_STATUS_DECLINED;
					break;
				case "Refunded":
					$newTransaction['status'] = TRANS_STATUS_REFUND;
					$newOrderStatus = ORDER_STATUS_REFUNDED;
					break;
				case "Reversed":
					$newTransaction['status'] = TRANS_STATUS_CHARGEBACK;
					$newOrderStatus = ORDER_STATUS_REFUNDED;
					break;
				case "Canceled_Reversal":
					$newTransaction['status'] = TRANS_STATUS_CANCELLED_REVERSAL;
					$newOrderStatus = ORDER_STATUS_REFUNDED;
					break;
			}


			$previousTransaction = $transaction->LoadByTransactionId($_POST['txn_id'], $this->GetId());

			// Already processed before, HALT and log error
			if(is_array($previousTransaction) && $previousTransaction['transactionid'] && $previousTransaction['status'] == $newTransaction['status']) {
				$GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), sprintf(GetLang('PayPalTransactionAlreadyProcessed'), $_POST['txn_id']));
				return false;
			}


			$newTransaction['message'] = $this->GetPayPalTransactionMessage($_POST);

			$transactionId = $transaction->Create($newTransaction);

			$oldOrderStatus = $this->GetOrderStatus();
			// If the order was previously incomplete, we need to do some extra work
			if($oldOrderStatus == ORDER_STATUS_INCOMPLETE) {
				// If a customer doesn't return to the store from PayPal, their cart will never be
				// emptied. So what we do here, is if we can, load up the existing customers session
				// and empty the cart and kill the checkout process. When they next visit the store,
				// everything should be "hunky-dory."
				session_write_close();
				$session = new ISC_SESSION($sessionToken[1]);
				EmptyCartAndKillCheckout();
			}

			// Update the status for all orders that we've just received the payment for
			foreach($this->GetOrders() as $orderId => $order) {
				$status = $newOrderStatus;
				// If it's a digital order & awaiting fulfillment, automatically complete it
				if($order['ordisdigital'] && $status == ORDER_STATUS_AWAITING_FULFILLMENT) {
					$status = ORDER_STATUS_COMPLETED;
				}
				UpdateOrderStatus($orderId, $status);
			}

			$updatedOrder = array(
				'ordpaymentstatus' => $orderPaymentStatus,
			);

			$this->UpdateOrders($updatedOrder);

			// This was a successful order
			$oldStatus = GetOrderStatusById($oldOrderStatus);
			if(!$oldStatus) {
				$oldStatus = 'Incomplete';
			}
			$newStatus = GetOrderStatusById($newOrderStatus);

			$extra = sprintf(GetLang('PayPalSuccessDetails'), implode(', ', array_keys($this->GetOrders())), $amount, '', $_POST['txn_id'], $_POST['payment_status'], $newStatus, $oldStatus);

			$successMsg = sprintf(GetLang('PayPalPaymentsProSuccess'), implode(', ', array_keys($this->GetOrders())));

			$GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess(array('payment', $this->GetName()), $successMsg, $extra);
			return true;
		}
Ejemplo n.º 25
0
 /**
  * Actually save a new order or an updated existing order in the database
  * after it's been validated.
  *
  * @param array An array of details about the order to save.
  * @param int The ID of the existing order if we're updating an order.
  * @return boolean True if successful, false if not.
  */
 private function CommitOrder($data, $orderId = 0)
 {
     $GLOBALS['ISC_CLASS_DB']->StartTransaction();
     /**
      * We need to find our billing/shipping details from the form fields first as it is
      * also used in creating the customer
      */
     $billingDetails = array();
     $shippingDetails = array();
     $billingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_BILLING, true);
     $shippingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_SHIPPING, true);
     $fields = $billingFields + $shippingFields;
     $addressMap = array('FirstName' => 'firstname', 'LastName' => 'lastname', 'CompanyName' => 'company', 'AddressLine1' => 'address1', 'AddressLine2' => 'address2', 'City' => 'city', 'State' => 'state', 'Zip' => 'zip', 'State' => 'state', 'Country' => 'country', 'Phone' => 'phone');
     foreach (array_keys($fields) as $fieldId) {
         $privateName = $fields[$fieldId]->record['formfieldprivateid'];
         if ($privateName == '' || !array_key_exists($privateName, $addressMap)) {
             continue;
         }
         if ($fields[$fieldId]->record['formfieldformid'] == FORMFIELDS_FORM_BILLING) {
             $detailsVar =& $billingDetails;
         } else {
             $detailsVar =& $shippingDetails;
         }
         /**
          * Find the country
          */
         if (isc_strtolower($privateName) == 'country') {
             $detailsVar['shipcountry'] = $fields[$fieldId]->getValue();
             $detailsVar['shipcountryid'] = GetCountryByName($fields[$fieldId]->getValue());
             if (!isId($detailsVar['shipcountryid'])) {
                 $detailsVar['shipcountryid'] = 0;
             }
             /**
              * Else find the state
              */
         } else {
             if (isc_strtolower($privateName) == 'state') {
                 $detailsVar['shipstate'] = $fields[$fieldId]->getValue();
                 $stateInfo = GetStateInfoByName($detailsVar['shipstate']);
                 if ($stateInfo && isId($stateInfo['stateid'])) {
                     $detailsVar['shipstateid'] = $stateInfo['stateid'];
                 } else {
                     $detailsVar['shipstateid'] = 0;
                 }
                 /**
                  * Else the rest
                  */
             } else {
                 $detailsVar['ship' . $addressMap[$privateName]] = $fields[$fieldId]->getValue();
             }
         }
     }
     // If we're creating an account for this customer, create it now
     if ($data['ordcustid'] == 0 && $data['customerType'] == 'new') {
         $customerData = array('email' => $data['custconemail'], 'password' => $data['custpassword'], 'firstname' => $billingDetails['shipfirstname'], 'lastname' => $billingDetails['shiplastname'], 'company' => $billingDetails['shipcompany'], 'phone' => $billingDetails['shipphone'], 'token' => GenerateCustomerToken(), 'customergroupid' => $data['custgroupid']);
         $GLOBALS['CusFirstname'] = $billingDetails['shipfirstname'];
         # Baskaran
         /* Added the store credit as seperate as it may be disabled while add/edit order - vikas  */
         if (isset($data['custstorecredit'])) {
             $customerData['storecredit'] = DefaultPriceFormat($data['custstorecredit']);
         }
         /**
          * Save the customer custom fields
          */
         if (gzte11(ISC_MEDIUMPRINT)) {
             $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_ACCOUNT);
             if (isId($formSessionId)) {
                 $customerData['custformsessionid'] = $formSessionId;
             }
         }
         $entity = new ISC_ENTITY_CUSTOMER();
         $data['ordcustid'] = $entity->add($customerData);
         if (!$data['ordcustid']) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
     }
     //2010-11-08 Ronnie add When calculating the ship infomation corresponding to no
     $GLOBALS['BCK_shipcountryid'] = $detailsVar['shipcountry'];
     $GLOBALS['BCK_shipstateid'] = $detailsVar['shipstate'];
     if ($GLOBALS['BCK_shipstateid'] == '') {
         $GLOBALS['BCK_shipcountryid'] = $billingDetails['shipcountry'];
         $GLOBALS['BCK_shipstateid'] = $billingDetails['shipstate'];
     }
     foreach ($this->GetCartApi()->GetProductsInCart() as $rowId => $product) {
         if (!isset($product['exists_order_coupon']) && isset($product['discount'])) {
             // Now workout the discount amount
             if ($product['coupontype'] == 0) {
                 // It's a dollar discount
                 $newPrice = $product['product_price'] - $product['discount'];
             } else {
                 // It's a percentage discount
                 $discount = $product['product_price'] / 100 * $product['discount'];
                 if ($discount == $product['product_price']) {
                     $newPrice = 0;
                 } else {
                     $newPrice = $product['product_price'] - $discount;
                 }
             }
             if ($newPrice < 0) {
                 $newPrice = 0;
             }
             $this->GetCartApi()->SetItemValue($rowId, 'discount_price', $newPrice);
         } elseif (isset($product['exists_order_coupon']) && isset($product['discount'])) {
             $this->GetCartApi()->SetItemValue($rowId, 'discount_price', $product['product_price']);
             $newPrice = 0;
             if ($product['coupontype'] == 0) {
                 // It's a dollar discount
                 $newPrice = $product['product_price'] + $product['discount'];
             } else {
                 // It's a percentage discount
                 $newPrice = $product['product_price'] / (1 - $product['discount'] / 100);
             }
             $this->GetCartApi()->SetItemValue($rowId, 'product_price', $newPrice);
         }
     }
     $orderSummary = $this->CalculateOrderSummary();
     //ronnie
     //$orderSummary['taxCost'];
     $defaultCurrency = GetDefaultCurrency();
     $email = '';
     if (isset($data['custconemail']) && $data['customerType'] == 'new') {
         $email = $data['custconemail'];
     } else {
         if (isset($data['anonymousemail']) && $data['customerType'] == 'anonymous') {
             $email = $data['anonymousemail'];
         }
     }
     /**********************************************************
     				Code added by Mayank Jaitly for getting the logged user
     				for adding his/her id as order owner.
     			************************************************************/
     $loggeduser = $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetUser();
     //////////  End of alteration
     $custid = $data['ordcustid'];
     $ordstatus = '';
     $query = $GLOBALS['ISC_CLASS_DB']->Query("SELECT * FROM [|PREFIX|]customers c, [|PREFIX|]customer_groups cg WHERE c.customerid = '{$custid}' AND cg.customergroupid = c.custgroupid AND cg.groupname = 'Walk In' ");
     if ($GLOBALS['ISC_CLASS_DB']->CountResult($query) > 0) {
         $ordstatus = '10';
     } else {
         $ordstatus = $data['ordstatus'];
     }
     $billemail = $email;
     $shipemail = $email;
     if ($data['customerType'] == 'anonymous') {
         if (isset($data['anonymousemail']) && !empty($data['anonymousemail'])) {
             $billemail = $email;
             $shipemail = $email;
         } else {
             $billemail = $_POST['ordbillemail'];
             $shipemail = $_POST['ordshipemail'];
         }
     }
     $newOrder = array('paymentmethod' => $data['orderpaymentmodule'], 'customerid' => $data['ordcustid'], 'billingaddress' => $billingDetails, 'ordbillemail' => $billemail, 'ordshipemail' => $shipemail, 'ordbillphone' => $billingDetails['shipphone'], 'geoipcountry' => $billingDetails['shipcountry'], 'geoipcountrycode' => GetCountryISO2ByName($billingDetails['shipcountry']), 'vendorid' => $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId(), 'giftcertificates' => $this->GetCartApi()->GetGiftCertificates(), 'shippingcost' => $orderSummary['shippingCost'], 'handlingcost' => $orderSummary['handlingCost'], 'pending_token' => GenerateOrderToken(), 'itemtotal' => $orderSummary['subtotal'], 'taxcost' => $orderSummary['taxCost'], 'taxrate' => $orderSummary['taxRate'], 'taxname' => $orderSummary['taxName'], 'giftcertificateamount' => $orderSummary['giftCertificateTotal'], 'companygiftcertificateamount' => $orderSummary['companyGiftCertificateTotal'], 'gatewayamount' => $orderSummary['adjustedTotalCost'], 'totalincludestax' => $orderSummary['taxIncluded'], 'shippingprovider' => $orderSummary['shippingMethod'], 'shippingmodule' => $orderSummary['shippingModule'], 'totalcost' => $orderSummary['total'], 'ordstatus' => 0, 'isdigitalorder' => (int) $this->GetCartApi()->AllProductsInCartAreIntangible(), 'currencyid' => $defaultCurrency['currencyid'], 'currencyexchangerate' => 0, 'ordercomments' => @$data['ordcustmessage'], 'ordnotes' => @$data['ordnotes'], 'products' => $this->GetCartApi()->GetProductsInCart(), 'ordtrackingno' => $data['ordtrackingno'], 'orderowner' => $loggeduser['pk_userid']);
     if (isset($data['ordbillsaveAddress'])) {
         $newOrder['billingaddress']['saveAddress'] = 1;
         if (gzte11(ISC_MEDIUMPRINT)) {
             $newOrder['billingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_BILLING);
         }
     }
     if ($newOrder['paymentmethod'] == 'manual') {
         $newOrder['paymentmethodname'] = GetLang('ManualPayment');
     } else {
         if ($newOrder['paymentmethod'] == 'giftcertificate') {
             $newOrder['giftcertificateamount'] = $orderSummary['total'];
         } else {
             if ($newOrder['paymentmethod'] == 'storecredit') {
                 $newOrder['storecreditamount'] = $orderSummary['total'];
             } else {
                 if ($newOrder['paymentmethod'] == 'custom') {
                     $newOrder['paymentmethodname'] = $data['paymentField']['custom']['name'];
                 } else {
                     if ($newOrder['paymentmethod'] == 'paypal_admin') {
                         // added new condition for paypal payment option - vikas
                         $newOrder['paymentmethodname'] = GetLang('PaypalPayment');
                     } else {
                         if ($newOrder['paymentmethod'] == 'googlecheckout_admin') {
                             $newOrder['paymentmethodname'] = GetLang('GooglePayment');
                         } else {
                             if ($newOrder['paymentmethod'] == 'creditcard') {
                                 $newOrder['paymentmethodname'] = GetLang('CreditCardPayment');
                             } else {
                                 if ($newOrder['paymentmethod'] == 'cash') {
                                     $newOrder['paymentmethodname'] = GetLang('CashPayment');
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     if (!$this->GetCartApi()->AllProductsInCartAreIntangible()) {
         if (isset($data['shippingUseBilling']) && $data['shippingUseBilling'] == 1) {
             $newOrder['shippingaddress'] = $newOrder['billingaddress'];
         } else {
             $newOrder['shippingaddress'] = $shippingDetails;
             if (isset($data['ordshipsaveAddress']) && gzte11(ISC_MEDIUMPRINT)) {
                 /**
                  * This is a bit tricky. We need to convert these shipping fields to use the billing
                  * field IDs when saving in the shipping_addresses table as they all use the billing
                  * fields on the frontend
                  */
                 $shippingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_SHIPPING, true);
                 $shippingKeys = array_keys($shippingFields);
                 $shippingMap = $GLOBALS['ISC_CLASS_FORM']->mapAddressFieldList(FORMFIELDS_FORM_SHIPPING, $shippingKeys);
                 $shippingSessData = array();
                 foreach ($shippingMap as $fieldId => $newBillingId) {
                     if ($shippingFields[$fieldId]->record['formfieldprivateid'] !== '') {
                         continue;
                     }
                     $shippingSessData[$newBillingId] = $shippingFields[$fieldId]->getValue();
                 }
                 $newOrder['shippingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($shippingSessData);
             }
         }
         if (isset($data['ordshipsaveAddress'])) {
             $newOrder['shippingaddress']['saveAddress'] = 1;
         }
     }
     if ($orderId > 0) {
         $existingOrder = GetOrder($orderId);
         $newOrder['vendorid'] = $existingOrder['ordvendorid'];
         $newOrder['extraInfo'] = @unserialize($existingOrder['extrainfo']);
         //Alandy_2011-14-20 debug credit amount error! recalculate the gatewayamount,fetch the gatewayamount from profer order is wrong!
         //$newOrder['gatewayamount'] = $existingOrder['ordgatewayamount'];
         $newOrder['storecreditamount'] = $existingOrder['ordstorecreditamount'];
         $newOrder['currencyid'] = $existingOrder['ordcurrencyid'];
         $newOrder['currencyexchangerate'] = $existingOrder['ordcurrencyexchangerate'];
         $newOrder['orderid'] = $orderId;
         $newOrder['orddate'] = $existingOrder['orddate'];
         $newOrder['ordipaddress'] = $existingOrder['ordipaddress'];
     }
     /**
      * Save the billing/shipping custom fields for the order
      */
     if (gzte11(ISC_MEDIUMPRINT)) {
         if (isId($orderId) && isset($existingOrder['ordformsessionid']) && isId($existingOrder['ordformsessionid'])) {
             $GLOBALS['ISC_CLASS_FORM']->saveFormSession(array(FORMFIELDS_FORM_BILLING, FORMFIELDS_FORM_SHIPPING), true, $existingOrder['ordformsessionid']);
         } else {
             $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(array(FORMFIELDS_FORM_BILLING, FORMFIELDS_FORM_SHIPPING));
             if (isId($formSessionId)) {
                 $newOrder['ordformsessionid'] = $formSessionId;
             }
         }
     }
     // dada.wang 20120406 save cgc change
     $cgces = $this->GetCartApi()->Get('COMPANYGIFTCERTIFICATES');
     if (is_array($cgces) && !empty($cgces)) {
         $newOrder['companygiftcertificates'] = $cgces;
     }
     $entity = new ISC_ENTITY_ORDER();
     if (isset($existingOrder)) {
         $newOrder['adminflag'] = 1;
         //dada.wang 2012-04-10 if has gc or cgc was remove then use this function to remove it
         $this->RemoveGCAndCGC($newOrder);
         if (!$entity->edit($newOrder)) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
     } else {
         $newOrder['adminflag'] = 1;
         $data['orderid'] = $entity->add($newOrder);
         if (!$data['orderid']) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
         $newOrder['orderid'] = $data['orderid'];
     }
     // If one or more gift certificates were used we need to apply them to this order
     if ($newOrder['giftcertificateamount'] > 0 && isset($newOrder['giftcertificates']) && !empty($newOrder['giftcertificates'])) {
         $usedCertificates = array();
         $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES'] = GetClass('ISC_GIFTCERTIFICATES');
         $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES']->ApplyGiftCertificatesToOrder($newOrder['orderid'], $newOrder['totalcost'], $newOrder['giftcertificates'], $usedCertificates);
     }
     // Add by NI_20100827_Jack
     // If one or more gift certificates were used we need to apply them to this order
     if ($newOrder['companygiftcertificateamount'] > 0 && isset($newOrder['companygiftcertificates']) && !empty($newOrder['companygiftcertificates'])) {
         $usedCertificates = array();
         $GLOBALS['ISC_CLASS_COMPANY_GIFT_CERTIFICATES'] = GetClass('ISC_COMPANYGIFTCERTIFICATES');
         $GLOBALS['ISC_CLASS_COMPANY_GIFT_CERTIFICATES']->ApplyCompanyGiftCertificatesToOrder($newOrder['orderid'], $newOrder['totalcost'], $newOrder['companygiftcertificates'], $usedCertificates);
     }
     $GLOBALS['ISC_CLASS_DB']->CommitTransaction();
     // Did the payment method have any info it needs to save? Save it
     $provider = null;
     GetModuleById('checkout', $provider, $data['orderpaymentmodule']);
     if (is_object($provider) && method_exists($provider, 'SaveManualPaymentFields')) {
         $fields = $data['paymentField'][$data['orderpaymentmodule']];
         $provider->SaveManualPaymentFields(GetOrder($data['orderid'], false, false), $fields);
     }
     if ($data['ordstatus'] != $newOrder['ordstatus']) {
         UpdateOrderStatus($data['orderid'], $data['ordstatus'], false);
     }
     // If we're emailing the customer about their order, send it now
     if (isset($data['emailinvoice']) && $data['emailinvoice'] == 1) {
         EmailInvoiceToCustomer($data['orderid']);
     }
     unset($_SESSION['ORDER_MANAGER'][$data['orderSession']]);
     /*************************************************************
     					Alterations done by Mayank Jaitly on 28 June 2010
     			**************************************************************/
     /*	
     // commented the below code as this is not needed.
     	$customerYMMdata=array(
     						   	'year' => $data['searchyear'],
     							'make' => $data['searchmake'],
     							'model' => MakeURLNormal($data['searchmodel']),
     							'bed_size' =>$data['bedsize'],
     							'cab_size' =>$data['cabsize']
     							
     						   );
     							   
     	$clarion_entity = new ISC_ADMIN_CLARION();
     	$ymmID=$clarion_entity->fnSaveUserYMM($customerYMMdata,$data['ordcustid'],$_REQUEST['customerType'],$data['orderid']);
     */
     /***********************	End of Alteration		*********/
     /***************************************************************
     				Code Added by Mayank Jaitly on 29 June 2010
     			****************************************************************/
     // commented the below code as this is not needed.
     //	$clarion_entity->fnUpdateOrderYMM($data['orderid'],$ymmID);
     /********************* End of code   **************************/
     return $data['orderid'];
 }
Ejemplo n.º 26
0
 /**
  * Handle the merchant-calculations-callback request from google. This is for calculating post checkout
  * adjustments to the order total such as tax, shipping , gift certificates and coupon codes
  *
  * @param Array $data The parsed array of data representing the google request
  *
  * @return void
  **/
 private function HandleMerchantCallback($data)
 {
     $root = 'merchant-calculation-callback';
     $this->LoadCart($data[$root]['shopping-cart']['merchant-private-data']['VALUE']);
     include_once dirname(__FILE__) . '/library/googlemerchantcalculations.php';
     include_once dirname(__FILE__) . '/library/googleresult.php';
     $currency = GetDefaultCurrency();
     $merchant_calc = new GoogleMerchantCalculations($currency['currencycode']);
     $addresses = $this->get_arr_result($data[$root]['calculate']['addresses']['anonymous-address']);
     //mysql_query("INSERT INTO isc_orderlogs(ordervalue) VALUES ( 'addresses: ".print_r(count($addresses),true)."')");
     foreach ($addresses as $curr_address) {
         $curr_id = $curr_address['id'];
         $country = $curr_address['country-code']['VALUE'];
         $city = $curr_address['city']['VALUE'];
         $region = $curr_address['region']['VALUE'];
         $postal_code = $curr_address['postal-code']['VALUE'];
         // Loop through each shipping method if merchant-calculated shipping
         // support is to be provided
         if (isset($data[$root]['calculate']['shipping']['method'])) {
             $shipping = $this->get_arr_result($data[$root]['calculate']['shipping']['method']);
             foreach ($shipping as $curr_ship) {
                 $costs = $this->CalculateShippingCost($curr_address);
                 $name = $curr_ship['name'];
                 $zoneInfo = $costs['zone'];
                 unset($costs['zone']);
                 $merchant_result = new GoogleResult($curr_id);
                 $costs = current($costs);
                 $found = false;
                 $price = 0;
                 foreach ($costs as $key => $cost) {
                     if ($zoneInfo['zoneid'] == 1) {
                         $shipping_name = $cost['description'];
                     } else {
                         $shipping_name = $cost['description'] . ' (' . $zoneInfo['zonename'] . ')';
                     }
                     if ($name != $shipping_name) {
                         continue;
                     }
                     //Compute the price for this shipping method and address id
                     if (isset($cost['price'])) {
                         $price = $cost['price'];
                     }
                     $merchant_result->SetShippingDetails($name, $price, 'true');
                     $found = true;
                     break;
                 }
                 if (!$found) {
                     $merchant_result->SetShippingDetails($name, $price, 'false');
                 }
                 if ($data[$root]['calculate']['tax']['VALUE'] == "true") {
                     //Compute tax for this address id and shipping type
                     $amount = $this->RecalculateTax($data, $price, $name);
                     $merchant_result->SetTaxable(true);
                     $merchant_result->SetTaxDetails($amount);
                 }
                 if (isset($data[$root]['calculate']['merchant-code-strings']['merchant-code-string'])) {
                     $codes = $this->get_arr_result($data[$root]['calculate']['merchant-code-strings']['merchant-code-string']);
                     foreach ($codes as $curr_code) {
                         $giftcert = $this->ValidateGiftCertificate($curr_code['code'], $data);
                         if ($giftcert === false) {
                             $coupons = $this->ValidateCouponCode($curr_code['code'], $data, $cc_count = count($codes));
                             $merchant_result->AddCoupons($coupons);
                             /*if( count($codes) > 1 )
                             		{
                             			break;
                             		}*/
                         } else {
                             $merchant_result->AddGiftCertificates($giftcert);
                         }
                     }
                 } else {
                     if (isset($data[$root]['calculate']['merchant-code-strings']) && !isset($data[$root]['calculate']['merchant-code-strings']['merchant-code-string'])) {
                         $googlecheckoutflag = 0;
                         $sescouponvalue = $GLOBALS['ISC_CLASS_CART']->api->GetAppliedCouponCodes();
                         //mysql_query("INSERT INTO isc_orderlogs(ordervalue) VALUES ( 'ses 1: ".print_r($sescouponvalue,true)."')");
                         if (!empty($sescouponvalue)) {
                             foreach ($sescouponvalue as $ccid => $ccval) {
                                 if (array_key_exists('googlecheckout', $ccval)) {
                                     $GLOBALS['ISC_CLASS_CART']->api->RemoveCouponCode($ccval['couponid']);
                                     $googlecheckoutflag = 1;
                                 }
                             }
                             if ($googlecheckoutflag == 1) {
                                 $GLOBALS['ISC_CLASS_CART']->api->UpdateCartInformation();
                             }
                             //$temp_products = $GLOBALS['ISC_CLASS_CART']->api->GetProductsInCart();
                         }
                     }
                 }
                 $merchant_calc->AddResult($merchant_result);
             }
         } else {
             $merchant_result = new GoogleResult($curr_id);
             if ($data[$root]['calculate']['tax']['VALUE'] == "true") {
                 //Compute tax for this address id and shipping type
                 $amount = $this->RecalculateTax($data, 0, '');
                 $merchant_result->SetTaxable(true);
                 $merchant_result->SetTaxDetails($amount);
             }
             if (isset($data[$root]['calculate']['merchant-code-strings']['merchant-code-string'])) {
                 $codes = $this->get_arr_result($data[$root]['calculate']['merchant-code-strings']['merchant-code-string']);
                 foreach ($codes as $curr_code) {
                     $giftcert = $this->ValidateGiftCertificate($curr_code['code'], $data);
                     if ($giftcert === false) {
                         $coupons = $this->ValidateCouponCode($curr_code['code'], $data, $cc_count = count($codes));
                         $merchant_result->AddCoupons($coupons);
                         /*if( count($codes) > 1 )
                         		{
                         			break;
                         		}*/
                     } else {
                         $merchant_result->AddGiftCertificates($giftcert);
                     }
                 }
             } else {
                 if (isset($data[$root]['calculate']['merchant-code-strings']) && !isset($data[$root]['calculate']['merchant-code-strings']['merchant-code-string'])) {
                     $sescouponvalue = $GLOBALS['ISC_CLASS_CART']->api->GetAppliedCouponCodes();
                     //mysql_query("INSERT INTO isc_orderlogs(ordervalue) VALUES ( 'ses 2: ".print_r($sescouponvalue,true)."')");
                     if (!empty($sescouponvalue)) {
                         foreach ($sescouponvalue as $ccid => $ccval) {
                             if (array_key_exists('googlecheckout', $ccval)) {
                                 $GLOBALS['ISC_CLASS_CART']->api->RemoveCouponCode($ccval['couponid']);
                                 $googlecheckoutflag = 1;
                             }
                         }
                         if ($googlecheckoutflag == 1) {
                             $GLOBALS['ISC_CLASS_CART']->api->UpdateCartInformation();
                         }
                         //$temp_products = $GLOBALS['ISC_CLASS_CART']->api->GetProductsInCart();
                     }
                 }
             }
             $merchant_calc->AddResult($merchant_result);
         }
     }
     $this->module->DebugLog($merchant_calc->GetXML());
     $this->response->ProcessMerchantCalculations($merchant_calc);
 }
Ejemplo n.º 27
0
		protected function editOrderSaveAction()
		{
			if (empty($_POST['quoteSession'])) {
				exit;
			}

			$quoteSession = $_POST['quoteSession'];

			/** @var ISC_QUOTE */
			$quote = getClass('ISC_ADMIN_ORDERS')->getQuoteSession($quoteSession);
			if(!$quote) {
				$this->sendEditOrderNoQuoteResponse('saveError');
			}

			try {
				$quote->setCustomerMessage(Interspire_Request::post('customerMessage'));
				$quote->setStaffNotes(Interspire_Request::post('staffNotes'));

				$entity = new ISC_ENTITY_ORDER;

				$currency = GetDefaultCurrency();
				$order = array(
					'ordcurrencyid' => $currency['currencyid'],
					'ordcurrencyexchangerate' => $currency['currencyexchangerate'],
					'ordipaddress' => getIp(),
					'extraInfo' => array(),
					'quote' => $quote,
				);

				$createAccount = false;

				// process customer details to see if an account should be made
				if (Interspire_Request::post('orderFor') == 'new') {
					// this really needs to be split off into another method because it's done both at the front end checkout, in save billing, and in here! -ge
					$password = '';
					$confirmedPassword = '';
					$email = '';
					$accountFormFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_ACCOUNT, true);
					$accountCustomFields = array();
					foreach($accountFormFields as $formFieldId => $formField) {
						$formFieldPrivateId = $formField->record['formfieldprivateid'];

						if (!$formFieldPrivateId) {
							$accountCustomFields[$formFieldId] = $formField->getValue();
						} else if($formFieldPrivateId == 'EmailAddress') {
							$email = $formField->getValue();
						} else if($formFieldPrivateId == 'Password') {
							$password = $formField->getValue();
						} else if($formFieldPrivateId == 'ConfirmPassword') {
							$confirmedPassword = $formField->getValue();
						}
					}

					// shouldn't reach this point with a valid email without all the details already being validated after step 1 > next, so go ahead and assign it to the order
					if ($email) {
						$createAccount = array(
							'addresses' => array(),
							'password' => $password,
							'customFormFields' => $accountCustomFields,
						);

						foreach ($quote->getAllAddresses() as /** @var ISC_QUOTE_ADDRESS */$address) {
							if (!$address->getSaveAddress()) {
								continue;
							}

							$customerAddress = $address->getAsArray();
							$customFields = $address->getCustomFields();
							if (!empty($customFields)) {
								$customerAddress['customFormFields'] = $customFields;

								// Shipping fields need to be mapped back to billing so they can be stored
								if ($address->getType() == ISC_QUOTE_ADDRESS::TYPE_SHIPPING) {
									$newCustomFields = array();
									$map = $GLOBALS['ISC_CLASS_FORM']->mapAddressFieldList(FORMFIELDS_FORM_SHIPPING, array_keys($customFields));
									foreach($map as $oldId => $newId) {
										$newCustomFields[$newId] = $customFields[$oldId];
									}
									$customerAddress['customFormFields'] = $newCustomFields;
								}
							}

							$createAccount['addresses'][] = $customerAddress;
						}
					}
				}

				if ($quote->getOrderId()) {
					$editing = true;
					$adding = false;

					$orderId = $quote->getOrderId();

					$existingOrder = $entity->get($orderId);
					if ($existingOrder['deleted']) {
						// don't allow saving changes for a deleted order
						$errors[] = GetLang('EditDeletedOrderError');
					} else {
						$order['orderid'] = $orderId;
						if (!$entity->edit($order)) {
							$errors[] = $entity->getError();
						}
					}
				} else {
					$editing = false;
					$adding = true;

					$order['orderpaymentmodule'] = '';

					$orderId = $entity->add($order);

					if ($orderId) {
						$quote->setOrderId($orderId);
					} else {
						$errors[] = $entity->getError();
					}
				}

				if (!empty($errors)) {
					$this->sendEditOrderResponse(array(
						'errors' => $errors,
						'stateTransition' => 'saveError',
					));
				}

				// retrieve the created/edited order record
				$order = GetOrder($orderId);

				if ($createAccount) {
					// this function doesn't return anything for error testing
					createOrderCustomerAccount($order, $createAccount);
				}

				// Process a payment
				$paymentMethod = Interspire_Request::post('paymentMethod');

				$providerSuccess = false;

				// Retrieve the payment method details
				$paymentFields = Interspire_Request::post('paymentField');
				if (!empty($paymentFields[$paymentMethod])) {
					$paymentFields = $paymentFields[$paymentMethod];
				}
				else {
					$paymentFields = array();
				}

				if ($quote->getGrandTotalWithStoreCredit() > 0 && ($adding || empty($order['ordpaymentstatus']) || empty($order['orderpaymentmodule'])) && !empty($paymentMethod)) {
					$gatewayAmount = $quote->getGrandTotalWithStoreCredit();

					$provider = null;

					// was a custom payment specified?
					if ($paymentMethod == 'custom') {
						$paymentMethodName = $paymentFields['custom_name'];
						$providerSuccess = true;
					}
					// actual payment module
					else {
						GetModuleById('checkout', $provider, $paymentMethod);
						if(is_object($provider)) {
							$paymentMethodName = $provider->GetDisplayName();

							if (method_exists($provider, 'ProcessManualPayment')) {
								// set the order token as required by various payment methods
								ISC_SetCookie('SHOP_ORDER_TOKEN', $order['ordtoken'], time() + (3600*24), true);
								// make the token immediately available
								$_COOKIE['SHOP_ORDER_TOKEN'] = $order['ordtoken'];

								// process the payment
								$result = $provider->ProcessManualPayment($order, $paymentFields);
								if ($result['result']) {
									$providerSuccess = true;
									$gatewayAmount = $result['amount'];

									FlashMessage(GetLang('OrderPaymentSuccess', array('amount' => FormatPrice($gatewayAmount), 'orderId' => $orderId, 'provider' => $paymentMethodName)), MSG_SUCCESS);
								}
								else {
									$errors[] = GetLang('OrderPaymentFail', array('orderId' => $orderId, 'provider' => $paymentMethodName, 'reason' => $result['message']));
								}
							}
							else {
								// all manual/offline methods will always be successfull
								$providerSuccess = true;
							}
						}
						else {
							// failed to get a payment module
						}
					}
				// if the grand total after minus the coupon,etc is 0 and it's adding order also the payment method is custom.
				} else if ($quote->getGrandTotalWithStoreCredit() == 0 && ($adding || empty($order['ordpaymentstatus']) || empty($order['orderpaymentmodule'])) && $paymentMethod == 'custom') {
					$paymentMethodName = $paymentFields['custom_name'];
					$providerSuccess = true;
				}

				// was payment successfull?
				if ($providerSuccess) {
					// record payment info for the order
					$updatedOrder = array(
						'orderpaymentmethod' 	=> $paymentMethodName,
						'orderpaymentmodule'	=> $paymentMethod,
					);

					$this->db->UpdateQuery("orders", $updatedOrder, "orderid = " . $orderId);

					// set appropriate status for the order
					if ($quote->isDigital()) {
						$newStatus = ORDER_STATUS_COMPLETED;
					}
					else {
						$newStatus = ORDER_STATUS_AWAITING_FULFILLMENT;
					}
					UpdateOrderStatus($orderId, $newStatus, false);

					// email invoice
					if (Interspire_Request::post('emailInvoiceToCustomer')) {
						EmailInvoiceToCustomer($orderId);
					}
				}

				if (!empty($errors)) {
					$response = array(
						'errors' => $errors,
						'stateTransition' => 'saveError',
					);
				}
				else {
					if ($editing) {
						FlashMessage(GetLang('OrderUpdated', array('orderId' => $orderId)), MSG_SUCCESS);
					} else {
						FlashMessage(GetLang('OrderCreated', array('orderId' => $orderId)), MSG_SUCCESS);
					}

					$response = array(
						'stateTransition' => 'saveOk',
					);

					// remove quote object from session after successful save and successful payment
					getClass('ISC_ADMIN_ORDERS')->deleteQuoteSession($quoteSession);
				}

				if ($adding) {
					$response['updateOrderId'] = $orderId;
				}

				$this->sendEditOrderResponse($response);
			} catch (ISC_QUOTE_EXCEPTION $exception) {
				$this->sendEditOrderResponse(array(
					'stateTransition' => 'saveError',
					'errors' => array(
						$exception->getMessage(),
					),
				));
			}
		}
Ejemplo n.º 28
0
 /**
  * Actually save a new order or an updated existing order in the database
  * after it's been validated.
  *
  * @param array An array of details about the order to save.
  * @param int The ID of the existing order if we're updating an order.
  * @return boolean True if successful, false if not.
  */
 private function CommitOrder($data, $orderId = 0)
 {
     $GLOBALS['ISC_CLASS_DB']->StartTransaction();
     /**
      * We need to find our billing/shipping details from the form fields first as it is
      * also used in creating the customer
      */
     $billingDetails = array();
     $shippingDetails = array();
     $billingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_BILLING, true);
     $shippingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_SHIPPING, true);
     $fields = $billingFields + $shippingFields;
     $addressMap = array('FirstName' => 'firstname', 'LastName' => 'lastname', 'CompanyName' => 'company', 'AddressLine1' => 'address1', 'AddressLine2' => 'address2', 'City' => 'city', 'State' => 'state', 'Zip' => 'zip', 'State' => 'state', 'Country' => 'country', 'Phone' => 'phone');
     foreach (array_keys($fields) as $fieldId) {
         $privateName = $fields[$fieldId]->record['formfieldprivateid'];
         if ($privateName == '' || !array_key_exists($privateName, $addressMap)) {
             continue;
         }
         if ($fields[$fieldId]->record['formfieldformid'] == FORMFIELDS_FORM_BILLING) {
             $detailsVar =& $billingDetails;
         } else {
             $detailsVar =& $shippingDetails;
         }
         /**
          * Find the country
          */
         if (isc_strtolower($privateName) == 'country') {
             $detailsVar['shipcountry'] = $fields[$fieldId]->getValue();
             $detailsVar['shipcountryid'] = GetCountryByName($fields[$fieldId]->getValue());
             if (!isId($detailsVar['shipcountryid'])) {
                 $detailsVar['shipcountryid'] = 0;
             }
             /**
              * Else find the state
              */
         } else {
             if (isc_strtolower($privateName) == 'state') {
                 $detailsVar['shipstate'] = $fields[$fieldId]->getValue();
                 $stateInfo = GetStateInfoByName($detailsVar['shipstate']);
                 if ($stateInfo && isId($stateInfo['stateid'])) {
                     $detailsVar['shipstateid'] = $stateInfo['stateid'];
                 } else {
                     $detailsVar['shipstateid'] = 0;
                 }
                 /**
                  * Else the rest
                  */
             } else {
                 $detailsVar['ship' . $addressMap[$privateName]] = $fields[$fieldId]->getValue();
             }
         }
     }
     // If we're creating an account for this customer, create it now
     if ($data['ordcustid'] == 0 && $data['customerType'] == 'new') {
         $customerData = array('email' => $data['custconemail'], 'password' => $data['custpassword'], 'firstname' => $billingDetails['shipfirstname'], 'lastname' => $billingDetails['shiplastname'], 'company' => $billingDetails['shipcompany'], 'phone' => $billingDetails['shipphone'], 'token' => GenerateCustomerToken(), 'customergroupid' => $data['custgroupid'], 'storecredit' => DefaultPriceFormat($data['custstorecredit']));
         /**
          * Save the customer custom fields
          */
         if (gzte11(ISC_MEDIUMPRINT)) {
             $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_ACCOUNT);
             if (isId($formSessionId)) {
                 $customerData['custformsessionid'] = $formSessionId;
             }
         }
         $entity = new ISC_ENTITY_CUSTOMER();
         $data['ordcustid'] = $entity->add($customerData);
         if (!$data['ordcustid']) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
     }
     $orderSummary = $this->CalculateOrderSummary();
     $defaultCurrency = GetDefaultCurrency();
     $email = '';
     if (isset($data['custconemail']) && $data['customerType'] == 'new') {
         $email = $data['custconemail'];
     } else {
         if (isset($data['anonymousemail']) && $data['customerType'] == 'anonymous') {
             $email = $data['anonymousemail'];
         }
     }
     $newOrder = array('paymentmethod' => $data['orderpaymentmodule'], 'customerid' => $data['ordcustid'], 'billingaddress' => $billingDetails, 'ordbillemail' => $email, 'ordbillphone' => $billingDetails['shipphone'], 'geoipcountry' => $billingDetails['shipcountry'], 'geoipcountrycode' => GetCountryISO2ByName($billingDetails['shipcountry']), 'vendorid' => $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId(), 'giftcertificates' => $this->GetCartApi()->GetGiftCertificates(), 'shippingcost' => $orderSummary['shippingCost'], 'handlingcost' => $orderSummary['handlingCost'], 'pending_token' => GenerateOrderToken(), 'itemtotal' => $orderSummary['subtotal'], 'taxcost' => $orderSummary['taxCost'], 'taxrate' => $orderSummary['taxRate'], 'taxname' => $orderSummary['taxName'], 'giftcertificateamount' => $orderSummary['giftCertificateTotal'], 'gatewayamount' => $orderSummary['adjustedTotalCost'], 'totalincludestax' => $orderSummary['taxIncluded'], 'shippingprovider' => $orderSummary['shippingMethod'], 'shippingmodule' => $orderSummary['shippingModule'], 'totalcost' => $orderSummary['total'], 'ordstatus' => 0, 'isdigitalorder' => (int) $this->GetCartApi()->AllProductsInCartAreIntangible(), 'currencyid' => $defaultCurrency['currencyid'], 'currencyexchangerate' => 0, 'ordercomments' => @$data['ordcustmessage'], 'ordnotes' => @$data['ordnotes'], 'products' => $this->GetCartApi()->GetProductsInCart(), 'ordtrackingno' => $data['ordtrackingno']);
     if (isset($data['ordbillsaveAddress'])) {
         $newOrder['billingaddress']['saveAddress'] = 1;
         if (gzte11(ISC_MEDIUMPRINT)) {
             $newOrder['billingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_BILLING);
         }
     }
     if ($newOrder['paymentmethod'] == 'manual') {
         $newOrder['paymentmethodname'] = GetLang('ManualPayment');
     } else {
         if ($newOrder['paymentmethod'] == 'giftcertificate') {
             $newOrder['giftcertificateamount'] = $orderSummary['total'];
         } else {
             if ($newOrder['paymentmethod'] == 'storecredit') {
                 $newOrder['storecreditamount'] = $orderSummary['total'];
             } else {
                 if ($newOrder['paymentmethod'] == 'custom') {
                     $newOrder['paymentmethodname'] = $data['paymentField']['custom']['name'];
                 }
             }
         }
     }
     if (!$this->GetCartApi()->AllProductsInCartAreIntangible()) {
         if (isset($data['shippingUseBilling']) && $data['shippingUseBilling'] == 1) {
             $newOrder['shippingaddress'] = $newOrder['billingaddress'];
         } else {
             $newOrder['shippingaddress'] = $shippingDetails;
             if (isset($data['ordshipsaveAddress']) && gzte11(ISC_MEDIUMPRINT)) {
                 /**
                  * This is a bit tricky. We need to convert these shipping fields to use the billing
                  * field IDs when saving in the shipping_addresses table as they all use the billing
                  * fields on the frontend
                  */
                 $shippingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_SHIPPING, true);
                 $shippingKeys = array_keys($shippingFields);
                 $shippingMap = $GLOBALS['ISC_CLASS_FORM']->mapAddressFieldList(FORMFIELDS_FORM_SHIPPING, $shippingKeys);
                 $shippingSessData = array();
                 foreach ($shippingMap as $fieldId => $newBillingId) {
                     if ($shippingFields[$fieldId]->record['formfieldprivateid'] !== '') {
                         continue;
                     }
                     $shippingSessData[$newBillingId] = $shippingFields[$fieldId]->getValue();
                 }
                 $newOrder['shippingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($shippingSessData);
             }
         }
         if (isset($data['ordshipsaveAddress'])) {
             $newOrder['shippingaddress']['saveAddress'] = 1;
         }
     }
     if ($orderId > 0) {
         $existingOrder = GetOrder($orderId);
         $newOrder['vendorid'] = $existingOrder['ordvendorid'];
         $newOrder['extraInfo'] = @unserialize($existingOrder['extrainfo']);
         $newOrder['gatewayamount'] = $existingOrder['ordgatewayamount'];
         $newOrder['storecreditamount'] = $existingOrder['ordstorecreditamount'];
         $newOrder['currencyid'] = $existingOrder['ordcurrencyid'];
         $newOrder['currencyexchangerate'] = $existingOrder['ordcurrencyexchangerate'];
         $newOrder['orderid'] = $orderId;
         $newOrder['orddate'] = $existingOrder['orddate'];
         $newOrder['ordipaddress'] = $existingOrder['ordipaddress'];
     }
     /**
      * Save the billing/shipping custom fields for the order
      */
     if (gzte11(ISC_MEDIUMPRINT)) {
         if (isId($orderId) && isset($existingOrder['ordformsessionid']) && isId($existingOrder['ordformsessionid'])) {
             $GLOBALS['ISC_CLASS_FORM']->saveFormSession(array(FORMFIELDS_FORM_BILLING, FORMFIELDS_FORM_SHIPPING), true, $existingOrder['ordformsessionid']);
         } else {
             $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(array(FORMFIELDS_FORM_BILLING, FORMFIELDS_FORM_SHIPPING));
             if (isId($formSessionId)) {
                 $newOrder['ordformsessionid'] = $formSessionId;
             }
         }
     }
     $entity = new ISC_ENTITY_ORDER();
     if (isset($existingOrder)) {
         if (!$entity->edit($newOrder)) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
     } else {
         $data['orderid'] = $entity->add($newOrder);
         if (!$data['orderid']) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
     }
     // If one or more gift certificates were used we need to apply them to this order
     if ($newOrder['giftcertificateamount'] > 0 && isset($newOrder['giftcertificates']) && !empty($newOrder['giftcertificates'])) {
         $usedCertificates = array();
         $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES'] = GetClass('ISC_GIFTCERTIFICATES');
         $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES']->ApplyGiftCertificatesToOrder($newOrder['orderid'], $newOrder['totalcost'], $newOrder['giftcertificates'], $usedCertificates);
     }
     $GLOBALS['ISC_CLASS_DB']->CommitTransaction();
     // Did the payment method have any info it needs to save? Save it
     $provider = null;
     GetModuleById('checkout', $provider, $data['orderpaymentmodule']);
     if (is_object($provider) && method_exists($provider, 'SaveManualPaymentFields')) {
         $fields = $data['paymentField'][$data['orderpaymentmodule']];
         $provider->SaveManualPaymentFields(GetOrder($data['orderid'], false, false), $fields);
     }
     if ($data['ordstatus'] != $newOrder['ordstatus']) {
         UpdateOrderStatus($data['orderid'], $data['ordstatus'], false);
     }
     // If we're emailing the customer about their order, send it now
     if (isset($data['emailinvoice']) && $data['emailinvoice'] == 1) {
         EmailInvoiceToCustomer($data['orderid']);
     }
     unset($_SESSION['ORDER_MANAGER'][$data['orderSession']]);
     return $data['orderid'];
 }
Ejemplo n.º 29
0
 /**
  * Build and format the message to be sent
  */
 private function BuildSmsMessage()
 {
     // We'll use the SMSMessageContents variable from the modules.ini language file
     $message = sprintf(GetLang('SMSMessageContents'), $this->_orderid, $GLOBALS['StoreName'], $this->_ordernumitems, FormatPrice($this->_ordertotal, false, true, false, GetDefaultCurrency()), $this->_orderpaymentmethod);
     return urlencode($message);
 }
Ejemplo n.º 30
0
/**
 *	Send an email notification to a customer when the status of their order changes.
 *
 * @param int The ID of the order to email the invoice for.
 * @return boolean True if successful.
 */
function EmailOnStatusChange($orderId, $status)
{
	// Load the order
	$order = GetOrder($orderId);
	if (!$order) {
		return false;
	}

	// Load the customer we'll be contacting
	if ($order['ordcustid'] > 0) {
		$customer = GetCustomer($order['ordcustid']);
		$GLOBALS['ViewOrderStatusLink'] = '<a href="'.$GLOBALS['ShopPathSSL'].'/orderstatus.php">'.GetLang('ViewOrderStatus').'</a>';
	} else {
		$customer['custconemail'] = $order['ordbillemail'];
		$customer['custconfirstname'] = $order['ordbillfirstname'];
		$GLOBALS['ViewOrderStatusLink'] = '';
	}

	if (empty($customer['custconemail'])) {
		return;
	}

	// All prices in the emailed invoices will be shown in the default currency of the store
	$defaultCurrency = GetDefaultCurrency();

	$statusName = GetOrderStatusById($status);
	$GLOBALS['OrderStatusChangedHi'] = sprintf(GetLang('OrderStatusChangedHi'), isc_html_escape($customer['custconfirstname']));
	$GLOBALS['OrderNumberStatusChangedTo'] = sprintf(GetLang('OrderNumberStatusChangedTo'), $order['orderid'], $statusName);
	$GLOBALS['OrderTotal'] = FormatPrice($order['total_inc_tax'], false, true, false, $defaultCurrency, true);
	$GLOBALS['DatePlaced'] = CDate($order['orddate']);

	if ($order['orderpaymentmethod'] === 'giftcertificate') {
		$GLOBALS['PaymentMethod'] = GetLang('PaymentGiftCertificate');
	}
	else if ($order['orderpaymentmethod'] === 'storecredit') {
		$GLOBALS['PaymentMethod'] = GetLang('PaymentStoreCredit');
	}
	else {
		$GLOBALS['PaymentMethod'] = $order['orderpaymentmethod'];
	}

	$query = "
		SELECT COUNT(*)
		FROM [|PREFIX|]order_products
		WHERE ordprodtype='digital'
		AND orderorderid='".$GLOBALS['ISC_CLASS_DB']->Quote($orderId)."'
	";

	$numDigitalProducts = $GLOBALS['ISC_CLASS_DB']->FetchOne($query);

	$emailTemplate = FetchEmailTemplateParser();

	$GLOBALS['SNIPPETS']['CartItems'] = "";

	if (OrderIsComplete($status) && $numDigitalProducts > 0) {
		$query = "
			SELECT *
			FROM [|PREFIX|]order_products op INNER JOIN [|PREFIX|]products p ON (op.ordprodid = p.productid)
			WHERE ordprodtype='digital'
			AND orderorderid='".$GLOBALS['ISC_CLASS_DB']->Quote($orderId)."'
		";
		$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
		while ($product_row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
			$GLOBALS['ProductOptions'] = '';
			$GLOBALS['ProductQuantity'] = $product_row['ordprodqty'];
			$GLOBALS['ProductName'] = isc_html_escape($product_row['ordprodname']);

			$GLOBALS['ISC_CLASS_ACCOUNT'] = GetClass('ISC_ACCOUNT');
			$DownloadItemEncrypted = $GLOBALS['ISC_CLASS_ACCOUNT']->EncryptDownloadKey($product_row['orderprodid'], $product_row['ordprodid'], $orderId, $order['ordtoken']);
			$GLOBALS['DownloadsLink'] = $GLOBALS['ShopPathSSL'].'/account.php?action=download_item&amp;data='.$DownloadItemEncrypted;

			$GLOBALS['SNIPPETS']['CartItems'] .= $emailTemplate->GetSnippet("StatusCompleteDownloadItem");
		}
	}

	$GLOBALS['SNIPPETS']['OrderTrackingLink'] = "";

	$shipments = $GLOBALS['ISC_CLASS_DB']->Query("
		SELECT shipmentid, shipdate, shiptrackno, shipping_module, shipmethod, shipcomments
		FROM [|PREFIX|]shipments
		WHERE shiporderid = " . (int)$orderId . "
		ORDER BY shipdate, shipmentid
	");

	$GLOBALS['TrackingLinkList'] = '';

	while($shipment = $GLOBALS['ISC_CLASS_DB']->Fetch($shipments)) {
		if (!$shipment['shiptrackno']) {
			continue;
		}

		GetModuleById('shipping', /** @var ISC_SHIPPING */$module, $shipment['shipping_module']);

		if ($module) {
			$link = $module->GetTrackingLink($shipment['shiptrackno']);
			if ($link) {
				$link = '<a href="' . isc_html_escape($link) . '" target="_blank">' . $shipment['shiptrackno'] . '</a>';
			} else {
				$link = $shipment['shiptrackno'];
			}
		} else {
			$link = $shipment['shiptrackno'];
		}

		if($shipment['shipmethod']) {
			$link .= ' (' . $shipment['shipmethod'] . ')';
		}

		if ($link) {
			$GLOBALS['TrackingLinkList'] .= '<li>' . $link . '</li>';
		}
	}

	if (empty($GLOBALS['TrackingLinkList'])) {
		$GLOBALS['TrackingLinkList'] = GetLang('NoTrackingNumbersYet');
	} else {
		$GLOBALS['TrackingLinkList'] = '<ul>' . $GLOBALS['TrackingLinkList'] . '</ul>';
	}

	// Set up tracking numbers for orders. Whilst we don't have tracking numbers
	// on orders any longer, this code is being kept for legacy reasons where
	// orders may already have a tracking number saved. To be removed in a future
	// version.
	if (!empty($order['ordtrackingno'])) {
		$GLOBALS['HideTrackingText'] = "";
		$GLOBALS['OrderTrackingNo'] = isc_html_escape($order['ordtrackingno']);

		// Let's instantiate an object for the shipper
		$shipper_object = false;
		if ($order['ordershipmodule'] != "" && GetModuleById('shipping', $shipper_object, $order['ordershipmodule'])) {
			// Does it have a link to track the order?
			if ($shipper_object->GetTrackingLink() != "") {
				// Show the tracking link
				$GLOBALS['TrackURL'] = $shipper_object->GetTrackingLink($order['ordtrackingno']);
				$GLOBALS['SNIPPETS']['OrderTrackingLink'] = $emailTemplate->GetSnippet("OrderTrackingLink");
			}
		}
	}

	if (empty($GLOBALS['SNIPPETS']['CartItems'])) {
		$emailTemplate->SetTemplate("order_status_email");
	} else {
		$emailTemplate->SetTemplate("order_status_downloads_email");
	}
	$message = $emailTemplate->ParseTemplate(true);

	// Create a new email API object to send the email
	$store_name = GetConfig('StoreName');
	$subject = GetLang('OrderStatusChangedSubject');

	require_once(ISC_BASE_PATH . "/lib/email.php");
	$obj_email = GetEmailClass();
	$obj_email->Set('CharSet', GetConfig('CharacterSet'));
	$obj_email->From(GetConfig('OrderEmail'), $store_name);
	$obj_email->Set('Subject', $subject);
	$obj_email->AddBody("html", $message);
	$obj_email->AddRecipient($customer['custconemail'], '', "h");
	$email_result = $obj_email->Send();

	if ($email_result['success']) {
		return true;
	}
	else {
		return false;
	}
}