public function ProcessGatewayPing()
		{
			$this->SetOrderData(LoadPendingOrdersByToken($_REQUEST['USER1']));

			if($this->GetGatewayAmount() == 0) {
				return false;
			}

			$orderid = $this->GetCombinedOrderId();

			$hash = md5($GLOBALS['ISC_CFG']['serverStamp'].$_REQUEST['AMOUNT'].$orderid.$_REQUEST['USER1'].$this->GetValue('paypallogin').$this->GetValue('paypalpartner'));

			if ($_REQUEST['USER2'] != $hash) {
				$GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang($this->_languagePrefix.'HashMismatch'));
				return false;
			}

			if (!isset($_REQUEST['INVOICE']) || $orderid != $_REQUEST['INVOICE']) {
				$GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang($this->_languagePrefix.'OrderMismatch'), sprintf("Sent %s. Received %s", $orderid, $_REQUEST['INVOICE']));
				return false;
			}

			if ($this->GetGatewayAmount() != $_REQUEST['AMOUNT']) {
				$GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang($this->_languagePrefix.'PaymentMismatch'), sprintf("Sent %s. Received %s", $this->GetGatewayAmount(), $_REQUEST['AMOUNT']));
				return false;
			}

			if ($_REQUEST['RESULT'] == 0 && $_REQUEST['RESPMSG'] == 'Approved') {


				$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($_REQUEST['USER3']);
				}

				$GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess(array('payment', $this->GetName()), GetLang($this->_languagePrefix.'Success'));

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

				return true;
			}

//			$transactionId = $_REQUEST['PNREF'];
			return false;
		}
		private function updateMultiOrderStatusRequestAction()
		{
			$success = (int)@$_REQUEST['success'];
			$failed = (int)@$_REQUEST['failed'];
			$result = $GLOBALS['ISC_CLASS_DB']->Query("SELECT * FROM [|PREFIX|]order_status WHERE statusid='" . $GLOBALS['ISC_CLASS_DB']->Quote(@$_REQUEST['statusId']) . "'");

			if (isId(@$_REQUEST['orderId']) && isId(@$_REQUEST['statusId']) && ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) && UpdateOrderStatus($_REQUEST['orderId'], $_REQUEST['statusId'])) {
				echo '1';
				$success++;
			} else {
				echo '0';
				$failed++;
			}

			$message = sprintf(GetLang('OrderUpdateStatusReport'), $success, $row['statusdesc']);
			if ($failed) {
				$message .= sprintf(GetLang('OrderUpdateStatusReportFail'), $failed);
			}

			MessageBox($message, MSG_SUCCESS);
			exit;
		}
 public function ProcessGatewayPing()
 {
     if (!isset($_POST['ordertoken'])) {
         $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang($this->_languagePrefix . 'ErrorInvalid'));
         return false;
     }
     $this->SetOrderData(LoadPendingOrdersByToken($_POST['ordertoken']));
     if (!isset($_POST['hash']) || !isset($_POST['amount']) || !isset($_POST['currency']) || !isset($_POST['orderref']) || !isset($_POST['ordertoken'])) {
         $this->TransferToProvider('Card Details Invalid', $_POST['ordertoken']);
     }
     if ($_POST['hash'] != md5($this->GetValue('SecretWord') . $_POST['orderref'] . $this->GetValue('MerchantId') . $_POST['amount'] . $_POST['currency'])) {
         $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang($this->_languagePrefix . 'ErrorInvalid'));
         return false;
     }
     $updatedOrder = array('ordpayproviderid' => $_REQUEST['streference'], 'ordpaymentstatus' => 'captured');
     $this->UpdateOrders($updatedOrder);
     foreach ($this->GetOrders() as $orderId => $order) {
         $status = ORDER_STATUS_AWAITING_FULFILLMENT;
         // If it's a digital order & awaiting fulfillment, automatically complete it
         if ($order['ordisdigital']) {
             $status = ORDER_STATUS_COMPLETED;
         }
         UpdateOrderStatus($orderId, $status);
     }
     $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess(array('payment', $this->GetName()), GetLang($this->_languagePrefix . 'Success'));
     header('Location: ' . $GLOBALS['ShopPath'] . '/finishorder.php');
     return true;
 }
 public function ProcessGatewayPing()
 {
     $this->SetOrderData(LoadPendingOrdersByToken($_REQUEST['USER1']));
     if ($this->GetGatewayAmount() == 0) {
         return false;
     }
     $orderid = $this->GetCombinedOrderId();
     $hash = md5($GLOBALS['ISC_CFG']['serverStamp'] . $_REQUEST['AMOUNT'] . $orderid . $_REQUEST['USER1'] . $this->GetValue('paypallogin') . $this->GetValue('paypalpartner'));
     if ($_REQUEST['USER2'] != $hash) {
         $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang($this->_languagePrefix . 'HashMismatch'));
         return false;
     }
     if (!isset($_REQUEST['INVOICE']) || $orderid != $_REQUEST['INVOICE']) {
         $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang($this->_languagePrefix . 'OrderMismatch'), sprintf("Sent %s. Received %s", $orderid, $_REQUEST['INVOICE']));
         return false;
     }
     if ($this->GetGatewayAmount() != $_REQUEST['AMOUNT']) {
         $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang($this->_languagePrefix . 'PaymentMismatch'), sprintf("Sent %s. Received %s", $this->GetGatewayAmount(), $_REQUEST['AMOUNT']));
         return false;
     }
     if ($_REQUEST['RESULT'] == 0 && $_REQUEST['RESPMSG'] == 'Approved') {
         $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess(array('payment', $this->GetName()), GetLang($this->_languagePrefix . 'Success'));
         // Update the status for all orders that we've just received the payment for
         foreach ($this->GetOrders() as $orderId => $order) {
             $status = ORDER_STATUS_AWAITING_FULFILLMENT;
             // If it's a digital order & awaiting fulfillment, automatically complete it
             if ($order['ordisdigital'] && ORDER_STATUS_AWAITING_FULFILLMENT) {
                 $status = ORDER_STATUS_COMPLETED;
             }
             UpdateOrderStatus($orderId, $status);
         }
         return true;
     }
     //			$transactionId = $_REQUEST['PNREF'];
     return false;
 }
 public function ProcessGatewayPing()
 {
     $siteid = $_REQUEST['site_id'];
     $productid = $_REQUEST['product_id'];
     $email = $_REQUEST['email'];
     $country = $_REQUEST['country'];
     $name = $_REQUEST['name'];
     $city = $_REQUEST['city'];
     $street = $_REQUEST['street'];
     $state = $_REQUEST['state'];
     $zip = $_REQUEST['zip'];
     $hash = $_REQUEST['cs1'];
     $session = $_REQUEST['cs2'];
     $currency = $_REQUEST['currency'];
     $siteCurrency = GetDefaultCurrency();
     $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess(array('payment', $this->GetName()), 'ChronoPay Pingback');
     if ($currency != $siteCurrency['currencycode']) {
         $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), sprintf(GetLang($this->_languagePrefix . 'CurrencyMismatch'), $siteCurrency['currencycode'], $currency));
         return false;
     }
     $this->SetOrderData(LoadPendingOrdersByToken($session));
     if (md5($GLOBALS['ISC_CFG']['serverStamp'] . $session . $this->GetCombinedOrderId() . $this->GetValue('ProductId')) != $hash) {
         $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang($this->_languagePrefix . 'HashMismatch'));
         return false;
     }
     if (isset($_REQUEST['transaction_id'])) {
         $updatedOrder = array('ordpayproviderid' => $_REQUEST['transaction_id'], 'ordpaymentstatus' => 'captured');
     }
     $this->UpdateOrders($updatedOrder);
     $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess(array('payment', $this->GetName()), GetLang($this->_languagePrefix . 'Success'));
     // Update the status for all orders that we've just received the payment for
     foreach ($this->GetOrders() as $orderId => $order) {
         $status = ORDER_STATUS_AWAITING_FULFILLMENT;
         // If it's a digital order & awaiting fulfillment, automatically complete it
         if ($order['ordisdigital'] && ORDER_STATUS_AWAITING_FULFILLMENT) {
             $status = ORDER_STATUS_COMPLETED;
         }
         UpdateOrderStatus($orderId, $status);
     }
     return true;
 }
