/**
		 * 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;
		}
Beispiel #2
0
 private function ManageOrdersGrid(&$numOrders)
 {
     // Show a list of products in a table
     $page = 0;
     $start = 0;
     $numPages = 0;
     $GLOBALS['OrderGrid'] = "";
     $GLOBALS['Nav'] = "";
     $GLOBALS['SmallNav'] = "";
     $catList = "";
     $max = 0;
     // Is this a custom search?
     if (isset($_GET['searchId'])) {
         $this->_customSearch = $GLOBALS['ISC_CLASS_ADMIN_CUSTOMSEARCH']->LoadSearch($_GET['searchId']);
         $_REQUEST = array_merge($_REQUEST, (array) $this->_customSearch['searchvars']);
         // Override custom search sort fields if we have a requested field
         if (isset($_GET['sortField'])) {
             $_REQUEST['sortField'] = $_GET['sortField'];
         }
         if (isset($_GET['sortOrder'])) {
             $_REQUEST['sortOrder'] = $_GET['sortOrder'];
         }
     } else {
         if (isset($_GET['searchQuery'])) {
             $GLOBALS['Query'] = $_GET['searchQuery'];
         }
     }
     if (isset($_REQUEST['sortOrder']) && $_REQUEST['sortOrder'] == "asc") {
         $sortOrder = "asc";
     } else {
         $sortOrder = "desc";
     }
     $validSortFields = array('orderid', 'custname', 'orddate', 'ordstatus', 'newmessages', 'ordtotalamount', 'ordoverview');
     if (isset($_REQUEST['sortField']) && in_array($_REQUEST['sortField'], $validSortFields)) {
         $sortField = $_REQUEST['sortField'];
         SaveDefaultSortField("ManageOrders", $_REQUEST['sortField'], $sortOrder);
     } else {
         list($sortField, $sortOrder) = GetDefaultSortField("ManageOrders", "orderid", $sortOrder);
     }
     if (isset($_GET['page'])) {
         $page = (int) $_GET['page'];
     } else {
         $page = 1;
     }
     // Build the pagination and sort URL
     $searchURL = '';
     foreach ($_GET as $k => $v) {
         if ($k == "sortField" || $k == "sortOrder" || $k == "page" || $k == "new" || $k == "ToDo" || $k == "SubmitButton1" || !$v) {
             continue;
         }
         $searchURL .= sprintf("&%s=%s", $k, urlencode($v));
     }
     $sortURL = sprintf("%s&sortField=%s&sortOrder=%s", $searchURL, $sortField, $sortOrder);
     $GLOBALS['SortURL'] = $sortURL;
     // Limit the number of orders returned
     if ($page == 1) {
         $start = 1;
     } else {
         $start = $page * ISC_ORDERS_PER_PAGE - (ISC_ORDERS_PER_PAGE - 1);
     }
     $start = $start - 1;
     // Get the results for the query
     $orderResult = $this->_GetOrderList($start, $sortField, $sortOrder, $numOrders);
     $numPages = ceil($numOrders / ISC_ORDERS_PER_PAGE);
     // Add the "(Page x of n)" label
     if ($numOrders > ISC_ORDERS_PER_PAGE) {
         $GLOBALS['Nav'] = sprintf("(%s %d of %d)    ", GetLang('Page'), $page, $numPages);
         //alandy_2012-3-28 add.
         if (isset($_REQUEST['orderOwner']) && $_REQUEST['orderOwner'] != '') {
             $GLOBALS['Nav'] .= BuildPagination($numOrders, ISC_ORDERS_PER_PAGE, $page, sprintf("index.php?ToDo=viewOrders%s&orderOwner=%s", $sortURL, $_REQUEST['orderOwner']));
         } else {
             $GLOBALS['Nav'] .= BuildPagination($numOrders, ISC_ORDERS_PER_PAGE, $page, sprintf("index.php?ToDo=viewOrders%s", $sortURL));
         }
     } else {
         $GLOBALS['Nav'] = "";
     }
     if (isset($_GET['searchQuery'])) {
         $query = $_GET['searchQuery'];
     } else {
         $query = "";
     }
     $GLOBALS['Nav'] = rtrim($GLOBALS['Nav'], ' |');
     $GLOBALS['SmallNav'] = rtrim($GLOBALS['SmallNav'], ' |');
     $GLOBALS['SearchQuery'] = $query;
     $GLOBALS['SortField'] = $sortField;
     $GLOBALS['SortOrder'] = $sortOrder;
     $sortLinks = array("Id" => "orderid", "Cust" => "custname", "Date" => "orddate", "Status" => "ordstatus", "Message" => "newmessages", "Total" => "ordtotalamount", "Review" => "ordoverview");
     BuildAdminSortingLinks($sortLinks, "index.php?ToDo=viewOrders&" . $searchURL . "&page=" . $page, $sortField, $sortOrder);
     // Workout the maximum size of the array
     $max = $start + ISC_ORDERS_PER_PAGE;
     if ($max > count($orderResult)) {
         $max = count($orderResult);
     }
     if (!gzte11(ISC_LARGEPRINT)) {
         $GLOBALS['HideOrderMessages'] = "none";
         $GLOBALS['CustomerNameSpan'] = 2;
     }
     // Display the orders
     while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($orderResult)) {
         $GLOBALS['OrderId'] = $row['orderid'];
         $GLOBALS['CustomerId'] = $row['ordcustid'];
         $GLOBALS['OrderId1'] = $row['orderid'];
         $GLOBALS['Customer'] = isc_html_escape($row['custname']);
         $GLOBALS['Date'] = isc_date(GetConfig('DisplayDateFormat'), $row['orddate']);
         $GLOBALS['OrderStatusOptions'] = $this->GetOrderStatusOptions($row['ordstatus']);
         $GLOBALS['Total'] = FormatPriceInCurrency($row['ordtotalamount'], $row['orddefaultcurrencyid'], null, true);
         $GLOBALS['GatewayTotal'] = FormatPriceInCurrency($row['ordgatewayamount'], $row['orddefaultcurrencyid'], null, true);
         $GLOBALS['TrackingNo'] = isc_html_escape($row['ordtrackingno']);
         $orderreview = '';
         switch ($row['ordoverview']) {
             case 0:
                 $orderreview = GetLang('OviewRequestNo');
                 break;
             case 1:
                 $orderreview = GetLang('OviewRequestYes');
                 break;
             case 2:
                 $orderreview = GetLang('OviewRequestSure');
                 break;
             default:
                 $orderreview = GetLang('OviewRequestNo');
                 break;
         }
         $GLOBALS['Review'] = $orderreview;
         // Look up the country for the IP address of this order
         if (gzte11(ISC_LARGEPRINT)) {
             $suspiciousOrder = false;
             $GLOBALS['FlagCellClass'] = $GLOBALS['FlagCellTitle'] = '';
             if ($row['ordgeoipcountrycode'] != '') {
                 $flag = strtolower($row['ordgeoipcountrycode']);
                 // If the GeoIP based country code and the billing country code don't match, we flag this order as a different colour
                 if (strtolower($row['ordgeoipcountrycode']) != strtolower($row['ordbillcountrycode'])) {
                     $GLOBALS['FlagCellClass'] = "Suspicious";
                     $suspiciousOrder = true;
                 }
                 $countryName = $row['ordgeoipcountry'];
             } else {
                 $flag = strtolower($row['ordbillcountrycode']);
                 $countryName = $row['ordbillcountry'];
                 $GLOBALS['FlagCellTitle'] = $row['ordbillcountry'];
             }
             // Do we have a country flag to show?
             if (file_exists(ISC_BASE_PATH . "/lib/flags/" . $flag . ".gif")) {
                 $flag = GetConfig('AppPath') . "/lib/flags/" . $flag . ".gif";
                 if ($suspiciousOrder == true) {
                     $title = sprintf(GetLang('OrderCountriesDontMatch'), $row['ordbillcountry'], $row['ordgeoipcountry']);
                     $GLOBALS['OrderCountryFlag'] = "<span onmouseout=\"HideQuickHelp(this);\" onmouseover=\"ShowQuickHelp(this, '" . GetLang('PossibleFraudulentOrder') . "', '" . $title . "');\"><img src=\"" . $flag . "\" alt='' /></span>";
                 } else {
                     $GLOBALS['OrderCountryFlag'] = "<img src=\"" . $flag . "\" alt='' title=\"" . $countryName . "\" />";
                 }
             } else {
                 $GLOBALS['OrderCountryFlag'] = '';
             }
         } else {
             $GLOBALS['HideCountry'] = "none";
         }
         // Workout the message link -- do they have permission to view order messages?
         $GLOBALS["HideMessages"] = "none";
         if ($GLOBALS['ISC_CLASS_ADMIN_AUTH']->HasPermission(AUTH_Order_Messages) && $row['ordcustid'] > 0) {
             $numMessages = GetLang('Messages');
             if ($row['nummessages'] == 1) {
                 $numMessages = GetLang('OrderMessage');
             }
             $newMessages = '0 ' . GetLang('NewText');
             if ($row['newmessages'] > 0) {
                 $newMessages = "<strong>" . $row['newmessages'] . " " . GetLang('NewText') . "</strong>";
             }
             $GLOBALS['MessageLink'] = sprintf("<a title='%s' class='Action' href='index.php?ToDo=viewOrderMessages&amp;ord\n\t\t\t\t\terId=%d'>%s %s</a><br />(%s)", GetLang('MessageOrder'), $row['orderid'], $row['nummessages'], $numMessages, $newMessages);
             if ($row["numunreadmessages"] > 0 && gzte11(ISC_LARGEPRINT)) {
                 $GLOBALS["HideMessages"] = "";
                 $GLOBALS["NumMessages"] = $row['numunreadmessages'];
             }
         } else {
             $GLOBALS['MessageLink'] = sprintf("<a class='Action' disabled>%s (0)</a>", GetLang('Messages'));
         }
         if (!gzte11(ISC_LARGEPRINT)) {
             $GLOBALS["HideMessages"] = "none";
         }
         // If the customer still exists, link to the customer page
         if (trim($row['custname']) != '') {
             $GLOBALS['CustomerLink'] = "<a href='index.php?ToDo=viewCustomers&amp;idFrom=" . $GLOBALS['CustomerId'] . "&idTo=" . $GLOBALS['CustomerId'] . "'>" . $GLOBALS['Customer'] . "</a>";
         } else {
             $GLOBALS['CustomerLink'] = $row['ordbillfirstname'] . ' ' . $row['ordbilllastname'];
         }
         if ($row['ordcustid'] == 0) {
             $GLOBALS['CustomerLink'] .= " <span style=\"color: gray;\">" . GetLang('GuestCheckoutCustomer') . "</span>";
         }
         // If the order has any notes, flag it
         if ($row['ordnotes'] != '') {
             $GLOBALS['HasNotesClass'] = 'HasNotes';
         } else {
             $GLOBALS['HasNotesClass'] = '';
         }
         // If the order has any shipable items, show the link to ship items
         $GLOBALS['ShipItemsLink'] = '';
         if (isset($row['ordtotalshipped']) && isset($row['ordtotalqty'])) {
             if ($row['ordisdigital'] == 0 && $row['ordtotalqty'] - $row['ordtotalshipped'] > 0) {
                 $GLOBALS['ShipItemsLink'] = '<option id="ShipItemsLink' . $row['orderid'] . '"  value="shipItems">' . GetLang('ShipItems') . '</option>';
             }
         }
         //Show payment status blow order status
         $GLOBALS['PaymentStatus'] = '';
         $GLOBALS['HidePaymentStatus'] = 'display:none;';
         $GLOBALS['PaymentStatusColor'] = '';
         if ($row['ordpaymentstatus'] != '') {
             $GLOBALS['HidePaymentStatus'] = '';
             $GLOBALS['PaymentStatusColor'] = '';
             switch ($row['ordpaymentstatus']) {
                 case 'authorized':
                     $GLOBALS['PaymentStatusColor'] = 'PaymentAuthorized';
                     break;
                 case 'captured':
                     $GLOBALS['PaymentStatus'] = GetLang('Payment') . " " . ucfirst($row['ordpaymentstatus']);
                     $GLOBALS['PaymentStatusColor'] = 'PaymentCaptured';
                     break;
                 case 'refunded':
                 case 'partially refunded':
                 case 'voided':
                     $GLOBALS['PaymentStatus'] = GetLang('Payment') . " " . ucwords($row['ordpaymentstatus']);
                     $GLOBALS['PaymentStatusColor'] = 'PaymentRefunded';
                     break;
             }
         }
         // If the allow payment delayed capture, show the link to Delayed capture
         $GLOBALS['DelayedCaptureLink'] = '';
         $GLOBALS['VoidLink'] = '';
         $GLOBALS['RefundLink'] = '';
         $transactionId = trim($row['ordpayproviderid']);
         //if orginal transaction id exist and payment provider is currently enabled
         if ($transactionId != '' && GetModuleById('checkout', $provider, $row['orderpaymentmodule']) && $provider->IsEnabled() && !gzte11(ISC_HUGEPRINT)) {
             //if the payment module allow delayed capture and the current payment status is authorized
             //display delay capture option
             if (method_exists($provider, "DelayedCapture") && $row['ordpaymentstatus'] == 'authorized') {
                 $GLOBALS['DelayedCaptureLink'] = '<option value="delayedCapture">' . GetLang('CaptureFunds') . '</option>';
                 $GLOBALS['PaymentStatus'] .= '<a onclick="Order.DelayedCapture(' . $row['orderid'] . '); return false;" href="#">' . GetLang('CaptureFunds') . '</a>';
             }
             //if the payment module allow void transaction and the current payment status is authorized
             //display void option
             if (method_exists($provider, "DoVoid") && $row['ordpaymentstatus'] == 'authorized') {
                 $GLOBALS['VoidLink'] = '<option value="voidTransaction">' . GetLang('VoidTransaction') . '</option>';
             }
             //if the payment module allow refund and the current payment status is authorized
             //display refund option
             if (method_exists($provider, "DoRefund") && ($row['ordpaymentstatus'] == 'captured' || $row['ordpaymentstatus'] == 'partially refunded')) {
                 $GLOBALS['RefundLink'] = '<option value="refundOrder">' . GetLang('Refund') . '</option>';
             }
         }
         $GLOBALS["OrderStatusText"] = GetOrderStatusById($row['ordstatus']);
         $GLOBALS['OrderStatusId'] = $row['ordstatus'];
         $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("order.manage.row");
         $GLOBALS['OrderGrid'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate(true);
     }
     // Close the GeoIP database if we used it
     if (isset($gi)) {
         geoip_close($gi);
     }
     // Hide the message box in templates/iphone/MessageBox.html if we're not searching
     if (!isset($_REQUEST["searchQuery"]) && isset($_REQUEST["page"])) {
         $GLOBALS["HideYellowMessage"] = "none";
     }
     $GLOBALS['CurrentPage'] = $page;
     $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("orders.manage.grid");
     return $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate(true);
 }
 /**
  * Handle the status change of an order. This is used to send google notifications so that ISC and
  * the Google control panel keep the order state at the same stage. It is also so that you can
  * approve, ship etc orders from the ISC control panel.
  *
  * @param integer $orderid The ISC order id whose status is changing
  * @param integer $oldstatus The status id the order is changing from. Order status are defined in lib/init.php.
  * @param integer $newstatus The new status id the order is changing to.
  * @param mixed $data Extra data associated with the status change
  *
  * @return void
  **/
 public function HandleStatusChange($orderid, $oldstatus, $newstatus, $data = '')
 {
     $request_result = '';
     $query = "\n\t\t\t\tSELECT *\n\t\t\t\tFROM [|PREFIX|]orders\n\t\t\t\tWHERE orderpaymentmodule = '" . $GLOBALS['ISC_CLASS_DB']->Quote($this->GetId()) . "'\n\t\t\t\tAND orderid = '" . $GLOBALS['ISC_CLASS_DB']->Quote($orderid) . "'\n\t\t\t";
     $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
     $order = $GLOBALS['ISC_CLASS_DB']->Fetch($result);
     switch ($newstatus) {
         case ORDER_STATUS_CANCELLED:
             $request_result = $this->request->SendCancelOrder($order['ordpayproviderid'], GetLang('GoogleCheckoutOrderCancelledByVendor'), '');
             break;
         case ORDER_STATUS_REFUNDED:
             $request_result = $this->request->SendRefundOrder($order['ordpayproviderid'], $data, GetLang('GoogleCheckoutOrderRefundedByVendor'), 'def');
             break;
         case ORDER_STATUS_AWAITING_FULFILLMENT:
         case ORDER_STATUS_AWAITING_SHIPMENT:
         case ORDER_STATUS_AWAITING_PICKUP:
         case ORDER_STATUS_SHIPPED:
         case ORDER_STATUS_COMPLETED:
         case ORDER_STATUS_PARTIALLY_SHIPPED:
             switch ($oldstatus) {
                 case ORDER_STATUS_AWAITING_PAYMENT:
                     $request_result = $this->request->SendChargeOrder($order['ordpayproviderid'], 0);
                     break;
             }
             if ($newstatus == ORDER_STATUS_COMPLETED) {
                 $request_result = $this->request->SendDeliverOrder($order['ordpayproviderid']);
             }
             break;
     }
     $GLOBALS['ISC_CLASS_LOG']->LogSystemDebug(array('payment', $this->GetName()), "Status change for #{$orderid} from " . GetOrderStatusById($oldstatus) . " to " . GetOrderStatusById($newstatus));
 }
 /**
  * Display a summary of all the orders for a given customer
  *
  * @return void
  **/
 private function GetCustomerOrders()
 {
     $GLOBALS['ISC_CLASS_ADMIN_ENGINE']->LoadLangFile('customers');
     $custId = (int) $_REQUEST['c'];
     // Get the details for the orders from the database
     $query = "\n\t\t\t\tSELECT o.*, c.custconemail\n\t\t\t\tFROM [|PREFIX|]orders o\n\t\t\t\tLEFT JOIN [|PREFIX|]customers c ON (c.customerid=o.ordcustid)\n\t\t\t\tWHERE ordcustid='" . (int) $custId . "' AND ordstatus != 0\n\t\t\t";
     if ($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId()) {
         $query .= " AND ordvendorid='" . (int) $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId() . "'";
     }
     $query .= "ORDER BY orderid DESC";
     $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
     while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
         // Output the details of the order
         $GLOBALS['OrderId'] = (int) $row['orderid'];
         $GLOBALS['OrderStatus'] = GetOrderStatusById($row['ordstatus']);
         $GLOBALS['OrderTotal'] = FormatPrice($row['ordtotalamount']);
         $GLOBALS['OrderDate'] = CDate($row['orddate']);
         $GLOBALS['OrderViewLink'] = '<a href="#" onclick="viewOrderNotes(' . $row['orderid'] . '); return false;">' . GetLang('CustomerOrderListNotesLink') . '</a>';
         $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("customer.quickorder");
         $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate();
         // The email is used by the view all orders button
         $GLOBALS['Email'] = isc_html_escape($row['custconemail']);
         $GLOBALS['CustomerId'] = $row['ordcustid'];
     }
     $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("customer.quickorderall");
     $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate();
 }