Exemple #6
0
	public function ProcessGatewayPing()
	{
		/*
		orderID Your order reference
		amount Order amount (not multiplied by 100)
		currency Currency of the order
		PM Payment method
		ACCEPTANCE Acceptance code returned by acquirer
		STATUS Transaction status
		CARDNO Masked card number
		PAYID Payment reference in our system
		NCERROR Error code
		BRAND Card brand (our system derives it from the card number) or similar information for other payment methods.
		SHASIGN SHA signature composed by our system, if SHA-out configured by you.
		*/

		if(!isset($_REQUEST['OrderToken'])) {
			exit;
		}

		if (!isset($_REQUEST['orderID']) || !isset($_REQUEST['amount']) || !isset($_REQUEST['currency']) || !isset($_REQUEST['STATUS'])) {
			// Bad order details
			$GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang('OgoneErrorInvalid'), print_r($_POST, true));
			return false;
		}

		// ogone response data
		$orderId = $_REQUEST['orderID'];
		$amount = $_REQUEST['amount'];
		$currency = $_REQUEST['currency'];
		$status = $_REQUEST['STATUS'];
		$transactionId = $_REQUEST['PAYID'];
		$errorCode = $_REQUEST['NCERROR'];

		$orderToken = $_REQUEST['OrderToken'];
		$sessionToken = $_REQUEST['SessionToken'];

		$this->SetOrderData(LoadPendingOrdersByToken($orderToken));

		// expected values
		$combinedOrderId = $this->GetCombinedOrderId();
		$gateway_amount = number_format($this->GetGatewayAmount(), 2, '.', '');
		$defaultcurrency = GetDefaultCurrency();

		// verify the SHA Sign
		$shaParamsToCheck = array(
			'AAVADDRESS', 'AAVCHECK', 'AAVZIP', 'ACCEPTANCE', 'ALIAS', 'AMOUNT', 'BRAND', 'CARDNO', 'CCCTY', 'CN', 'COMPLUS', 'CURRENCY', 'CVCCHECK',
			'DCC_COMMPERCENTAGE', 'DCC_CONVAMOUNT', 'DCC_CONVCCY', 'DCC_EXCHRATE', 'DCC_EXCHRATESOURCE', 'DCC_EXCHRATETS', 'DCC_INDICATOR', 'DCC_MARGINPERCENTAGE', 'DCC_VALIDHOUS',
			'DIGESTCARDNO', 'ECI', 'ED', 'ENCCARDNO', 'IP', 'IPCTY', 'NBREMAILUSAGE', 'NBRIPUSAGE', 'NBRIPUSAGE_ALLTX', 'NBRUSAGE', 'NCERROR',
			'ORDERID', 'PAYID', 'PM', 'SCO_CATEGORY', 'SCORING', 'STATUS', 'SUBSCRIPTION_ID', 'TRXDATE', 'VC',
		);

		$checkRequest = array_change_key_case($_REQUEST, CASE_UPPER);
		$signature = $this->GetValue("signature_out");
		$stringToHash = '';

		foreach ($shaParamsToCheck as $param) {
			if (!isset($checkRequest[$param]) || $checkRequest[$param] == '') {
				continue;
			}

			$stringToHash .= $param . '=' . $checkRequest[$param] . $signature;
		}

		$sha = strtoupper(sha1($stringToHash));

		if ($sha != $_REQUEST['SHASIGN']) {
			$GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang('OgoneErrorInvalid', array('orderId' => $orderId)), print_r($_POST, true));
			return false;
		}

		// The values passed don't match what we expected
		if($orderId != $combinedOrderId || $amount != $gateway_amount || $currency != $defaultcurrency['currencycode']) {
			$errorMsg = GetLang('OgoneErrorDetailsNoMatch', array(
				"total" => $amount,
				"expectedTotal" => $gateway_amount,
				"orderId" => $orderId,
				"expectedOrderId" => $combinedOrderId,
				"currency" => $currency,
				"expectedCurrency" => $defaultcurrency['currencycode'],
				"status" => $status
			));
			$GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang('OgoneErrorInvalid', array('orderId' => $orderId)), $errorMsg);
			return false;
		}

		$paymentStatus = '';
		$statusLang = $status;
		switch($status) {
			case '0': // incomplete
			case '1': // cancelled by customer
				$newOrderStatus = ORDER_STATUS_INCOMPLETE;
				break;
			case '2': // auth refused
				$newOrderStatus = ORDER_STATUS_DECLINED;
				break;
			case '5': // authorized
				$newOrderStatus = ORDER_STATUS_AWAITING_PAYMENT;
				break;
			case '51': // awaiting authorization
			case '52': // authorization unknown
				$newOrderStatus = ORDER_STATUS_PENDING;
				break;
			case '6': // authorized and cancelled
				$newOrderStatus = ORDER_STATUS_INCOMPLETE;
				break;
			case '7': // payment deleted
			case '74': // payment deleted
				$newOrderStatus = ORDER_STATUS_AWAITING_PAYMENT;
				break;
			case '8': // refund
				$newOrderStatus = ORDER_STATUS_REFUNDED;
				break;
			case '9': // payment authorized and captured
				$newOrderStatus = ORDER_STATUS_AWAITING_FULFILLMENT;
				break;
			case '91': // awaiting payment
			case '93': // payment refused (tech problem or expired auth)
				$newOrderStatus = ORDER_STATUS_AWAITING_PAYMENT;
				break;
			case '92': // unknown payment
				$newOrderStatus = ORDER_STATUS_PENDING;
				break;
			case '94': // payment declined by aquirer
				$newOrderStatus = ORDER_STATUS_DECLINED;
				break;
			default :
				$newOrderStatus = ORDER_STATUS_DECLINED;
				$statusLang = 'Unknown';
				break;
		}

		// if the order is currently incomplete and the new status isn't incomplete (ie. transaction cancelled by customer), then empty the cart
		if($this->GetOrderStatus() == ORDER_STATUS_INCOMPLETE && $newOrderStatus != ORDER_STATUS_INCOMPLETE) {
			session_write_close();
			$session = new ISC_SESSION($sessionToken);
			EmptyCartAndKillCheckout();
		}

		// update orders with the transaction id
		$updatedOrder = array(
			'ordpayproviderid' => $transactionId
		);

		// if captured then update pay status in order
		if ($newOrderStatus == ORDER_STATUS_AWAITING_FULFILLMENT) {
			$updatedOrder['ordpaymentstatus'] = 'captured';
		}

		$this->UpdateOrders($updatedOrder);

		// we only want to notify the customer of a successfull order
		$emailCustomer = false;
		if ($newOrderStatus != ORDER_STATUS_INCOMPLETE) {
			$emailCustomer = true;
		}

		// update order statuses
		foreach($this->GetOrders() as $orderId => $order) {
			// digital orders should complete right away if captured
			if($order['ordisdigital'] && $newOrderStatus == ORDER_STATUS_AWAITING_FULFILLMENT) {
				$newOrderStatus = ORDER_STATUS_COMPLETED;
			}

			UpdateOrderStatus($orderId, $newOrderStatus, $emailCustomer);
		}

		// Log this payment response
		$oldStatus = GetOrderStatusById($order['ordstatus']);
		if(!$oldStatus) {
			$oldStatus = 'Incomplete';
		}

		$newStatus = GetOrderStatusById($newOrderStatus);
		if (!$newStatus) {
			$newStatus = 'Incomplete';
		}

		$extra = GetLang('OgoneSuccessDetails', array(
			"orderId" => implode(', ', array_keys($this->GetOrders())),
			"amount" => $gateway_amount,
			"paymentId" => $transactionId,
			"paymentStatus" => $status,
			"paymentDesc" => GetLang('OgoneTransactionStatus' . $statusLang),
			"newStatus" => $newStatus,
			"oldStatus" => $oldStatus
		));
		$GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess(array('payment', $this->_name), GetLang('OgoneSuccess', array('orderId' => $orderId)), $extra);

		return true;
	}
 /**
  * Commit a new shipment to the database.
  *
  * @param array An array of information about the shipment.
  * @return boolean True if successful, false if not.
  */
 private function CommitShipment($data)
 {
     $order = GetOrder($data['orderId'], true);
     if (!isset($data['shiptrackno'])) {
         $data['shiptrackno'] = '';
     }
     $GLOBALS['ISC_CLASS_DB']->StartTransaction();
     $newShipment = array('shipdate' => time(), 'shiptrackno' => $data['shiptrackno'], 'shipmethod' => $data['shipmethod'], 'shiporderid' => $data['orderId'], 'shiporderdate' => $order['orddate'], 'shipcomments' => $data['shipcomments'], 'shipvendorid' => $order['ordvendorid'], 'shipcustid' => $order['ordcustid'], 'shipbillfirstname' => $order['ordbillfirstname'], 'shipbilllastname' => $order['ordbilllastname'], 'shipbillcompany' => $order['ordbillcompany'], 'shipbillstreet1' => $order['ordbillstreet1'], 'shipbillstreet2' => $order['ordbillstreet2'], 'shipbillsuburb' => $order['ordbillsuburb'], 'shipbillstate' => $order['ordbillstate'], 'shipbillzip' => $order['ordbillzip'], 'shipbillcountry' => $order['ordbillcountry'], 'shipbillcountrycode' => $order['ordbillcountrycode'], 'shipbillcountryid' => $order['ordbillcountryid'], 'shipbillstateid' => $order['ordbillstateid'], 'shipbillphone' => $order['ordbillphone'], 'shipbillemail' => $order['ordbillemail'], 'shipshipfirstname' => $order['ordshipfirstname'], 'shipshiplastname' => $order['ordshiplastname'], 'shipshipcompany' => $order['ordshipcompany'], 'shipshipstreet1' => $order['ordshipstreet1'], 'shipshipstreet2' => $order['ordshipstreet2'], 'shipshipsuburb' => $order['ordshipsuburb'], 'shipshipstate' => $order['ordshipstate'], 'shipshipzip' => $order['ordshipzip'], 'shipshipcountry' => $order['ordshipcountry'], 'shipshipcountrycode' => $order['ordshipcountrycode'], 'shipshipcountryid' => $order['ordshipcountryid'], 'shipshipstateid' => $order['ordshipstateid'], 'shipshipphone' => $order['ordshipphone'], 'shipshipemail' => $order['ordshipemail']);
     $shipmentId = $GLOBALS['ISC_CLASS_DB']->InsertQuery('shipments', $newShipment);
     if (!$shipmentId) {
         return false;
     }
     $totalShipped = $order['ordtotalshipped'];
     // Now actually create the shipment based on all the items that were selected
     foreach ($data['quantity'] as $productId => $quantity) {
         if (!isset($order['products'][$productId])) {
             return false;
         }
         $product = $order['products'][$productId];
         // We didn't choose to ship any of this item
         if ((int) $data['quantity'][$product['orderprodid']] <= 0 || $product['ordprodtype'] != 'physical') {
             continue;
         }
         $newItem = array('shipid' => $shipmentId, 'itemordprodid' => (int) $productId, 'itemprodid' => $product['ordprodid'], 'itemprodsku' => $product['ordprodsku'], 'itemprodname' => $product['ordprodname'], 'itemqty' => (int) $quantity, 'itemprodoptions' => $product['ordprodoptions'], 'itemprodvariationid' => $product['ordprodvariationid']);
         if (isset($product['ordprodeventdate'])) {
             $newItem['itemprodeventdate'] = $product['ordprodeventdate'];
         }
         if (isset($product['ordprodeventname'])) {
             $newItem['itemprodeventname'] = $product['ordprodeventname'];
         }
         if (!$GLOBALS['ISC_CLASS_DB']->InsertQuery('shipment_items', $newItem)) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
         // Increase the amount of items shipped for this product
         $totalShipped += $quantity;
         $updatedOrderItem = array('ordprodqtyshipped' => $product['ordprodqtyshipped'] + $quantity);
         if (!$GLOBALS['ISC_CLASS_DB']->UpdateQuery('order_products', $updatedOrderItem, "orderprodid='" . (int) $product['orderprodid'] . "'")) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
     }
     $updatedOrder = array('ordtotalshipped' => $totalShipped);
     // Chose to update the status of this order
     if (isset($data['ordstatus'])) {
         if (isset($GLOBALS['StillShippable'])) {
             $newStatus = ORDER_STATUS_PARTIALLY_SHIPPED;
         } else {
             $newStatus = ORDER_STATUS_SHIPPED;
             if (!$order['ordtrackingno']) {
                 $updatedOrder['ordtrackingno'] = $data['shiptrackno'];
             }
         }
         UpdateOrderStatus($order['orderid'], $newStatus);
     }
     if (!$GLOBALS['ISC_CLASS_DB']->UpdateQuery('orders', $updatedOrder, "orderid='" . (int) $order['orderid'] . "'")) {
         $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
         return false;
     }
     // Still here? Commit and send back the ID of the new shipment
     $GLOBALS['ISC_CLASS_DB']->CommitTransaction();
     return $shipmentId;
 }
 private function RefundOrder()
 {
     $message = '';
     $messageStaus = MSG_ERROR;
     $provider = null;
     if (!isset($_REQUEST['orderid'])) {
         return false;
     }
     $orderId = $_REQUEST['orderid'];
     $order = GetOrder($_REQUEST['orderid']);
     if (!isset($order['orderid'])) {
         return false;
     }
     /* Validate posted data*/
     $refundType = '';
     if (!isset($_REQUEST['refundType'])) {
         return false;
     }
     $refundType = $_REQUEST['refundType'];
     //preset the refund amount to the available amount of the order
     $refundAmt = $order['ordgatewayamount'] - $order['ordrefundedamount'];
     //refund partial amount
     if ($refundType == 'partial') {
         //is refund amount specified
         if (!isset($_REQUEST['refundAmt']) || $_REQUEST['refundAmt'] == '') {
             $message = GetLang('EnterRefundAmount');
         } else {
             if (!is_numeric($_REQUEST['refundAmt']) || $_REQUEST['refundAmt'] <= 0) {
                 $message = GetLang('InvalidRefundAmountFormat');
             } else {
                 if ($_REQUEST['refundAmt'] + $order['ordrefundedamount'] > $order['ordgatewayamount']) {
                     $message = GetLang('InvalidRefundAmount');
                 } else {
                     $refundAmt = $_REQUEST['refundAmt'];
                 }
             }
         }
     }
     //there is an error message
     if ($message != '') {
         FlashMessage($message, $messageStatus, 'index.php?ToDo=viewOrders');
     }
     $transactionId = trim($order['ordpayproviderid']);
     if ($transactionId == '') {
         $message = GetLang('OrderTranscationIDNotFound');
     } else {
         if (!GetModuleById('checkout', $provider, $order['orderpaymentmodule'])) {
             $message = GetLang('PaymentMethodNotExist');
         } else {
             if (!$provider->IsEnabled()) {
                 $message = GetLang('PaymentProviderIsDisabled');
             } else {
                 if (!method_exists($provider, "DoRefund")) {
                     $message = GetLang('RefundNotAvailable');
                 } else {
                     //still here, perform a delay capture
                     if ($provider->DoRefund($order, $message, $refundAmt)) {
                         $messageStatus = MSG_SUCCESS;
                         //update order status
                         $orderStatus = ORDER_STATUS_REFUNDED;
                         UpdateOrderStatus($order['orderid'], $orderStatus, true);
                     }
                 }
             }
         }
     }
     FlashMessage($message, $messageStatus, 'index.php?ToDo=viewOrders');
     return $message;
 }
 public function ProcessGatewayPing()
 {
     $transactionid = $_REQUEST['transaction_id'];
     $order_id = $_REQUEST['order_id'];
     $amount = $_REQUEST['amount'];
     $from_email = $_REQUEST['from_email'];
     $session = $_REQUEST['session'];
     $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess(array('payment', $this->GetName()), 'APC Pingback');
     $this->SetOrderData(LoadPendingOrdersByToken($session));
     if (md5($GLOBALS['ISC_CFG']['serverStamp'] . number_format($amount, 2) . $this->GetValue('merchantid') . $session) != $_REQUEST['hash']) {
         $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang($this->_languagePrefix . 'HashMismatch'));
         return false;
     }
     if (function_exists("curl_exec")) {
         // Use CURL if it's available
         $ch = curl_init('https://www.nochex.com/nochex.dll/apc/apc');
         curl_setopt($ch, CURLOPT_POST, 1);
         curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
         curl_setopt($ch, CURLOPT_TIMEOUT, 60);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
         // Setup the proxy settings if there are any
         if (GetConfig('HTTPProxyServer')) {
             curl_setopt($ch, CURLOPT_PROXY, GetConfig('HTTPProxyServer'));
             if (GetConfig('HTTPProxyPort')) {
                 curl_setopt($ch, CURLOPT_PROXYPORT, GetConfig('HTTPProxyPort'));
             }
         }
         if (GetConfig('HTTPSSLVerifyPeer') == 0) {
             curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
         }
         $result = curl_exec($ch);
         if (curl_errno($ch)) {
             $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang($this->_languagePrefix . 'CurlError'));
             return false;
         }
     }
     if (isset($result) && $result == 'AUTHORISED') {
         $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess(array('payment', $this->GetName()), GetLang($this->_languagePrefix . 'Success'));
         // Update the status for all orders that we've just received the payment for
         foreach ($this->GetOrders() as $orderId => $order) {
             $status = ORDER_STATUS_AWAITING_FULFILLMENT;
             // If it's a digital order & awaiting fulfillment, automatically complete it
             if ($order['ordisdigital'] && ORDER_STATUS_AWAITING_FULFILLMENT) {
                 $status = ORDER_STATUS_COMPLETED;
             }
             UpdateOrderStatus($orderId, $status);
         }
         return true;
     }
     return false;
 }