Beispiel #5
0
 /**
  * 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;
     }
 }
Beispiel #6
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;
	}
}
Beispiel #7
0
		protected function ManageOrdersGrid(&$numOrders, &$numDeletedOrders = 0)
		{
			// Show a list of products in a table
			$page = 0;
			$start = 0;
			$GLOBALS['OrderGrid'] = "";
			$catList = "";
			$max = 0;

			// Is this a custom search?
			if(isset($_GET['searchId'])) {
				// Override custom search sort fields if we have a requested field
				if(isset($_GET['sortField'])) {
					$_REQUEST['sortField'] = $_GET['sortField'];
				}
				if(isset($_GET['sortOrder'])) {
					$_REQUEST['sortOrder'] = $_GET['sortOrder'];
				}
			}

			if(isset($_GET['searchQuery'])) {
				$GLOBALS['QueryEscaped'] = isc_html_escape($_GET['searchQuery']);
			}

			if(isset($_REQUEST['sortOrder']) && $_REQUEST['sortOrder'] == "asc") {
				$sortOrder = "asc";
			}
			else {
				$sortOrder = "desc";
			}

			$validSortFields = array('orderid', 'custname', 'orddate', 'ordstatus', 'newmessages', 'total_inc_tax');
			if(isset($_REQUEST['sortField']) && in_array($_REQUEST['sortField'], $validSortFields)) {
				$sortField = $_REQUEST['sortField'];
				SaveDefaultSortField("ManageOrders", $_REQUEST['sortField'], $sortOrder);
			}
			else {
				list($sortField, $sortOrder) = GetDefaultSortField("ManageOrders", "orderid", $sortOrder);
			}

			if (isset($_GET['page'])) {
				$page = (int)$_GET['page'];
			} else {
				$page = 1;
			}

			if (isset($_GET['perpage'])) {
				$perPage = (int)$_GET['perpage'];
				SaveDefaultPerPage("ManageOrders", $perPage);
			}
			else {
				$perPage = GetDefaultPerPage("ManageOrders", ISC_ORDERS_PER_PAGE);
			}

			// Build the pagination and sort URL
			$searchURL = $_GET;
			unset($searchURL['sortField'], $searchURL['sortOrder'], $searchURL['page'], $searchURL['new'], $searchURL['ToDo'], $searchURL['SubmitButton1'], $searchURL['SearchButton_x'], $searchURL['SearchButton_y']);
			$searchURL['sortField'] = $sortField;
			$searchURL['sortOrder'] = $sortOrder;
			$this->template->assign('searchURL', $searchURL);

			$sortURL = $searchURL;
			unset($sortURL['sortField'], $sortURL['sortOrder']);

			// Limit the number of orders returned
			if ($page == 1) {
				$start = 1;
			} else {
				$start = ($page * $perPage) - ($perPage-1);
			}

			$start = $start-1;

			// Get the results for the query
			$orderResult = $this->_GetOrderList($start, $sortField, $sortOrder, $numOrders, $perPage, $numDeletedOrders);

			$GLOBALS['perPage'] = $perPage;
			$GLOBALS['numOrders'] = $numOrders;
			$GLOBALS['pageURL'] = "index.php?ToDo=viewOrders&" . http_build_query($searchURL);
			$GLOBALS['currentPage'] = $page;

			$this->template->assign('numDeletedOrders', $numDeletedOrders);

			if ($numOrders && $numDeletedOrders) {
				$searchGet = $_GET;
				if (isset($searchGet['searchId']) && $searchGet['searchId'] == 0) {
					unset($searchGet['searchId']);
				}

				if (count($searchGet) > 1) {
					$deletedUrl = $searchGet;
					$deletedUrl['searchDeletedOrders'] = 'only';
					$deletedUrl = 'index.php?' . http_build_query($deletedUrl);
					$this->template->assign('viewDeletedOrdersUrl', $deletedUrl);
					unset($deletedUrl);
				}
				unset($searchGet);
			}

			if(isset($_GET['searchQuery'])) {
				$query = $_GET['searchQuery'];
			} else {
				$query = "";
			}

			$GLOBALS['SearchQuery'] = $query;
			$GLOBALS['SortField'] = $sortField;
			$GLOBALS['SortOrder'] = $sortOrder;

			$sortLinks = array(
				"Id" => "orderid",
				"Cust" => "custname",
				"Date" => "orddate",
				"Status" => "ordstatus",
				"Message" => "newmessages",
				"Total" => "total_inc_tax"
			);
			BuildAdminSortingLinks($sortLinks, "index.php?ToDo=viewOrders&amp;".http_build_query($sortURL)."&amp;page=".$page, $sortField, $sortOrder);

			// Workout the maximum size of the array
			$max = $start + $perPage;

			if ($max > count($orderResult)) {
				$max = count($orderResult);
			}

			if(!gzte11(ISC_LARGEPRINT)) {
				$GLOBALS['HideOrderMessages'] = "none";
				$GLOBALS['CustomerNameSpan'] = 2;
			}

			// Display the orders
			while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($orderResult)) {
				$this->template->assign('order', $row);
				$GLOBALS['OrderId'] = $row['orderid'];
				$GLOBALS['CustomerId'] = $row['ordcustid'];
				$GLOBALS['OrderId1'] = $row['orderid'];
				$GLOBALS['Customer'] = isc_html_escape($row['custname']);

				$GLOBALS['Date'] = isc_date(GetConfig('DisplayDateFormat'), $row['orddate']);
				$GLOBALS['OrderStatusOptions'] = $this->GetOrderStatusOptions($row['ordstatus']);

				$GLOBALS['Total'] = FormatPriceInCurrency($row['total_inc_tax'], $row['orddefaultcurrencyid'], null, true);

				$GLOBALS['NotesIcon'] = "";
				$GLOBALS['CommentsIcon'] = "";

				// Look up the country for the IP address of this order
				if(gzte11(ISC_LARGEPRINT)) {
					$suspiciousOrder = false;
					$GLOBALS['FlagCellClass'] = $GLOBALS['FlagCellTitle'] = '';
					if($row['ordgeoipcountrycode'] != '') {
						$flag = strtolower($row['ordgeoipcountrycode']);
						// If the GeoIP based country code and the billing country code don't match, we flag this order as a different colour
						if(strtolower($row['ordgeoipcountrycode']) != strtolower($row['ordbillcountrycode'])) {
							$GLOBALS['FlagCellClass'] = "Suspicious";
							$suspiciousOrder = true;

						}
						$countryName = $row['ordgeoipcountry'];
					}
					else {
						$flag = strtolower($row['ordbillcountrycode']);
						$countryName = $row['ordbillcountry'];
						$GLOBALS['FlagCellTitle'] = $row['ordbillcountry'];
					}
					// Do we have a country flag to show?
					if(file_exists(ISC_BASE_PATH."/lib/flags/".$flag.".gif")) {
						$flag = GetConfig('AppPath')."/lib/flags/".$flag.".gif";
						if($suspiciousOrder == true) {
							$title = sprintf(GetLang('OrderCountriesDontMatch'), $row['ordbillcountry'], $row['ordgeoipcountry']);
							$GLOBALS['OrderCountryFlag'] = "<span onmouseout=\"HideQuickHelp(this);\" onmouseover=\"ShowQuickHelp(this, '".GetLang('PossibleFraudulentOrder')."', '".$title."');\"><img src=\"".$flag."\" alt='' /></span>";
						}
						else {
							$GLOBALS['OrderCountryFlag'] = "<img src=\"".$flag."\" alt='' title=\"".$countryName."\" />";
						}
					}
					else {
						$GLOBALS['OrderCountryFlag'] = '';
					}
				}
				else {
					$GLOBALS['HideCountry'] = "none";
				}

				// If this is ebay item, we will have the icon as eBay icon
				$GLOBALS['OrderIcon'] = 'order.gif';
				if ($row['ebay_order_id'] != '0') {
					$GLOBALS['OrderIcon'] = 'ebay.gif';
				}

				// Workout the message link -- do they have permission to view order messages?
				$GLOBALS["HideMessages"] = "none";

				if($GLOBALS['ISC_CLASS_ADMIN_AUTH']->HasPermission(AUTH_Order_Messages) && $row['ordcustid'] > 0) {
					$numMessages = GetLang('Messages');
					if($row['nummessages'] == 1) {
						$numMessages = GetLang('OrderMessage');
					}
					$newMessages = '0 '.GetLang('NewText');
					if($row['newmessages'] > 0) {
						$newMessages = "<strong>" . $row['newmessages'] . " " . GetLang('NewText') . "</strong>";
					}
					$GLOBALS['MessageLink'] = sprintf("<a title='%s' class='Action' href='index.php?ToDo=viewOrderMessages&amp;ord
					erId=%d'>%s %s</a><br />(%s)",
						GetLang('MessageOrder'),
						$row['orderid'],
						$row['nummessages'],
						$numMessages,
						$newMessages
					);

					if($row["numunreadmessages"] > 0 && gzte11(ISC_LARGEPRINT)) {
						$GLOBALS["HideMessages"] = "";
						$GLOBALS["NumMessages"] = $row['numunreadmessages'];
					}
				}
				else {
					$GLOBALS['MessageLink'] = sprintf("<a class='Action' disabled>%s (0)</a>", GetLang('Messages'));
				}

				if(!gzte11(ISC_LARGEPRINT)) {
					$GLOBALS["HideMessages"] = "none";
				}

				// If the customer still exists, link to the customer page
				if(trim($row['custname']) != '') {
					$GLOBALS['CustomerLink'] = "<a href='index.php?ToDo=viewCustomers&amp;idFrom=".$GLOBALS['CustomerId']."&idTo=".$GLOBALS['CustomerId']."'>".$GLOBALS['Customer']."</a>";
				}
				else {
					$GLOBALS['CustomerLink'] = $row['ordbillfirstname'].' '.$row['ordbilllastname'];
				}

				if($row['ordcustid'] == 0) {
					$GLOBALS['CustomerLink'] .= " <span style=\"color: gray;\">".GetLang('GuestCheckoutCustomer')."</span>";
				}

				// If the order has any notes, flag it
				if($row['ordnotes'] != '') {
					$GLOBALS['NotesIcon'] = '<a href="#" onclick="Order.HandleAction(' . $row['orderid'] . ', \'orderNotes\');"><img src="images/note.png" alt="" title="' . GetLang('OrderHasNotes') . '" style="border-style: none;" /></a>';
					$GLOBALS['HasNotesClass'] = 'HasNotes';
				}
				else {
					$GLOBALS['HasNotesClass'] = '';
				}

				// does the order have a customer message?
				if (!empty($row['ordcustmessage'])) {
					$GLOBALS['CommentsIcon'] = '<a href="#" onclick="Order.HandleAction(' . $row['orderid'] . ', \'orderNotes\');"><img src="images/user_comment.png" alt="" title="' . GetLang('OrderHasComments') . '" style="border-style: none;" /></a>';
				}

				// If the order has any shipable items, show the link to ship items
				$GLOBALS['ShipItemsLink'] = '';
				if (!$row['deleted'] && isset($row['ordtotalshipped']) && isset($row['ordtotalqty'])) {
					if($row['ordisdigital'] == 0 && ($row['ordtotalqty']-$row['ordtotalshipped']) > 0) {
						$addClass = '';
						if($row['shipping_address_count'] > 1) {
							$addClass = 'MultipleAddresses';
						}
						$GLOBALS['ShipItemsLink'] = '<option id="ShipItemsLink'.$row['orderid'].'"  value="shipItems'.$addClass.'">'.GetLang('ShipItems').'</option>';
					}
				}

				//Show payment status blow order status
				$GLOBALS['PaymentStatus'] = '';
				$GLOBALS['HidePaymentStatus'] = 'display:none;';
				$GLOBALS['PaymentStatusColor'] = '';
				if($row['ordpaymentstatus'] != '') {
					$GLOBALS['HidePaymentStatus'] = '';
					$GLOBALS['PaymentStatusColor'] = '';
					switch($row['ordpaymentstatus']) {
						case 'authorized':
							$GLOBALS['PaymentStatusColor'] = 'PaymentAuthorized';
							break;
						case 'captured':
							$GLOBALS['PaymentStatus'] = GetLang('Payment')." ".ucfirst($row['ordpaymentstatus']);
							$GLOBALS['PaymentStatusColor'] = 'PaymentCaptured';
							break;
						case 'refunded':
						case 'partially refunded':
						case 'voided':
							$GLOBALS['PaymentStatus'] = GetLang('Payment')." ".ucwords($row['ordpaymentstatus']);
							$GLOBALS['PaymentStatusColor'] = 'PaymentRefunded';
							break;
					}
				}


				// If the allow payment delayed capture, show the link to Delayed capture
				$GLOBALS['DelayedCaptureLink'] = '';
				$GLOBALS['VoidLink'] = '';
				$GLOBALS['RefundLink'] ='';
				$transactionId = trim($row['ordpayproviderid']);

				//if orginal transaction id exist and payment provider is currently enabled
				if($transactionId != '' && GetModuleById('checkout', $provider, $row['orderpaymentmodule']) && $provider->IsEnabled() && !gzte11(ISC_HUGEPRINT)) {
					//if the payment module allow delayed capture and the current payment status is authorized
					//display delay capture option
					if(method_exists($provider, "DelayedCapture") && $row['ordpaymentstatus'] == 'authorized') {
						$GLOBALS['DelayedCaptureLink'] = '<option value="delayedCapture">'.GetLang('CaptureFunds').'</option>';

						$GLOBALS['PaymentStatus'] .= '<a onclick="Order.DelayedCapture('.$row['orderid'].'); return false;" href="#">'.GetLang('CaptureFunds').'</a>';
					}

					//if the payment module allow void transaction and the current payment status is authorized
					//display void option
					if(method_exists($provider, "DoVoid") && $row['ordpaymentstatus'] == 'authorized') {
						$GLOBALS['VoidLink'] = '<option value="voidTransaction">'.GetLang('VoidTransaction').'</option>';
					}

					//if the payment module allow refund and the current payment status is authorized
					//display refund option
					if(method_exists($provider, "DoRefund") && ($row['ordpaymentstatus'] == 'captured' || $row['ordpaymentstatus'] == 'partially refunded')) {
						$GLOBALS['RefundLink'] = '<option value="refundOrder">'.GetLang('Refund').'</option>';
					}
				}

				$GLOBALS["OrderStatusText"] = GetOrderStatusById($row['ordstatus']);
				$GLOBALS['OrderStatusId'] = $row['ordstatus'];
				$GLOBALS['OrderGrid'] .= $this->template->render('order.manage.row.tpl');
			}

			// Close the GeoIP database if we used it
			if(isset($gi)) {
				geoip_close($gi);
			}

			// Hide the message box in templates/iphone/MessageBox.html if we're not searching
			if(!isset($_REQUEST["searchQuery"]) && isset($_REQUEST["page"])) {
				$GLOBALS["HideYellowMessage"] = "none";
			}

			$GLOBALS['CurrentPage'] = $page;

			return $this->template->render('orders.manage.grid.tpl');
		}
Beispiel #8
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);
    // 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['ISC_LANG']['OrderStatusChangedHi'] = sprintf(GetLang('OrderStatusChangedHi'), isc_html_escape($customer['custconfirstname']));
    $GLOBALS['ISC_LANG']['OrderNumberStatusChangedTo'] = sprintf(GetLang('OrderNumberStatusChangedTo'), $order['orderid'], $statusName);
    $GLOBALS['OrderTotal'] = FormatPrice($order['ordtotalamount'], 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 = "\n\t\tSELECT COUNT(*)\n\t\tFROM [|PREFIX|]order_products\n\t\tWHERE ordprodtype='digital'\n\t\tAND orderorderid='" . $GLOBALS['ISC_CLASS_DB']->Quote($orderId) . "'\n\t";
    $numDigitalProducts = $GLOBALS['ISC_CLASS_DB']->FetchOne($query);
    $emailTemplate = FetchEmailTemplateParser();
    $GLOBALS['SNIPPETS']['CartItems'] = "";
    if (OrderIsComplete($status) && $numDigitalProducts > 0) {
        $query = "\n\t\t\tSELECT *\n\t\t\tFROM [|PREFIX|]order_products op INNER JOIN [|PREFIX|]products p ON (op.ordprodid = p.productid)\n\t\t\tWHERE ordprodtype='digital'\n\t\t\tAND orderorderid='" . $GLOBALS['ISC_CLASS_DB']->Quote($orderId) . "'\n\t\t";
        $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");
        }
    }
    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;
    }
}
Beispiel #9
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;
	}
Beispiel #10
0
 /**
  *    Show how many times each product has been viewed
  */
 public function SalesStatsByNumViewsGrid()
 {
     $GLOBALS['OrderGrid'] = "";
     if (isset($_GET['From']) && isset($_GET['To'])) {
         $from_stamp = (int) $_GET['From'];
         $to_stamp = (int) $_GET['To'];
         // How many records per page?
         if (isset($_GET['Show'])) {
             $per_page = (int) $_GET['Show'];
         } else {
             $per_page = 20;
         }
         $cursortfield = '';
         if (isset($_GET['vendorId']) && $_GET['vendorId'] != '-1') {
             $cursortfield = " AND (orderowner='" . $_GET['vendorId'] . "')";
         }
         $GLOBALS['ProductsPerPage'] = $per_page;
         $GLOBALS["IsShowPerPage" . $per_page] = 'selected="selected"';
         // Should we limit the records returned?
         if (isset($_GET['Page'])) {
             $page = (int) $_GET['Page'];
         } else {
             $page = 1;
         }
         $GLOBALS['salesByNumViewsCurrentPage'] = $page;
         // Workout the start and end records
         $start = $per_page * $page - $per_page;
         $end = $start + ($per_page - 1);
         // How many products are there in total?
         $CountQuery = "\n        SELECT \n            count(*) AS num\n                FROM [|PREFIX|]orders o\n                    LEFT JOIN [|PREFIX|]customers c ON (o.ordcustid=c.customerid)\n                    LEFT JOIN [|PREFIX|]order_status s ON (s.statusid=o.ordstatus)\n                WHERE\n                    o.ordstatus > 0 \n                    AND o.orddate >= '" . $from_stamp . "'\n                    AND o.orddate <= '" . $to_stamp . "'" . $cursortfield;
         $result = $GLOBALS['ISC_CLASS_DB']->Query($CountQuery);
         $row = $GLOBALS['ISC_CLASS_DB']->Fetch($result);
         $total_products = $row['num'];
         if ($total_products > 0) {
             //Sorting code goes by Simha
             if (isset($_GET['SortOrder']) && $_GET['SortOrder'] == "asc") {
                 $sortOrder = 'asc';
             } else {
                 $sortOrder = 'desc';
             }
             //changed field name and commented
             $sortFields = array('orderid', 'custname', 'orddate', 'ordstatus', 'ordtotalamount');
             //changed field name
             if (isset($_GET['SortBy']) && in_array($_GET['SortBy'], $sortFields)) {
                 $sortField = $_GET['SortBy'];
                 SaveDefaultSortField("ProductStatsByViews", $_REQUEST['SortBy'], $sortOrder);
             } else {
                 list($sortField, $sortOrder) = GetDefaultSortField("ProductStatsByViews", "o.orderid", $sortOrder);
             }
             $sortLinks = array("OrderId" => "orderid", "Cusname" => "custname", "OrdDate" => "orddate", "Status" => "ordstatus", "Total" => "ordtotalamount");
             //Above comment and new addition belowby Simha
             //$sortLinks = array();
             $numSoldCounter = '921124412848294';
             BuildAdminSortingLinks($sortLinks, "javascript:SortSalesByNumViews('%%SORTFIELD%%', '%%SORTORDER%%');", $sortField, $sortOrder);
             //Sorting code goes ends by Simha
             // Workout the paging
             $num_pages = ceil($total_products / $per_page);
             // Should we limit the records returned?
             if (isset($_GET['Page']) && (int) $_GET['Page'] <= $num_pages) {
                 $page = (int) $_GET['Page'];
             } else {
                 $page = 1;
             }
             // Workout the start and end records
             $start = $per_page * $page - $per_page;
             $end = $start + ($per_page - 1);
             $paging = sprintf(GetLang('PageXOfX'), $page, $num_pages);
             $paging .= "&nbsp;&nbsp;&nbsp;&nbsp;";
             // Is there more than one page? If so show the &laquo; to jump back to page 1
             if ($num_pages > 1) {
                 $paging .= "<a href='javascript:void(0)' onclick='ChangeSalesViewsPage(1)'>&laquo;</a> | ";
             } else {
                 $paging .= "&laquo; | ";
             }
             // Are we on page 2 or above?
             if ($page > 1) {
                 $paging .= sprintf("<a href='javascript:void(0)' onclick='ChangeSalesViewsPage(%d)'>%s</a> | ", $page - 1, GetLang('Prev'));
             } else {
                 $paging .= sprintf("%s | ", GetLang('Prev'));
             }
             for ($i = 1; $i <= $num_pages; $i++) {
                 // Only output paging -5 and +5 pages from the page we're on
                 if ($i >= $page - 6 && $i <= $page + 5) {
                     if ($page == $i) {
                         $paging .= sprintf("<strong>%d</strong> | ", $i);
                     } else {
                         $paging .= sprintf("<a href='javascript:void(0)' onclick='ChangeSalesViewsPage(%d)'>%d</a> | ", $i, $i);
                     }
                 }
             }
             // Are we on page 2 or above?
             if ($page < $num_pages) {
                 $paging .= sprintf("<a href='javascript:void(0)' onclick='ChangeSalesViewsPage(%d)'>%s</a> | ", $page + 1, GetLang('Next'));
             } else {
                 $paging .= sprintf("%s | ", GetLang('Next'));
             }
             // Is there more than one page? If so show the &raquo; to go to the last page
             if ($num_pages > 1) {
                 $paging .= sprintf("<a href='javascript:void(0)' onclick='ChangeSalesViewsPage(%d)'>&raquo;</a> | ", $num_pages);
             } else {
                 $paging .= "&raquo; | ";
             }
             $paging = rtrim($paging, ' |');
             $GLOBALS['Paging'] = $paging;
             // Should we set focus to the grid?
             if (isset($_GET['FromLink']) && $_GET['FromLink'] == "true") {
                 $GLOBALS['JumpToOrdersByItemsSoldGrid'] = "<script type=\"text/javascript\">document.location.href='#ordersByItemsSoldAnchor';</script>";
             }
             //Sorting code moved to the topof this loop
             //Code here has been moved to the fucntion GetQueries
             // Add the Limit
             $mainQuery = "SELECT o.*, c.*,us.username, s.statusdesc AS ordstatustext, CONCAT(custconfirstname, ' ', custconlastname) AS custname\n                    \n                FROM [|PREFIX|]orders o\n                    LEFT JOIN [|PREFIX|]customers c ON (o.ordcustid=c.customerid)\n                    LEFT JOIN [|PREFIX|]order_status s ON (s.statusid=o.ordstatus)\n                    LEFT JOIN [|PREFIX|]users us ON us.`pk_userid` = o.orderowner \n                WHERE\n                    o.ordstatus > 0 \n                    AND o.orddate >= '" . $from_stamp . "'\n                    AND o.orddate <= '" . $to_stamp . "' {$cursortfield}   \n                ORDER BY " . $sortField . " " . $sortOrder;
             $mainQuery .= $GLOBALS['ISC_CLASS_DB']->AddLimit($start, $per_page);
             $result = $GLOBALS['ISC_CLASS_DB']->Query($mainQuery);
             if ($GLOBALS['ISC_CLASS_DB']->CountResult($result) > 0) {
                 while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
                     $GLOBALS['OrderId'] = $row['orderid'];
                     $GLOBALS['CustomerId'] = $row['ordcustid'];
                     $GLOBALS['OrderId1'] = $row['orderid'];
                     $GLOBALS['Customer'] = isc_html_escape($row['custname']);
                     $GLOBALS['Date'] = isc_date(GetConfig('DisplayDateFormat'), $row['orddate']);
                     $GLOBALS['OrderStatusOptions'] = $this->GetOrderStatusOptions($row['ordstatus']);
                     $GLOBALS['Total'] = FormatPriceInCurrency($row['ordtotalamount'], $row['orddefaultcurrencyid'], null, true);
                     $GLOBALS['TrackingNo'] = isc_html_escape($row['ordtrackingno']);
                     $GLOBALS['username'] = isc_html_escape($row['username']);
                     switch ($row['requeststatus']) {
                         case 0:
                             $orderreview = GetLang('OviewRequestNo');
                             break;
                         case 1:
                             $orderreview = GetLang('OviewRequestYes');
                             break;
                         case 2:
                             $orderreview = GetLang('OviewRequestSure');
                             break;
                         default:
                             $orderreview = GetLang('OviewRequestNo');
                             break;
                     }
                     $GLOBALS['Review'] = $orderreview;
                     //Show payment status blow order status
                     $GLOBALS['PaymentStatus'] = '';
                     $GLOBALS['HidePaymentStatus'] = 'display:none;';
                     $GLOBALS['PaymentStatusColor'] = '';
                     if ($row['ordpaymentstatus'] != '') {
                         $GLOBALS['HidePaymentStatus'] = '';
                         $GLOBALS['PaymentStatusColor'] = '';
                         switch ($row['ordpaymentstatus']) {
                             case 'authorized':
                                 $GLOBALS['PaymentStatusColor'] = 'PaymentAuthorized';
                                 break;
                             case 'captured':
                                 $GLOBALS['PaymentStatus'] = GetLang('Payment') . " " . ucfirst($row['ordpaymentstatus']);
                                 $GLOBALS['PaymentStatusColor'] = 'PaymentCaptured';
                                 break;
                             case 'refunded':
                             case 'partially refunded':
                             case 'voided':
                                 $GLOBALS['PaymentStatus'] = GetLang('Payment') . " " . ucwords($row['ordpaymentstatus']);
                                 $GLOBALS['PaymentStatusColor'] = 'PaymentRefunded';
                                 break;
                         }
                     }
                     // If the allow payment delayed capture, show the link to Delayed capture
                     $GLOBALS['DelayedCaptureLink'] = '';
                     $GLOBALS['VoidLink'] = '';
                     $GLOBALS['RefundLink'] = '';
                     $transactionId = trim($row['ordpayproviderid']);
                     //if orginal transaction id exist and payment provider is currently enabled
                     if ($transactionId != '' && GetModuleById('checkout', $provider, $row['orderpaymentmodule']) && $provider->IsEnabled() && !gzte11(ISC_HUGEPRINT)) {
                         //if the payment module allow delayed capture and the current payment status is authorized
                         //display delay capture option
                         if (method_exists($provider, "DelayedCapture") && $row['ordpaymentstatus'] == 'authorized') {
                             $GLOBALS['DelayedCaptureLink'] = '<option value="delayedCapture">' . GetLang('CaptureFunds') . '</option>';
                             $GLOBALS['PaymentStatus'] .= '<a onclick="Order.DelayedCapture(' . $row['orderid'] . '); return false;" href="#">' . GetLang('CaptureFunds') . '</a>';
                         }
                         //if the payment module allow void transaction and the current payment status is authorized
                         //display void option
                         if (method_exists($provider, "DoVoid") && $row['ordpaymentstatus'] == 'authorized') {
                             $GLOBALS['VoidLink'] = '<option value="voidTransaction">' . GetLang('VoidTransaction') . '</option>';
                         }
                         //if the payment module allow refund and the current payment status is authorized
                         //display refund option
                         if (method_exists($provider, "DoRefund") && ($row['ordpaymentstatus'] == 'captured' || $row['ordpaymentstatus'] == 'partially refunded')) {
                             $GLOBALS['RefundLink'] = '<option value="refundOrder">' . GetLang('Refund') . '</option>';
                         }
                     }
                     $GLOBALS["OrderStatusText"] = GetOrderStatusById($row['ordstatus']);
                     $GLOBALS['OrderStatusId'] = $row['ordstatus'];
                     $CustomerLink = '';
                     $CustomerId = $row['ordcustid'];
                     $custname = isc_html_escape($row['custname']);
                     if (trim($row['ordcustid']) != '0') {
                         $GLOBALS['CustomerLink'] = "<a href='index.php?ToDo=viewCustomers&amp;idFrom={$CustomerId}&idTo={$CustomerId}' target='_blank'>" . $custname . "</a>";
                     } else {
                         $GLOBALS['CustomerLink'] = $row['ordbillfirstname'] . ' ' . $row['ordbilllastname'];
                     }
                     $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("sales.manage.row");
                     $GLOBALS['OrderGrid'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate(true);
                     $GLOBALS['Quickview'] = "\n                        <tr id=\"trQ{$OrderId}\" style=\"display:none\">\n                            <td></td>\n                            <td colspan=\"12\" id=\"tdQ{$OrderId}\" class=\"QuickView\"></td>\n                        </tr> ";
                 }
             }
         } else {
             $GLOBALS['OrderGrid'] .= sprintf("\n                <tr class=\"GridRow\" onmouseover=\"this.className='GridRowOver';\" onmouseout=\"this.className='GridRow';\">\n                    <td nowrap height=\"22\" colspan=\"5\">\n                        <em>%s</em>\n                    </td>\n                </tr>\n            ", GetLang('StatsNoProducts'));
         }
         $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("sales.manage.grid");
         $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate();
     }
 }
 /**
  * Load and return a listing of the recent orders placed on this store.
  * Orders are loaded for a specific status if one is passed in via the GET
  * or via a cookie.
  *
  * @return string The recent list of orders HTML.
  */
 public function LoadRecentOrders()
 {
     // Do we have permission to view this widget?
     if (!$this->auth->HasPermission(AUTH_Manage_Orders)) {
         return false;
     }
     // If we don't have a status coming in via the URL, use the default
     if (!isset($_GET['status'])) {
         // Maybe it's set in a cookie? Use that
         if (isset($_COOKIE['DashboardRecentOrdersStatus'])) {
             $status = $_COOKIE['DashboardRecentOrdersStatus'];
         } else {
             $status = 'recent';
         }
     } else {
         $status = $_GET['status'];
     }
     $orderWhere = '1=1';
     $statusIn = array();
     // Determine which statuses we'll be showing orders for. Will be used in the query.
     switch ($status) {
         case 'pending':
             $statusIn = array(ORDER_STATUS_PENDING, ORDER_STATUS_PARTIALLY_SHIPPED, ORDER_STATUS_AWAITING_PAYMENT, ORDER_STATUS_AWAITING_SHIPMENT, ORDER_STATUS_AWAITING_FULFILLMENT, ORDER_STATUS_AWAITING_PICKUP);
             break;
         case 'completed':
             $statusIn = array(ORDER_STATUS_SHIPPED, ORDER_STATUS_COMPLETED);
             break;
         case 'refunded':
             $statusIn = array(ORDER_STATUS_REFUNDED, ORDER_STATUS_CANCELLED);
             break;
         default:
             $status = 'recent';
     }
     // If they've just changed statuses, store it in a cookie
     if (isset($_GET['status'])) {
         isc_setcookie('DashboardRecentOrdersStatus', $status);
     }
     if (!empty($statusIn)) {
         $orderWhere .= " AND ordstatus IN (" . implode(',', $statusIn) . ")";
     }
     // Only get orders for this vendor
     if ($this->auth->GetVendorId()) {
         $orderWhere .= " AND ordvendorid='" . $this->auth->GetVendorId() . "'";
     }
     // Fetch orders
     $query = "\n\t\t\tSELECT orderid, ordbillfirstname, ordbilllastname, ordstatus, orddate, ordtotalamount\n\t\t\tFROM [|PREFIX|]orders\n\t\t\tWHERE " . $orderWhere . " AND ordstatus != 0\n\t\t\tORDER BY orddate DESC\n\t\t";
     $query .= $this->db->AddLimit(0, 10);
     $result = $this->db->Query($query);
     $orderList = '';
     while ($order = $this->db->Fetch($result)) {
         $this->template->Assign('OrderId', $order['orderid']);
         $this->template->Assign('OrderStatusId', $order['ordstatus']);
         $this->template->Assign('OrderStatus', GetOrderStatusById($order['ordstatus']));
         $customerName = $order['ordbillfirstname'] . ' ' . $order['ordbilllastname'];
         if (!trim($customerName)) {
             $customerName = GetLang('Guest');
         }
         $this->template->Assign('CustomerName', isc_html_escape($customerName));
         $orderSummary = sprintf(GetLang('RecentOrdersDateAndTotal'), NiceDate($order['orddate'], true), FormatPrice($order['ordtotalamount']));
         $this->template->Assign('OrderSummary', $orderSummary);
         $orderList .= $this->template->GetSnippet('DashboardRecentOrdersItem');
     }
     if (!$orderList) {
         $orderList = $this->template->GetSnippet('DashboardRecentOrdersNone');
     }
     return $orderList;
 }