Exemple #10
0
	/**
	 * Commit a new shipment to the database.
	 *
	 * @param array An array of information about the shipment.
	 * @return boolean True if successful, false if not.
	 */
	public function CommitShipment($data)
	{
		$order = GetOrder($data['orderId']);

		if(!$order || !isset($data['shiptrackno'])) {
			$data['shiptrackno'] = '';
		}

		$query = "
			SELECT *
			FROM [|PREFIX|]order_addresses
			WHERE id='".(int)$data['addressId']."'
		";
		$result = $this->db->query($query);
		$address = $this->db->fetch($result);

		$addressProducts = array();
		$query = "
			SELECT *
			FROM [|PREFIX|]order_products
			WHERE order_address_id='".$address['id']."'
		";
		$result = $this->db->query($query);
		while($product = $this->db->fetch($result)) {
			$addressProducts[$product['orderprodid']] = $product;
		}

		$GLOBALS['ISC_CLASS_DB']->StartTransaction();

		$newShipment = array(
			'shipdate' => time(),
			'shiptrackno' => $data['shiptrackno'],
			'shipping_module' => $data['shipping_module'],
			'shipmethod' => $data['shipmethod'],
			'shiporderid' => $data['orderId'],
			'shiporderdate' => $order['orddate'],
			'shipcomments' => $data['shipcomments'],
			'shipvendorid' => $order['ordvendorid'],
			'shipcustid' => $order['ordcustid'],

			// Billing Details
			'shipbillfirstname' => $order['ordbillfirstname'],
			'shipbilllastname' => $order['ordbilllastname'],
			'shipbillcompany' => $order['ordbillcompany'],
			'shipbillstreet1' => $order['ordbillstreet1'],
			'shipbillstreet2' => $order['ordbillstreet2'],
			'shipbillsuburb' => $order['ordbillsuburb'],
			'shipbillstate' => $order['ordbillstate'],
			'shipbillzip' => $order['ordbillzip'],
			'shipbillcountry' => $order['ordbillcountry'],
			'shipbillcountrycode' => $order['ordbillcountrycode'],
			'shipbillcountryid' => $order['ordbillcountryid'],
			'shipbillstateid' => $order['ordbillstateid'],
			'shipbillphone' => $order['ordbillphone'],
			'shipbillemail' => $order['ordbillemail'],

			// Shipping Details
			'shipshipfirstname'		=> $address['first_name'],
			'shipshiplastname'		=> $address['last_name'],
			'shipshipcompany'		=> $address['company'],
			'shipshipstreet1'		=> $address['address_1'],
			'shipshipstreet2'		=> $address['address_2'],
			'shipshipsuburb'		=> $address['city'],
			'shipshipstate'			=> $address['state'],
			'shipshipzip'			=> $address['zip'],
			'shipshipcountry'		=> $address['country'],
			'shipshipcountrycode'	=> $address['country_iso2'],
			'shipshipcountryid'		=> $address['country_id'],
			'shipshipstateid'		=> $address['state_id'],
			'shipshipphone'			=> $address['phone'],
			'shipshipemail'			=> $address['email'],
		);
		$shipmentId = $GLOBALS['ISC_CLASS_DB']->InsertQuery('shipments', $newShipment);
		if(!$shipmentId) {
			return false;
		}

		$totalShipped = $order['ordtotalshipped'];

		// Number of items already shipped for this address
		$query = "
			SELECT total_shipped
			FROM [|PREFIX|]order_shipping
			WHERE order_address_id='".$address['id']."'
		";
		$totalAddressShipped = $this->db->fetchOne($query);

		// Now actually create the shipment based on all the items that were selected
		foreach($data['quantity'] as $productId => $quantity) {
			if(!isset($addressProducts[$productId])) {
				return false;
			}

			$product = $addressProducts[$productId];
			// We didn't choose to ship any of this item
			if((int)$data['quantity'][$product['orderprodid']] <= 0 || $product['ordprodtype'] != 'physical') {
				continue;
			}

			$newItem = array(
				'shipid' => $shipmentId,
				'itemordprodid' => (int)$productId,
				'itemprodid' => $product['ordprodid'],
				'itemprodsku' => $product['ordprodsku'],
				'itemprodname' => $product['ordprodname'],
				'itemqty' => (int)$quantity,
				'itemprodoptions' => $product['ordprodoptions'],
				'itemprodvariationid' => $product['ordprodvariationid']
			);

			if (isset($product['ordprodeventdate'])) {
				$newItem['itemprodeventdate'] = $product['ordprodeventdate'];
			}

			if (isset($product['ordprodeventname'])) {
				$newItem['itemprodeventname'] = $product['ordprodeventname'];
			}

			if(!$GLOBALS['ISC_CLASS_DB']->InsertQuery('shipment_items', $newItem)) {
				$GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
				return false;
			}

			// Increase the amount of items shipped for this product
			$totalShipped += $quantity;
			$totalAddressShipped += $quantity;

			$updatedOrderItem = array(
				'ordprodqtyshipped' => $product['ordprodqtyshipped'] + $quantity
			);
			if(!$GLOBALS['ISC_CLASS_DB']->UpdateQuery('order_products', $updatedOrderItem, "orderprodid='".(int)$product['orderprodid']."'")) {
				$GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
				return false;
			}
		}

		$updatedOrder = array(
			'ordtotalshipped' => $totalShipped
		);

		// Chose to update the status of this order
		if(isset($data['ordstatus'])) {
			if(isset($GLOBALS['StillShippable'])) {
				$newStatus = ORDER_STATUS_PARTIALLY_SHIPPED;
			}
			else {
				$newStatus = ORDER_STATUS_SHIPPED;
			}
			UpdateOrderStatus($order['orderid'], $newStatus);
		}
		if(!$GLOBALS['ISC_CLASS_DB']->UpdateQuery('orders', $updatedOrder, "orderid='".(int)$order['orderid']."'")) {
			$GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
			return false;
		}

		// Update the order_shipping table to indicate what's shipped
		$updatedShipping = array(
			'total_shipped' => $totalAddressShipped
		);
		if(!$this->db->updateQuery('order_shipping', $updatedShipping,
			'order_address_id='.$address['id'])) {
				$this->db->rollbackTransaction();
				return false;
		}

		// Still here? Commit and send back the ID of the new shipment
		$GLOBALS['ISC_CLASS_DB']->CommitTransaction();
		return $shipmentId;
	}
 private function updateOrderStatusBoxRequest()
 {
     $success = (int) @$_REQUEST['success'];
     $failed = (int) @$_REQUEST['failed'];
     $result = $GLOBALS['ISC_CLASS_DB']->Query("SELECT * FROM [|PREFIX|]order_status WHERE statusid='" . $GLOBALS['ISC_CLASS_DB']->Quote(@$_REQUEST['statusId']) . "'");
     $_SESSION["canupdateorder"] = "";
     if (isId(@$_REQUEST['orderId']) && isId(@$_REQUEST['statusId']) && ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) && UpdateOrderStatus($_REQUEST['orderId'], $_REQUEST['statusId'])) {
         echo '1';
         $success++;
     } else {
         echo '0';
         $failed++;
     }
     $message = sprintf(GetLang('OrderUpdateStatusReport'), $success, $row['statusdesc']);
     if ($failed) {
         $message .= sprintf(GetLang('OrderUpdateStatusReportFail'), $failed);
     }
     MessageBox($message, MSG_SUCCESS);
     //2011-4-21 ronnie add
     if ($_SESSION["canupdateorder"] != "") {
         //echo MessageBox($_SESSION["canupdateorder"], MSG_ERROR);
         echo $_SESSION["canupdateorder"];
     }
     exit;
 }