Beispiel #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;
	}
		/**
		 * Handle the status change of an order. This is used to send google notifications so that ISC and
		 * the Google control panel keep the order state at the same stage. It is also so that you can
		 * approve, ship etc orders from the ISC control panel.
		 *
		 * @param integer $orderid The ISC order id whose status is changing
		 * @param integer $oldstatus The status id the order is changing from. Order status are defined in lib/init.php.
		 * @param integer $newstatus The new status id the order is changing to.
		 * @param mixed $data Extra data associated with the status change
		 *
		 * @return void
		 **/
		public function HandleStatusChange($orderid, $oldstatus, $newstatus, $data = '')
		{
			$request_result = '';

			$query = "
				SELECT *
				FROM [|PREFIX|]orders
				WHERE orderpaymentmodule = '".$GLOBALS['ISC_CLASS_DB']->Quote($this->GetId())."'
				AND orderid = '".$GLOBALS['ISC_CLASS_DB']->Quote($orderid)."'
				AND deleted = 0
			";
			$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
			$order = $GLOBALS['ISC_CLASS_DB']->Fetch($result);

			$statusActions = array(
				'cancel' => array(
					ORDER_STATUS_CANCELLED,
					),
				'refund' => array(
					ORDER_STATUS_REFUNDED,
					),
				'charge' => array(
					ORDER_STATUS_AWAITING_FULFILLMENT,
					ORDER_STATUS_AWAITING_SHIPMENT,
					ORDER_STATUS_AWAITING_PICKUP,
					ORDER_STATUS_SHIPPED,
					ORDER_STATUS_COMPLETED,
					ORDER_STATUS_PARTIALLY_SHIPPED,
					),
				'ship' => array(
					ORDER_STATUS_SHIPPED,
					ORDER_STATUS_COMPLETED,
					),
			);

			if(in_array($newstatus, $statusActions['cancel'])){
				$request_result = $this->request->SendCancelOrder($order['ordpayproviderid'], GetLang('GoogleCheckoutOrderCancelledByVendor'), '');
			}

			if(in_array($newstatus, $statusActions['refund'])){
				$request_result = $this->request->SendRefundOrder($order['ordpayproviderid'], $data, GetLang('GoogleCheckoutOrderRefundedByVendor'), 'def');
			}

			if(in_array($newstatus, $statusActions['charge']) && $oldstatus == ORDER_STATUS_AWAITING_PAYMENT){
				$request_result = $this->request->SendChargeOrder($order['ordpayproviderid'], 0);
			}

			if(in_array($newstatus, $statusActions['ship'])) {
				$request_result = $this->request->SendDeliverOrder($order['ordpayproviderid']);
			}

			$GLOBALS['ISC_CLASS_LOG']->LogSystemDebug(array('payment', $this->GetName()), "Status change for #$orderid from ".GetOrderStatusById($oldstatus)." to ".GetOrderStatusById($newstatus));
		}
Beispiel #14
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;
 }