Exemple #12
0
	/**
	 * Process the NAB pingback
	 */
	public function ProcessGatewayPing()
	{
		if(!isset($_REQUEST['payment_reference']) || !isset($_REQUEST['bank_reference']) || !isset($_REQUEST['orderToken']) || !isset($_REQUEST['signature'])) {
			exit;
		}

		$paymentReference = $_REQUEST['payment_reference'];
		$paymentAmount = number_format($_REQUEST['payment_amount'], 2, '.', '');
		$orderToken = $_REQUEST['orderToken'];
		$sessionToken = $_REQUEST['sessionToken'];
		$requestSignature = $_REQUEST['signature'];
		$transactionId = $_REQUEST['payment_number'];
		$bankReference = $_REQUEST['bank_reference'];

		$this->SetOrderData(LoadPendingOrdersByToken($orderToken));

		$orders = $this->GetOrders();
		list(,$order) = each($orders);
		$orderId = $order['orderid'];

		// GetGatewayAmount returns the amount from the order record, so $amount is that but formatted into #.##
		$amount = number_format($this->GetGatewayAmount(), 2, '.', '');

		// verify that the signature matches
		$verifySignature = md5($amount . $orderToken . $orderId . GetConfig('EncryptionToken'));

		if ($verifySignature != $requestSignature) {
			$errorMsg = GetLang('NabSignatureMismatchDetails', array('orderId' => $orderId, 'transactionId' => $transactionId));
			$GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang('NabSignatureMismatch'), $errorMsg);
			return false;
		}

		/** @var ISC_TRANSACTION */
		$transaction = GetClass('ISC_TRANSACTION');

		$previousTransaction = $transaction->LoadByTransactionId($transactionId, $this->GetId());

		if(is_array($previousTransaction) && $previousTransaction['transactionid']) {
			$GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), sprintf(GetLang('NabTransactionAlreadyProcessed'), $_REQUEST['payment_date']));
			return false;
		}

		// Need to finish the processing of the pingback
		$newTransaction = array(
			'providerid' => $this->GetId(),
			'transactiondate' => $_REQUEST['payment_date'],
			'transactionid' => $transactionId,
			'orderid' => $orderId,
			'message' => 'Completed',
			'status' => '',
			'amount' => $_REQUEST['payment_amount'],
			'extrainfo' => array()
		);

		$newTransaction['status'] = TRANS_STATUS_COMPLETED;
		$newOrderStatus = ORDER_STATUS_AWAITING_FULFILLMENT;

		$transaction->Create($newTransaction);

		// If the order was previously incomplete, empty the customers cart
		if($this->GetOrderStatus() == ORDER_STATUS_INCOMPLETE) {
			session_write_close();
			$session = new ISC_SESSION($sessionToken);
			EmptyCartAndKillCheckout();
		}

		$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(
			'ordpayproviderid' => $_REQUEST['payment_number'],
			'ordpaymentstatus' => 'captured',
		);

		$this->UpdateOrders($updatedOrder);

		// This was a successful order
		$oldStatus = GetOrderStatusById($this->GetOrderStatus());

		if(!$oldStatus) {
			$oldStatus = 'Incomplete';
		}

		$newStatus = GetOrderStatusById($newOrderStatus);
		$extra = GetLang('NabSuccessDetails',
			array(
				'orderId' 			=> $orderId,
				'amount' 			=> $amount,
				'bankAuth' 			=> $bankReference,
				'transactionId' 	=> $transactionId,
				'paymentStatus' 	=> 'Captured',
				'newOrderStatus' 	=> $newStatus,
				'oldOrderStatus' 	=> $oldStatus,
			)
		);
		$GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess(array('payment', $this->GetName()), GetLang('NabSuccess'), $extra);
		return true;
	}
	/**
	* Ebay: Sent to a seller when a buyer completes the checkout process for an item. Not sent when an auction ends without bids.
	*
	* My notes: Seems to be triggered when the buyer's payment process for an AUCTION item has completed, is not fired for fixed price items which fire 'FixedPrice...' notifications instead
	*
	* @param array $body
	*/
	protected function _handleAuctionCheckoutComplete($body)
	{
		// The data fields in the notification are the same as those returned by the GetItemTransactions call with the default detail level.
		if (!empty ($body['Item']['ItemID']) && ISC_ADMIN_EBAY::validEbayItemId($body['Item']['ItemID'])) {
			// variables init
			$order = array();
			$orderId = 1;
			$order['ShippingInsuranceCost'] = 0;
			$completedPaymentHoldStatus = array('None', 'Released');
			$orderStatus = ORDER_STATUS_AWAITING_PAYMENT;
			$existingOrderId = 0;

			// Determine if the buyer purchase multiple items from the same seller
			if (!empty($body['TransactionArray']['Transaction']['ContainingOrder'])) {
			 // Call the operation to get the order transaction.
				$orderId = $body['TransactionArray']['Transaction']['ContainingOrder']['OrderID'];

				// if the record already exist, check if we need to update existing orders, that the payment hasn't been cleared previously.
				$existingOrder = GetOrderByEbayOrderId($orderId);
				$orderTransaction = ISC_ADMIN_EBAY_OPERATIONS::getOrderTransactions($orderId);
				$transactions = $orderTransaction->OrderArray->Order->TransactionArray->Transaction;

				$order['SubTotal'] = (string) $orderTransaction->OrderArray->Order->Subtotal;
				$order['ShippingCost'] = (string) $orderTransaction->OrderArray->Order->ShippingServiceSelected->ShippingServiceCost;
				$order['ShippingInsuranceCost'] = 0;
				$order['GrandTotal'] = (string) $orderTransaction->OrderArray->Order->Total;
				$order['TotalQuantityPurchased'] = 0;
				foreach ($transactions as $transaction) {
					$convertedTransaction = (array) $transaction;
					$variationOptionsString = '';
					if (isset($convertedTransaction['Variation']->VariationSpecifics)) {
						$variationNameValueList = (array) $convertedTransaction['Variation']->VariationSpecifics->NameValueList;
						$variationOptions = array();
						$variationSpecifics = (array) $convertedTransaction['Variation']->VariationSpecifics;
						if (is_array($variationSpecifics['NameValueList'])) {
							foreach ($variationSpecifics['NameValueList'] as $option) {
								$variationOptions[(string) $option->Name] = (string) $option->Value;
							}
						} else {
							$variationOptions[(string) $variationSpecifics['NameValueList']->Name] = (string) $variationSpecifics['NameValueList']->Value;
						}
						$variationOptionsString = serialize($variationOptions);
					}
					$quantityPurchased = $convertedTransaction['QuantityPurchased'];
					$transactionPrice = $convertedTransaction['TransactionPrice'];
					$itemId = (string) $convertedTransaction['Item']->ItemID;
					$transactionId = (string) $convertedTransaction['TransactionID'];
					$totalTransactionPrice = $transactionPrice * $quantityPurchased;
					$order['Transaction'][] = array(
						'QuantityPurchased' => $quantityPurchased,
						'TransactionPrice' => $transactionPrice,
						'ItemId' => $itemId,
						'TotalTransactionPrice' => $totalTransactionPrice,
						'VariationOptionsString' => $variationOptionsString,
						'TransactionId' => $transactionId,
					);
					$order['TotalQuantityPurchased'] += $quantityPurchased;
					$order['Currency'] = GetCurrencyByCode($body['TransactionArray']['Transaction']['AmountPaid']['!currencyID']);
					$buyerInfoShippingAddress = $body['TransactionArray']['Transaction']['Buyer']['BuyerInfo']['ShippingAddress'];
					$buyerEmailAddress = $body['TransactionArray']['Transaction']['Buyer']['Email'];
				}

				if ($existingOrder) {
					$existingOrderId = $existingOrder['orderid'];
				}
			}
			else {
				$transactions = $body['TransactionArray'];
				foreach ($transactions as $transaction) {
					$itemId = $body['Item']['ItemID'];
					$transactionId = $transaction['TransactionID'];
					$query = "
						SELECT *
						FROM [|PREFIX|]order_products
						WHERE ebay_item_id = '".$GLOBALS["ISC_CLASS_DB"]->Quote($itemId)."'
							AND ebay_transaction_id = '".$GLOBALS["ISC_CLASS_DB"]->Quote($transactionId)."'
						LIMIT 1
					";
					$res = $GLOBALS['ISC_CLASS_DB']->Query($query);
					$row = $GLOBALS['ISC_CLASS_DB']->Fetch($res);
					$eachItemPriceExTax = $transaction['TransactionPrice']['!'];
					$quantityPurchased = $transaction['QuantityPurchased'];
					$totalTransactionPrice = $quantityPurchased * $eachItemPriceExTax;
					$variationOptionsString = '';

					// do we have a variation for this product?
					if (isset($transaction['Variation']['VariationSpecifics'])) {
						$variationNameValueList = $transaction['Variation']['VariationSpecifics']['NameValueList'];
						$variationOptions = array();
						foreach ($variationNameValueList as $option) {
							$variationOptions[$option['Name']] = $option['Value'];
						}
						$variationOptionsString = serialize($variationOptions);
					}
					$order['TotalQuantityPurchased'] = $quantityPurchased;
					$order['SubTotal'] = $eachItemPriceExTax * $order['TotalQuantityPurchased'];
					$order['ShippingCost'] = $transaction['ShippingServiceSelected']['ShippingServiceCost']['!'];
					if (isset ($transaction['ShippingServiceSelected']['ShippingInsuranceCost']['!'])) {
						$order['ShippingInsuranceCost'] = $transaction['ShippingServiceSelected']['ShippingInsuranceCost']['!'];
					}
					$order['GrandTotal'] = $transaction['AmountPaid']['!'];
					$order['Transaction'][] = array(
						'QuantityPurchased' => $quantityPurchased,
						'TransactionPrice' => $eachItemPriceExTax,
						'ItemId' => $itemId,
						'TotalTransactionPrice' => $totalTransactionPrice,
						'VariationOptionsString' => $variationOptionsString,
						'TransactionId' => $transactionId,
					);
					$order['Currency'] = GetCurrencyByCode($transaction['AmountPaid']['!currencyID']);
					$buyerInfoShippingAddress = $transaction['Buyer']['BuyerInfo']['ShippingAddress'];
					$buyerEmailAddress = $transaction['Buyer']['Email'];

					if (!$row) {
						// only process the new transaction
						break;
					} else {
						$existingOrderId = $row['orderorderid'];
					}
				}
			}

			$paymentHoldStatus = $body['TransactionArray']['Transaction']['Status']['PaymentHoldStatus'];
			if (in_array(trim($paymentHoldStatus), $completedPaymentHoldStatus)) {
				$orderStatus = ORDER_STATUS_AWAITING_FULFILLMENT;
			}
			if ($existingOrderId != 0) {
				if (!isset ($existingOrder)) {
					$existingOrder = GetOrder($existingOrderId, false, true, true);
				}

				// check if there're any existing order need to be updated.
				// in the case, paypal release the hold payment of buyer
				if ($existingOrder['ordstatus'] == ORDER_STATUS_AWAITING_PAYMENT
				&& $orderStatus == ORDER_STATUS_AWAITING_FULFILLMENT) {
					// update the quantity for each transaction
					$GLOBALS["ISC_CLASS_DB"]->StartTransaction();
					foreach ($order['Transaction'] as $eachTransaction) {
						// Get product Id
						try {
							$itemObj = new ISC_ADMIN_EBAY_ITEMS($eachTransaction['ItemId']);
							$productId = $itemObj->getProductId();
						} catch (Exception $e) {
							$this->log->LogSystemDebug('ebay', $e->getMessage());
							return false;
						}

						// update the item quantity in store
						$updatedData['quantity_remaining'] = $itemObj->getQuantityRemaining() - $eachTransaction['QuantityPurchased'];
						if (!$GLOBALS['ISC_CLASS_DB']->UpdateQuery('ebay_items', $updatedData, "ebay_item_id='" . $eachTransaction['ItemId'] . "'")) {
							$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
							$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
							return false;
						}
						if (!UpdateOrderStatus($existingOrderId, $orderStatus, true, true)) {
							$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
							return false;
						}
					}
					$GLOBALS["ISC_CLASS_DB"]->CommitTransaction();

					// update the store inventory if necessary
					if (GetConfig('UpdateInventoryLevels') == 1) {
						DecreaseInventoryFromOrder($existingOrderId);
					}
					$this->log->LogSystemDebug('ebay', 'The status of the store order ('. $existingOrderId .') has been updated to: Awaiting Fulfillment');
				}
				return true;
			}

			$order['ShippingTotalCost'] = $order['ShippingInsuranceCost'] + $order['ShippingCost'];

			// Buyer's address information
			$addressMap = array(
				'Name',
				'CompanyName',
				'Street1',
				'Street2',
				'CityName',
				'PostalCode',
				'Country',
				'CountryName',
				'Phone',
				'StateOrProvince',
			);

			// Initialize the value, make sure it's not empty
			foreach ($addressMap as $key) {
				if (!isset($buyerInfoShippingAddress[$key])) {
					$buyerInfoShippingAddress[$key] = '';
				}
			}
			$buyerCountryId = GetCountryIdByISO2($buyerInfoShippingAddress['Country']);
			$buyerStateId = GetStateByName($buyerInfoShippingAddress['StateOrProvince'], $buyerCountryId);
			$buyerStateName = $buyerInfoShippingAddress['StateOrProvince'];
			if (!$buyerStateId) {
				$buyerStateId = GetStateByAbbrev($buyerInfoShippingAddress['StateOrProvince'], $buyerCountryId);
				$stateInfo = GetStateInfoById($buyerStateId);
				$buyerStateName = $stateInfo['statename'];
			}

			// Tokenize buyer's first and last name
			$nameTokens = explode(' ', $buyerInfoShippingAddress['Name']);
			$buyerFirstName = $nameTokens[0];
			$buyerLastName = '';
			if (!empty($nameTokens[1])) {
				$buyerLastName = $nameTokens[1];
			}

			$orderToken = generateOrderToken();

			// Preparing data to be inserted to orders table
			$newOrder = array(
				'ordtoken' => $orderToken,
				'orderpaymentmodule' => '',
				'orderpaymentmethod' => '',
				'orderpaymentmodule' => '',
				'extraInfo' => serialize(array()),
				'orddefaultcurrencyid' => $order['Currency']['currencyid'],
				'orddate' => time(),
				'ordlastmodified' => time(),
				'ordcurrencyid' => $order['Currency']['currencyid'],
				'ordcurrencyexchangerate' => 1,
				'ordipaddress' => GetIP(),
				'ordcustmessage' => '',
				'ordstatus' => $orderStatus,
				'base_shipping_cost' => $order['ShippingTotalCost'],
				'base_handling_cost' => 0,
				'ordbillemail' => $buyerEmailAddress,
				'ordbillfirstname' => $buyerFirstName,
				'ordbilllastname' => $buyerLastName,
				'ordbillcompany' => $buyerInfoShippingAddress['CompanyName'],
				'ordbillstreet1' => $buyerInfoShippingAddress['Street1'],
				'ordbillstreet2' => $buyerInfoShippingAddress['Street2'],
				'ordbillsuburb' => $buyerInfoShippingAddress['CityName'],
				'ordbillzip' => $buyerInfoShippingAddress['PostalCode'],
				'ordbillcountrycode' => $buyerInfoShippingAddress['Country'],
				'ordbillphone' => $buyerInfoShippingAddress['Phone'],
				'ordbillstateid' => (int) $buyerStateId,
				'ordbillstate' => $buyerStateName,
				'ordbillcountry' => $buyerInfoShippingAddress['CountryName'],
				'ordbillcountryid' => (int) $buyerCountryId,
				'total_ex_tax' => $order['GrandTotal'],
				'total_inc_tax' => $order['GrandTotal'],
				'shipping_cost_ex_tax' => $order['ShippingTotalCost'],
				'shipping_cost_inc_tax' => $order['ShippingTotalCost'],
				'subtotal_inc_tax' => $order['SubTotal'],
				'subtotal_ex_tax' => $order['SubTotal'],
				'ebay_order_id' => $orderId,
			);
			ResetStartingOrderNumber();

			// Start the transaction
			$GLOBALS["ISC_CLASS_DB"]->StartTransaction();

			// Inserting order data
			$newOrderId = $GLOBALS["ISC_CLASS_DB"]->InsertQuery('orders', $newOrder);
			if (!$newOrderId) {
				$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
				$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
				return false;
			}

			$orderAddress = array(
				'first_name' => $buyerFirstName,
				'last_name' => $buyerLastName,
				'company' => $buyerInfoShippingAddress['CompanyName'],
				'address_1' => $buyerInfoShippingAddress['Street1'],
				'address_2' => $buyerInfoShippingAddress['Street2'],
				'city' => $buyerInfoShippingAddress['CityName'],
				'zip' => $buyerInfoShippingAddress['PostalCode'],
				'country_iso2' => $buyerInfoShippingAddress['Country'],
				'phone' => $buyerInfoShippingAddress['Phone'],
				'total_items' => $order['TotalQuantityPurchased'],
				'email' => $buyerEmailAddress,
				'country_id' => (int) $buyerCountryId,
				'country' => $buyerInfoShippingAddress['CountryName'],
				'state_id' => (int) $buyerStateId,
				'state' => $buyerStateName,
				'order_id' => $newOrderId,
			);

			$addressId = $GLOBALS['ISC_CLASS_DB']->insertQuery('order_addresses', $orderAddress);
			if (!$addressId) {
				$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
				$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
				return false;
			}

			// Inserting order shipping
			$orderShipping = array(
				'order_address_id' => $addressId,
				'order_id' => $newOrderId,
				'base_cost' => $order['ShippingTotalCost'],
				'cost_inc_tax' => $order['ShippingTotalCost'],
				'cost_ex_tax' => $order['ShippingTotalCost'],
				'method' => 'Available on eBay',
			);

			if (!$GLOBALS['ISC_CLASS_DB']->insertQuery('order_shipping', $orderShipping)) {
				$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
				$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
				return false;
			}

			// Go thru each sold item in the order
			foreach ($order['Transaction'] as $eachTransaction) {
				// Get product Id
				try {
					$itemObj = new ISC_ADMIN_EBAY_ITEMS($eachTransaction['ItemId']);
					$productId = $itemObj->getProductId();
				} catch (Exception $e) {
					$this->log->LogSystemDebug('ebay', $e->getMessage());
					return false;
				}

				// Inserting order product
				$productObj = new ISC_PRODUCT($productId);
				$newProduct = array(
					'orderorderid' => $newOrderId,
					'ordprodid' => $productId,
					'ordprodsku' => $productObj->GetSKU(),
					'ordprodname' => $productObj->GetProductName(),
					'ordprodtype' => $productObj->GetProductType(),
					'ordprodqty' => $eachTransaction['QuantityPurchased'],
					'base_price' => $eachTransaction['TransactionPrice'],
					'price_ex_tax' => $eachTransaction['TransactionPrice'],
					'price_inc_tax' => $eachTransaction['TransactionPrice'],
					'price_tax' => 0,
					'base_total' => $eachTransaction['TotalTransactionPrice'],
					'total_ex_tax' => $eachTransaction['TotalTransactionPrice'],
					'total_inc_tax' => $eachTransaction['TotalTransactionPrice'],
					'total_tax' => 0,
					'base_cost_price' => 0,
					'cost_price_inc_tax' => 0,
					'cost_price_inc_tax' => 0,
					'cost_price_tax' => 0,
					'ordprodweight' => $productObj->GetWeight(false),
					'ordprodoptions' => $eachTransaction['VariationOptionsString'],
					'ordprodvariationid' => $productObj->_prodvariationid,
					'ordprodwrapid' => 0,
					'ordprodwrapname' => '',
					'base_wrapping_cost' => 0,
					'wrapping_cost_ex_tax' => 0,
					'wrapping_cost_inc_tax' => 0,
					'wrapping_cost_tax' => 0,
					'ordprodwrapmessage' => '',
					'ordprodeventname' => '',
					'ordprodeventdate' => 0,
					'ordprodfixedshippingcost' => $productObj->GetFixedShippingCost(),
					'order_address_id' => $addressId,
					'ebay_item_id' => $eachTransaction['ItemId'],
					'ebay_transaction_id' => $eachTransaction['TransactionId'],
				);

				$orderProductId = $GLOBALS['ISC_CLASS_DB']->insertQuery('order_products', $newProduct);
				if (!$orderProductId) {
					$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
					$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
					return false;
				}

				if ($orderStatus == ORDER_STATUS_AWAITING_FULFILLMENT) {
					// update the item quantity in store
					$updatedData['quantity_remaining'] = $itemObj->getQuantityRemaining() - $eachTransaction['QuantityPurchased'];
					if (!$GLOBALS['ISC_CLASS_DB']->UpdateQuery('ebay_items', $updatedData, "ebay_item_id='" . $eachTransaction['ItemId'] . "'")) {
						$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
						$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
						return false;
					}
				}
			}
			$GLOBALS["ISC_CLASS_DB"]->CommitTransaction();

			// update the store inventory if necessary
			if (GetConfig('UpdateInventoryLevels') == 1) {
				DecreaseInventoryFromOrder($newOrderId);
			}

			// Trigger new order notifications
			SendOrderNotifications($orderToken);

			$this->log->LogSystemDebug('ebay', 'An Item ('. $body['Item']['ItemID'] .') has been paid by the buyer and added to the store order (' . $newOrderId. ').');
			return true;
		}
		return false;
	}
 /**
  * Update the order status of a specific order from the manage orders page
  *
  * @return void
  **/
 private function UpdateOrderStatus()
 {
     $GLOBALS['ISC_CLASS_ADMIN_ENGINE']->LoadLangFile('orders');
     if (isset($_REQUEST['o']) && isset($_REQUEST['s'])) {
         $order_id = (int) $_REQUEST['o'];
         $status = (int) $_REQUEST['s'];
         $order = GetOrder($order_id);
         if ($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId() && $order['ordvendorid'] != $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId()) {
             echo 0;
             exit;
         }
         if (UpdateOrderStatus($order_id, $status)) {
             echo 1;
         } else {
             echo 0;
         }
     } else {
         echo 0;
     }
     exit;
 }
 public function ProcessGatewayPing()
 {
     $hash = $_REQUEST['isc_hash'];
     $returnStatus = $_REQUEST['status'];
     $md5sig = $_REQUEST['md5sig'];
     $merchant_id = $_REQUEST['merchant_id'];
     $pay_to_email = $_REQUEST['pay_to_email'];
     $mb_amount = $_REQUEST['mb_amount'];
     $mb_transaction_id = $_REQUEST['mb_transaction_id'];
     $session = $_REQUEST['isc_session'];
     $mb_currency = $_REQUEST['mb_currency'];
     $transaction_id = $_REQUEST['transaction_id'];
     $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess(array('payment', $this->GetName()), 'MoneyBookers Pingback');
     $this->SetOrderData(LoadPendingOrdersByToken($session));
     if (md5($GLOBALS['ISC_CFG']['serverStamp'] . $this->GetCombinedOrderId() . $session . number_format($this->GetGatewayAmount(), 2)) != $hash) {
         $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang($this->_languagePrefix . 'HashMismatch'));
         return false;
     }
     if (strtoupper(md5($merchant_id . $transaction_id . strtoupper(md5($this->GetValue('secretword'))) . $mb_amount . $mb_currency . $returnStatus)) != $md5sig) {
         $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang($this->_languagePrefix . 'HashMBMismatch'));
         return false;
     }
     $currency = GetDefaultCurrency();
     if ($returnStatus != 2) {
         $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang($this->_languagePrefix . 'Failure'));
         return false;
     }
     if ($mb_currency != $currency['currencycode']) {
         $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang($this->_languagePrefix . 'CurrencyMismatch'));
         return false;
     }
     if ($mb_amount != $this->GetGatewayAmount()) {
         $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang($this->_languagePrefix . 'PaymentMismatch'));
         return false;
     }
     if ($pay_to_email != $this->GetValue('mbemail')) {
         $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang($this->_languagePrefix . 'AccountMismatch'));
         return false;
     }
     $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess(array('payment', $this->GetName()), GetLang($this->_languagePrefix . 'Success'));
     // Update the status for all orders that we've just received the payment for
     foreach ($this->GetOrders() as $orderId => $order) {
         $status = ORDER_STATUS_AWAITING_FULFILLMENT;
         // If it's a digital order & awaiting fulfillment, automatically complete it
         if ($order['ordisdigital'] && ORDER_STATUS_AWAITING_FULFILLMENT) {
             $status = ORDER_STATUS_COMPLETED;
         }
         UpdateOrderStatus($orderId, $status);
     }
     return true;
 }
 /**
  * Handle a change of financial state of an order
  *
  * @param array $data The google request array
  *
  * @return void
  **/
 private function HandleFinancialStateChange($data)
 {
     $googleid = $data['google-order-number']['VALUE'];
     $orderid = $this->GetOrderIdByGoogleId($googleid);
     if ($orderid === false) {
         return;
     }
     $new_financial_state = $data['new-financial-order-state']['VALUE'];
     switch ($new_financial_state) {
         case 'REVIEWING':
             UpdateOrderStatus($orderid, ORDER_STATUS_PENDING, false, true);
             $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess($this->logtype, sprintf(GetLang('GoogleCheckoutOrderStatusUpdated'), $orderid, GetOrderStatusById(ORDER_STATUS_PENDING)));
             break;
         case 'CHARGEABLE':
             UpdateOrderStatus($orderid, ORDER_STATUS_AWAITING_PAYMENT, false, true);
             $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess($this->logtype, sprintf(GetLang('GoogleCheckoutOrderStatusUpdated'), $orderid, GetOrderStatusById(ORDER_STATUS_AWAITING_PAYMENT)));
             break;
         case 'CHARGING':
             // We don't need to do anything on our end when Google is midway through charging an order
             break;
         case 'CHARGED':
             $order = GetOrder($orderid, false);
             if (!OrderIsComplete($order['ordstatus'])) {
                 $this->module->debuglog($order);
                 if ($order['ordisdigital'] == 1) {
                     UpdateOrderStatus($orderid, ORDER_STATUS_COMPLETED, true, true);
                     $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess($this->logtype, sprintf(GetLang('GoogleCheckoutOrderStatusUpdated'), $orderid, GetOrderStatusById(ORDER_STATUS_COMPLETED)));
                 } else {
                     $status = $this->module->GetValue('orderchargestatus');
                     if (!$status) {
                         $status = ORDER_STATUS_AWAITING_FULFILLMENT;
                     }
                     UpdateOrderStatus($orderid, $status, false, true);
                     $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess($this->logtype, sprintf(GetLang('GoogleCheckoutOrderStatusUpdated'), $orderid, GetOrderStatusById($status)));
                 }
             }
             break;
         case 'PAYMENT_DECLINED':
             UpdateOrderStatus($orderid, ORDER_STATUS_DECLINED, false, true);
             $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess($this->logtype, sprintf(GetLang('GoogleCheckoutOrderStatusUpdated'), $orderid, GetOrderStatusById(ORDER_STATUS_DECLINED)));
             break;
         case 'CANCELLED':
             UpdateOrderStatus($orderid, ORDER_STATUS_CANCELLED, false, true);
             $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess($this->logtype, sprintf(GetLang('GoogleCheckoutOrderStatusUpdated'), $orderid, GetOrderStatusById(ORDER_STATUS_CANCELLED)));
             break;
         case 'CANCELLED_BY_GOOGLE':
             UpdateOrderStatus($orderid, ORDER_STATUS_CANCELLED, false, true);
             $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess($this->logtype, sprintf(GetLang('GoogleCheckoutOrderStatusUpdated'), $orderid, GetOrderStatusById(ORDER_STATUS_CANCELLED)));
             break;
         default:
             break;
     }
 }
 public function ProcessGatewayPing()
 {
     $pName = $_REQUEST['payer_name'];
     $pEmail = $_REQUEST['payer_email'];
     $qta = $_REQUEST['qta'];
     $thxId = $_REQUEST['thx_id'];
     $sessionToken = explode('_', $_REQUEST['custom'], 2);
     $payerId = $_REQUEST['payer_id'];
     $amount = $_REQUEST['amount'];
     $this->SetOrderData(LoadPendingOrdersByToken($sessionToken[0]));
     if ($this->GetGatewayAmount() == 0) {
         exit;
     }
     if ($amount != $this->GetGatewayAmount()) {
         $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), sprintf(GetLang($this->_languagePrefix . 'AmountMismatch'), $this->GetGatewayAmount(), $amount));
         return false;
     }
     if (isset($_REQUEST['payer_email'])) {
         $updatedOrder = array('ordpayproviderid' => $pEmail, 'ordpaymentstatus' => 'captured');
         $this->UpdateOrders($updatedOrder);
     }
     $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess(array('payment', $this->GetName()), GetLang($this->_languagePrefix . 'Success'));
     // If the order was previously incomplete, we need to do some extra work
     if ($this->GetOrderStatus() == 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]);
         $orderClass = GetClass('ISC_ORDER');
         $orderClass->EmptyCartAndKillCheckout();
     }
     // Update the status for all orders that we've just received the payment for
     foreach ($this->GetOrders() as $orderId => $order) {
         $status = ORDER_STATUS_AWAITING_FULFILLMENT;
         // If it's a digital order & awaiting fulfillment, automatically complete it
         if ($order['ordisdigital'] && ORDER_STATUS_AWAITING_FULFILLMENT) {
             $status = ORDER_STATUS_COMPLETED;
         }
         UpdateOrderStatus($orderId, $status);
     }
     return true;
 }
				/**
		 * 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;
		}
Exemple #19
0
 public function ProcessGatewayPing()
 {
     try {
         if (!isset($_REQUEST['SessionToken'])) {
             exit;
         }
         $sessionToken = explode('_', $_REQUEST['SessionToken'], 2);
         $this->SetOrderData(LoadPendingOrdersByToken($sessionToken[0]));
         $amount = $_REQUEST['amount'];
         $currency = $_REQUEST['currency'];
         $storeCurrency = GetDefaultCurrency();
         $storeCurrency = $storeCurrency['currencycode'];
         if ($amount != $this->GetGatewayAmount() || $this->GetGatewayAmount() == 0) {
             exit;
         }
         if ($storeCurrency != $currency) {
             exit;
         }
         switch ($_REQUEST['status']) {
             case '5':
                 $newOrderStatus = ORDER_STATUS_AWAITING_FULFILLMENT;
                 break;
             default:
                 $newOrderStatus = ORDER_STATUS_DECLINED;
                 break;
         }
         if ($this->GetOrderStatus() == ORDER_STATUS_INCOMPLETE) {
             session_write_close();
             $session = new ISC_SESSION($sessionToken[1]);
             $orderClass = GetClass('ISC_ORDER');
             $orderClass->EmptyCartAndKillCheckout();
         }
         foreach ($this->GetOrders() as $orderId => $order) {
             if ($order['ordisdigital'] && $newOrderStatus == ORDER_STATUS_AWAITING_FULFILLMENT) {
                 $status = ORDER_STATUS_COMPLETED;
             }
             UpdateOrderStatus($orderId, $newOrderStatus);
         }
         $updatedOrder = array('ordpayproviderid' => $_REQUEST['payid'], 'ordpaymentstatus' => 'captured');
         $this->UpdateOrders($updatedOrder);
         $oldStatus = GetOrderStatusById($order['ordstatus']);
         if (!$oldStatus) {
             $oldStatus = 'Incomplete';
         }
         $newStatus = GetOrderStatusById($newOrderStatus);
         $extra = sprintf(GetLang('OgoneSuccessDetails'), $order['orderid'], $order['ordgatewayamount'], $_REQUEST['PAYID'], $_REQUEST['STATUS'], $newStatus, $oldStatus);
         $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess(array('payment', $this->_name), GetLang('OgoneSuccess'), $extra);
     } catch (Exception $e) {
         $GLOBALS['ISC_CLASS_LOG']->LogSystemError($e->getMessage());
     }
     return true;
 }