コード例 #1
0
ファイル: Usps.php プロジェクト: buttasg/cowgirlk
 /**
  * Clean service name from unsupported strings and characters
  *
  * @param  string $name
  * @return string
  */
 protected function _filterServiceName($name)
 {
     ShopgateLogger::getInstance()->log("# " . __METHOD__, ShopgateLogger::LOGTYPE_DEBUG);
     $name = (string) preg_replace(array('~<[^/!][^>]+>.*</[^>]+>~sU', '~\\<!--.*--\\>~isU', '~<[^>]+>~is'), '', html_entity_decode($name));
     $name = str_replace('*', '', $name);
     return $name;
 }
コード例 #2
0
 public function getFields()
 {
     if (parent::validateFields()) {
         ShopgateLogger::getInstance()->log('Validation for shopgate database fields invalid', ShopgateLogger::LOGTYPE_ERROR);
     }
     $fields = array();
     $fields['id_shopgate_customer'] = (int) $this->id_shopgate_customer;
     $fields['id_customer'] = (int) $this->id_customer;
     $fields['customer_token'] = $this->customer_token;
     $fields['date_add'] = $this->date_add;
     return $fields;
 }
コード例 #3
0
ファイル: Router.php プロジェクト: buttasg/cowgirlk
 /**
  * @return bool|false|Mage_Core_Model_Abstract
  */
 public function getMethodModel()
 {
     $model = $this->getModelByPaymentMethod();
     if (!$model) {
         $model = $this->_checkAllPossibleModels();
     }
     if (!$model) {
         $debug = $this->_getHelper()->__('No class found for payment method: %s', $this->getPaymentMethod());
         ShopgateLogger::getInstance()->log($debug, ShopgateLogger::LOGTYPE_DEBUG);
     }
     return $model;
 }
コード例 #4
0
ファイル: Abstract.php プロジェクト: buttasg/cowgirlk
 /**
  * Predefined Getter for method
  * ready to be rewritten in subclasses
  */
 public function getMethod()
 {
     ShopgateLogger::getInstance()->log("# " . __METHOD__, ShopgateLogger::LOGTYPE_DEBUG);
     if (is_null($this->_method) && is_object($this->_order)) {
         $this->_method = $this->_fetchMethod($this->_order);
     } else {
         if (is_null($this->_method) && is_null($this->_order)) {
             Mage::logException(new Exception('Error: model not initialized properly'));
         }
     }
     ShopgateLogger::getInstance()->log("  Mapped shipping method is: '" . $this->_method . "'", ShopgateLogger::LOGTYPE_DEBUG);
     return $this->_method;
 }
コード例 #5
0
ファイル: Observer.php プロジェクト: buttasg/cowgirlk
 /**
  * @param Varien_Event_Observer $observer
  * @return bool
  */
 public function sendOrder(Varien_Event_Observer $observer)
 {
     /* @var ShopgateOrder $shopgateOrder */
     /* @var Mage_Sales_Model_Order $magentoOrder */
     $shopgateOrder = $observer->getShopgateOrder();
     $magentoOrder = $observer->getOrder();
     if (class_exists("DreamRobot_Checkout_Model_Observer", false) && !$shopgateOrder->getIsShippingBlocked()) {
         $msg = "Start to send order to DreamRobot\n";
         $msg .= "\tOrderID: {$magentoOrder->getId()}\n";
         $msg .= "\tOrderNumber: {$magentoOrder->getIncrementId()}\n";
         $msg .= "\tShopgateOrderNumber: {$shopgateOrder->getOrderNumber()}\n";
         ShopgateLogger::getInstance()->log($msg, ShopgateLogger::LOGTYPE_REQUEST);
         Mage::getSingleton('checkout/type_onepage')->getCheckout()->setLastOrderId($magentoOrder->getId());
         $c = new DreamRobot_Checkout_Model_Observer();
         $c->getSaleOrder();
     }
     return true;
 }
コード例 #6
0
ファイル: Payone.php プロジェクト: buttasg/cowgirlk
 /**
  * @param Payone_Core_Model_Config $config
  * @param string $methodType
  *
  * @return int
  */
 public function getMethodId($config, $methodType)
 {
     if ($methodType) {
         $methods = $config->getPayment()->getMethodsByType($methodType);
         if (!empty($methods)) {
             /** @var Payone_Core_Model_Config_Payment_Method $method */
             foreach ($methods as $method) {
                 $id = $method->getScope() === 'websites' ? Mage::app()->getWebsite()->getId() : Mage::app()->getStore()->getStoreId();
                 if ($method->getScopeId() === $id) {
                     return $method->getId();
                 }
             }
             $error = $this->__('PayOne: could not match config scope with any of the active methods');
         } else {
             $error = $this->__('PayOne: could not find an enabled config for mapping: %s', $methodType);
         }
     } else {
         $error = $this->__('PayOne: method type not set in the called class');
     }
     ShopgateLogger::getInstance()->log($error, ShopgateLogger::LOGTYPE_ERROR);
     return false;
 }
コード例 #7
0
 /**
  * Unregisters a shopgate connection by storeViewId
  *
  * @return void
  */
 public function ajax_unregisterAction()
 {
     $storeViewId = Mage::app()->getRequest()->getParam('storeviewid');
     $result = Mage::getModel('shopgate/shopgate_connection')->loadByStoreViewId($storeViewId)->unregister();
     $responseData = array();
     $hasErrors = false;
     if (count($result->getErrors())) {
         $hasErrors = true;
         foreach ($result->getErrors() as $msg) {
             $responseData['errors'] = Mage::helper('shopgate')->__($msg);
         }
         ShopgateLogger::getInstance()->log("Unregister OAuth Shop Connection with store View Id \"" . (string) $storeViewId . "\" could not get loaded", ShopgateLogger::LOGTYPE_ERROR);
     }
     if (!$hasErrors) {
         $responseData['success'] = true;
     } else {
         $responseData['success'] = false;
     }
     $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($responseData));
     $this->getResponse()->sendResponse();
     exit;
 }
コード例 #8
0
 /**
  * @param ShopgateOrder $order
  *
  * @return array
  * @throws PrestaShopException
  * @throws ShopgateLibraryException
  */
 public function addOrder(ShopgateOrder $order)
 {
     /**
      * check exits shopgate order
      */
     if (ShopgateOrderPrestashop::loadByOrderNumber($order->getOrderNumber())->status == 1) {
         throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DUPLICATE_ORDER, sprintf('external_order_id: %s', $order->getOrderNumber()), true);
     }
     /** @var CarrierCore $sgCarrier */
     $sgCarrier = new Carrier(Configuration::get('SG_CARRIER_ID'));
     if (version_compare(_PS_VERSION_, '1.5.0', '<') && empty($sgCarrier->name)) {
         $sgCarrier->name = 'shopgate_tmp_carrier';
     }
     if ($order->getShippingType() != ShopgateShipping::DEFAULT_PLUGIN_API_KEY) {
         if ($order->getShippingInfos()->getAmount() > 0) {
             if (version_compare(_PS_VERSION_, '1.5.0', '<')) {
                 ShopgateModObjectModel::updateShippingPrice(pSQL($order->getShippingInfos()->getAmount()));
             } else {
                 $data = array('price' => pSQL($order->getShippingInfos()->getAmount()));
                 $where = 'a.id_carrier = ' . (int) Configuration::get('SG_CARRIER_ID');
                 ObjectModel::updateMultishopTable('Delivery', $data, $where);
             }
             $sgCarrier->is_free = 0;
         } else {
             $sgCarrier->is_free = 1;
         }
     }
     $sgCarrier->update();
     $customerModel = new ShopgateItemsCustomerImportJson($this->getPlugin());
     $paymentModel = new ShopgatePayment($this->getModule());
     $shippingModel = new ShopgateShipping($this->getModule());
     /**
      * read / check customer
      */
     if (!($customerId = Customer::customerExists($order->getMail(), true, false))) {
         /**
          * prepare customer
          */
         $shopgateCustomerItem = new ShopgateCustomer();
         $shopgateCustomerItem->setLastName($order->getInvoiceAddress()->getLastName());
         $shopgateCustomerItem->setFirstName($order->getInvoiceAddress()->getFirstName());
         $shopgateCustomerItem->setGender($order->getInvoiceAddress()->getGender());
         $shopgateCustomerItem->setBirthday($order->getInvoiceAddress()->getBirthday());
         $shopgateCustomerItem->setNewsletterSubscription(Configuration::get('SG_SUBSCRIBE_NEWSLETTER') ? true : false);
         $customerId = $customerModel->registerCustomer($order->getMail(), md5(_COOKIE_KEY_ . time()), $shopgateCustomerItem);
     }
     /** @var CustomerCore $customer */
     $customer = new Customer($customerId);
     /**
      * prepare cart
      */
     if (!$order->getDeliveryAddress()->getPhone()) {
         $order->getDeliveryAddress()->setPhone($order->getPhone());
     }
     if (!$order->getInvoiceAddress()->getPhone()) {
         $order->getInvoiceAddress()->setPhone($order->getPhone());
     }
     $this->getCart()->id_address_delivery = $customerModel->createAddress($order->getDeliveryAddress(), $customer);
     $this->getCart()->id_address_invoice = $customerModel->createAddress($order->getInvoiceAddress(), $customer);
     $this->getCart()->id_customer = $customerId;
     // id_guest is a connection to a ps_guest entry which includes screen width etc.
     // is_guest field only exists in Prestashop 1.4.1.0 and higher
     if (version_compare(_PS_VERSION_, '1.4.1.0', '>=')) {
         $this->getCart()->id_guest = $customer->is_guest;
     }
     $this->getCart()->secure_key = $customer->secure_key;
     $this->getCart()->id_carrier = $shippingModel->getCarrierIdByApiOrder($order);
     $shopgateCustomFieldsHelper = new ShopgateCustomFieldsHelper();
     $shopgateCustomFieldsHelper->saveCustomFields($this->getCart(), $order->getCustomFields());
     $this->getCart()->add();
     /**
      * add cart items
      */
     $canCreateOrder = true;
     $errorMessages = array();
     foreach ($order->getItems() as $item) {
         list($productId, $attributeId) = ShopgateHelper::getProductIdentifiers($item);
         if ($productId == 0) {
             continue;
         }
         $updateCart = $this->getCart()->updateQty($item->getQuantity(), $productId, $attributeId, false, 'up', $this->getCart()->id_address_delivery);
         if ($updateCart !== true) {
             $canCreateOrder = false;
             $errorMessages[] = array('product_id' => $productId, 'attribute_id' => $attributeId, 'quantity' => $item->getQuantity(), 'result' => $updateCart, 'reason' => $updateCart == -1 ? 'minimum quantity not reached' : '');
         }
     }
     /**
      * coupons
      */
     foreach ($order->getExternalCoupons() as $coupon) {
         /** @var CartRuleCore $cartRule */
         $cartRule = new CartRule(CartRule::getIdByCode($coupon->getCode()));
         if (Validate::isLoadedObject($cartRule)) {
             $this->getCart()->addCartRule($cartRule->id);
             $this->getCart()->save();
         }
     }
     if (version_compare(_PS_VERSION_, '1.5.0.0', '>=')) {
         /**
          * this field is not available in version 1.4.x.x
          * set delivery option
          */
         $delivery_option = array($this->getCart()->id_address_delivery => $shippingModel->getCarrierIdByApiOrder($order) . ',');
         $this->getCart()->setDeliveryOption($delivery_option);
     }
     /**
      * store shopgate order
      */
     $shopgateOrderItem = new ShopgateOrderPrestashop();
     $shopgateOrderItem->fillFromOrder($this->getCart(), $order, $this->getPlugin()->getShopgateConfig()->getShopNumber());
     if (version_compare(_PS_VERSION_, '1.6.0.0', '<')) {
         $shopgateOrderItem->add();
     }
     /**
      * create order
      */
     if ($canCreateOrder) {
         /**
          * get first item from order stats
          */
         $this->getCart()->save();
         $idOrderState = reset($paymentModel->getOrderStateId($order));
         $validateOder = $this->getModule()->validateOrder($this->getCart()->id, $idOrderState, $this->getCart()->getOrderTotal(true, defined('Cart::BOTH') ? Cart::BOTH : 3), $paymentModel->getPaymentTitleByKey($order->getPaymentMethod()), null, array(), null, false, $this->getCart()->secure_key);
         if (version_compare(_PS_VERSION_, '1.5.0.0', '<') && (int) $this->getModule()->currentOrder > 0 && $order->getShippingType() != ShopgateShipping::DEFAULT_PLUGIN_API_KEY && $order->getShippingInfos()->getAmount() > 0) {
             ShopgateLogger::log('PS < 1.5.0.0: update shipping and payment cost', ShopgateLogger::LOGTYPE_DEBUG);
             // in versions below 1.5.0.0 the shipping and payment costs must be updated after the order was imported
             /** @var OrderCore $updateShopgateOrder */
             $updateShopgateOrder = new Order($this->getModule()->currentOrder);
             $updateShopgateOrder->total_shipping = $order->getAmountShipping() + $order->getAmountShopPayment();
             $updateShopgateOrder->total_paid += $order->getAmountShipping() + $order->getAmountShopPayment();
             $updateShopgateOrder->total_paid_real += $order->getAmountShipping() + $order->getAmountShopPayment();
             $updateShopgateOrder->update();
         }
         /**
          * update shopgate order
          */
         if ($validateOder) {
             $shopgateOrderItem->id_order = $this->getModule()->currentOrder;
             $shopgateOrderItem->status = 1;
             $shopgateOrderItem->save();
             return array('external_order_id' => $shopgateOrderItem->id_order, 'external_order_number' => $shopgateOrderItem->id_order);
         }
     }
     $shopgateOrderItem->delete();
     throw new ShopgateLibraryException(ShopgateLibraryException::UNKNOWN_ERROR_CODE, 'Unable to create order:' . print_r($errorMessages, true), true);
 }
コード例 #9
0
ファイル: core.php プロジェクト: buttasg/cowgirlk
 protected function iterateObjectList($list = null)
 {
     $newList = array();
     if (!empty($list) && is_array($list)) {
         foreach ($list as $object) {
             if (!$object instanceof ShopgateContainer) {
                 ShopgateLogger::getInstance()->log('Encountered unknown type in what is supposed to be a list of ShopgateContainer objects: ' . var_export($object, true));
                 continue;
             }
             $object->accept($this);
             $newList[] = $this->array;
         }
     }
     return $newList;
 }
コード例 #10
0
ファイル: Sales.php プロジェクト: buttasg/cowgirlk
 /**
  * Returns all valid shipping methods for current quote.
  * (based on provided delivery address)
  *
  * @param Mage_Checkout_Model_Cart $mageCart
  * @return array
  */
 public function getShippingMethods($mageCart)
 {
     $methods = array();
     /** @var Mage_Sales_Model_Quote_Address $shippingAddress */
     $shippingAddress = $mageCart->getQuote()->getShippingAddress();
     $shippingAddress->collectTotals();
     $shippingAddress->collectShippingRates();
     $calc = Mage::getSingleton('tax/calculation');
     $rates = $calc->getRatesForAllProductTaxClasses($calc->getRateOriginRequest());
     $taxClassIdShipping = Mage::helper('tax')->getShippingTaxClass(Mage::helper("shopgate/config")->getConfig()->getStoreViewId());
     $taxRateShipping = $taxClassIdShipping ? $rates[$taxClassIdShipping] : $taxClassIdShipping;
     /** @var Mage_Sales_Model_Quote_Address_Rate $_rate */
     foreach ($shippingAddress->getShippingRatesCollection() as $_rate) {
         if ($_rate instanceof Mage_Shipping_Model_Rate_Result_Error || strpos($_rate->getCode(), 'error') !== false || $_rate->getCarrierInstance() == false) {
             /* skip errors so they dont get processed as valid shipping rates without any cost */
             ShopgateLogger::getInstance()->log("Skipping Shipping Rate because of Error Type: '" . $_rate->getCode() . "'", ShopgateLogger::LOGTYPE_DEBUG);
             continue;
         }
         $shippingAddress->setShippingMethod($_rate->getCode());
         $shippingAddress->setCollectShippingRates(true);
         $shippingAddress->collectTotals();
         $method = new ShopgateShippingMethod();
         $method->setId($_rate->getCode());
         $method->setTitle($_rate->getMethodTitle());
         $method->setShippingGroup($_rate->getCarrier());
         $method->setDescription($_rate->getMethodDescription() ? $_rate->getMethodDescription() : '');
         $method->setSortOrder($_rate->getCarrierInstance()->getSortOrder());
         $method->setAmount($shippingAddress->getBaseShippingAmount());
         $method->setAmountWithTax($shippingAddress->getBaseShippingInclTax());
         $method->setTaxClass($taxClassIdShipping);
         $method->setTaxPercent(number_format($taxRateShipping, 2));
         $methods[] = $method;
     }
     return $methods;
 }
コード例 #11
0
ファイル: Abstract.php プロジェクト: buttasg/cowgirlk
 /**
  * Returns the payment model of a class,
  * else falls back to mobilePayment
  *
  * @return mixed
  */
 public function getPaymentModel()
 {
     $payment = $this->getConstant('PAYMENT_MODEL');
     $model = Mage::getModel($payment);
     if (!$model) {
         $debug = $this->_getHelper()->__('Could not find PAYMENT_MODEL %s in class %s', $payment, get_class($this));
         ShopgateLogger::getInstance()->log($debug, ShopgateLogger::LOGTYPE_DEBUG);
         $model = Mage::getModel(self::PAYMENT_MODEL);
     }
     return $model;
 }
コード例 #12
0
ファイル: Redirect.php プロジェクト: buttasg/cowgirlk
 /**
  * Redirect with 301
  */
 public function redirectWithCode()
 {
     try {
         // no redirection in admin
         if (Mage::app()->getStore()->isAdmin()) {
             Mage::getSingleton('core/session')->setData('shopgate_header', '');
             return;
         }
         // isAjax is not available on Magento < 1.5 >> no ajax-check
         if (method_exists(Mage::app()->getRequest(), 'isAjax') && Mage::app()->getRequest()->isAjax()) {
             Mage::getSingleton('core/session')->setData('shopgate_header', '');
             return;
         }
         if (!$this->_config->isValidConfig()) {
             Mage::getSingleton('core/session')->setData('shopgate_header', '');
             return;
         }
         if (!Mage::getStoreConfig(Shopgate_Framework_Model_Config::XML_PATH_SHOPGATE_ACTIVE, $this->_config->getStoreViewId())) {
             Mage::getSingleton('core/session')->setData('shopgate_header', '');
             return;
         }
         $jsHeader = $this->_getJsHeader();
         Mage::getSingleton('core/session')->setData('shopgate_header', $jsHeader);
     } catch (Exception $e) {
         Mage::getSingleton('core/session')->setData('shopgate_header', '');
         ShopgateLogger::getInstance()->log('error in mobile redirector: ' . $e->getMessage());
     }
 }
コード例 #13
0
ファイル: Connection.php プロジェクト: buttasg/cowgirlk
 /**
  * Removes all through oauth registration saved config entries for the current model
  *
  * @return boolean
  */
 public function unregister()
 {
     ShopgateLogger::getInstance()->log("Unregister OAuth Shop Connection with shopnumber# " . $this->getShopnumber(), ShopgateLogger::LOGTYPE_DEBUG);
     $result = Mage::getModel('varien/object');
     $deletedKeys = Mage::getModel('varien/object');
     $errors = array();
     foreach ($this->_getRelatedConfigDataEntries() as $config) {
         $deleted = $config->delete();
         if (!$deleted instanceof Mage_Core_Model_Config_Data) {
             $errors[] = "Could not delete Config Field for '" . $config->getPath() . "' in scope (" . $config->getScope() . "," . $config->getScopeId() . ")";
             continue;
         }
         $deletedKeys->setData($config->getPath(), $deleted);
     }
     $result->setData('erros', $errors);
     $result->setData('deleted_keys', $deletedKeys);
     $cacheResult = Mage::app()->getCacheInstance()->clean(Mage_Core_Model_Config::CACHE_TAG);
     ShopgateLogger::getInstance()->log(' Config cache cleared with result: ' . ($cacheResult ? '[OK]' : '[ERROR]'), ShopgateLogger::LOGTYPE_DEBUG);
     $this->_notifyBackendAboutConnectionDisconnect();
     return $result;
 }
コード例 #14
0
 /**
  * @param string    $message
  * @param int       $errorcount
  */
 public function setShippingComplete(&$message, &$errorcount)
 {
     $log = ShopgateLogger::getInstance();
     $shopgateConfig = new ShopgateConfigPrestashop();
     $shopgateBuilder = new ShopgateBuilder($shopgateConfig);
     $shopgateMerchantApi = $shopgateBuilder->buildMerchantApi();
     try {
         /** @var OrderCore $orderCore */
         $orderCore = new Order($this->id_order);
         $trackingCode = $orderCore->shipping_number;
         if (Tools::strlen($trackingCode) > 32) {
             $log->log("TrackingCode '" . $trackingCode . "' is too long", ShopgateLogger::LOGTYPE_DEBUG);
             $trackingCode = '';
         }
         $shopgateMerchantApi->addOrderDeliveryNote($this->order_number, ShopgateDeliveryNote::OTHER, $trackingCode, true);
         $message .= "Setting \"shipping complete\" for shopgate-order #{$this->order_number} successfully completed\n";
         $this->is_sent_to_shopgate = 1;
         $this->tracking_number = $trackingCode;
         $this->update();
     } catch (ShopgateMerchantApiException $e) {
         if ($e->getCode() == ShopgateMerchantApiException::ORDER_SHIPPING_STATUS_ALREADY_COMPLETED) {
             $log->log("Order with order-number #{$this->order_number} already marked as complete at shopgate.", ShopgateLogger::LOGTYPE_DEBUG);
             $e = null;
             $this->is_sent_to_shopgate = 1;
             $this->update();
         }
     } catch (Exception $e) {
         $errorcount++;
         $message .= "Error while setting \"shipping complete\" for shopgate-order #{$this->order_number}\n";
     }
 }
コード例 #15
0
ファイル: Observer.php プロジェクト: buttasg/cowgirlk
 /**
  * @param $items
  * @param $id
  * @return bool
  */
 protected function findItemByOriginal($items, $id)
 {
     if (empty($id) || empty($items)) {
         return false;
     }
     foreach ($items as $item) {
         $json_info = $item->getInternalOrderInfo();
         try {
             $object = Mage::helper('shopgate')->getConfig()->jsonDecode($json_info);
         } catch (Exception $e) {
             ShopgateLogger::getInstance()->log("Product ID (#{$id}) Json parse error! Message: {$e->getCode()} - {$e->getMessage()}", ShopgateLogger::LOGTYPE_ERROR);
             return false;
         }
         if ($object->product_id == $id) {
             return $item;
         }
     }
     return false;
 }
コード例 #16
0
ファイル: Plugin.php プロジェクト: buttasg/cowgirlk
 /**
  * Performs the necessary queries to add an order to the shop system's database.
  *
  * @see http://wiki.shopgate.com/Merchant_API_get_orders#API_Response
  * @see http://wiki.shopgate.com/Shopgate_Plugin_API_add_order#API_Response
  *
  * @param ShopgateOrder $order The ShopgateOrder object to be added to the shop system's database.
  *
  * @return array(
  *                             <ul>
  *                             <li>'external_order_id' => <i>string</i>, # the ID of the order in your shop system's database</li>
  *                             <li>'external_order_number' => <i>string</i> # the number of the order in your shop system</li>
  *                             </ul>)
  * @throws ShopgateLibraryException if an error occurs.
  */
 public function addOrder(ShopgateOrder $order)
 {
     /* @var Mage_Sales_Model_Order $magentoOrder */
     /* @var Mage_Sales_Model_Quote $quote */
     /* @var Mage_Sales_Model_Service_Quote $service */
     try {
         $this->log("## Start to add new Order", ShopgateLogger::LOGTYPE_DEBUG);
         $this->log("## Order-Number: {$order->getOrderNumber()}", ShopgateLogger::LOGTYPE_DEBUG);
         $this->log("# Begin database Transaction", ShopgateLogger::LOGTYPE_DEBUG);
         Mage::getModel("sales/order")->getResource()->beginTransaction();
         $this->log("#> Succesfull created database Transaction", ShopgateLogger::LOGTYPE_DEBUG);
         $this->_errorOnInvalidCoupon = true;
         $this->log("# Try to load old shopgate order to check for duplicate", ShopgateLogger::LOGTYPE_DEBUG);
         /** @var Shopgate_Framework_Model_Shopgate_Order $magentoShopgateOrder */
         $magentoShopgateOrder = Mage::getModel("shopgate/shopgate_order")->load($order->getOrderNumber(), "shopgate_order_number");
         if ($magentoShopgateOrder->getId() !== null) {
             $this->log("# Duplicate Order", ShopgateLogger::LOGTYPE_DEBUG);
             $orderId = 'unset';
             if ($magentoShopgateOrder->getOrderId()) {
                 $orderId = $magentoShopgateOrder->getOrderId();
             }
             throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DUPLICATE_ORDER, 'orderId: ' . $orderId, true);
         }
         Mage::dispatchEvent('shopgate_add_order_before', array('shopgate_order' => $order));
         $this->log("# Add shopgate order to Session", ShopgateLogger::LOGTYPE_DEBUG);
         Mage::getSingleton("core/session")->setData("shopgate_order", $order);
         $this->log("# Create quote for order", ShopgateLogger::LOGTYPE_DEBUG);
         $quote = Mage::getModel('sales/quote')->setStoreId($this->_getConfig()->getStoreViewId());
         $quote->getBillingAddress()->setCartFixedRules(array());
         $quote->getShippingAddress()->setCartFixedRules(array());
         $quote = $this->executeLoaders($this->_getCreateOrderQuoteLoaders(), $quote, $order);
         $quote->setInventoryProcessed(false);
         $quote->setTotalsCollectedFlag(false);
         // Shipping rate is set at Shopgate_Framework_Model_Carrier_Fix
         $quote->getShippingAddress()->setCollectShippingRates(true);
         ShopgateLogger::getInstance()->log('setCollectShippingRates ok', ShopgateLogger::LOGTYPE_DEBUG);
         if (Mage::getConfig()->getModuleConfig('FireGento_MageSetup')->is('active', 'true') || Mage::getConfig()->getModuleConfig('FireGento_GermanSetup')->is('active', 'true')) {
             $session = Mage::getSingleton('checkout/session');
             $session->replaceQuote($quote);
         }
         $quote->collectTotals();
         $rates = $quote->getShippingAddress()->collectShippingRates()->getGroupedAllShippingRates();
         $title = null;
         $method = 'shopgate_fix';
         if (array_key_exists('shopgate', $rates)) {
             /** @var Mage_Sales_Model_Quote_Address_Rate $addressRate */
             $addressRate = $rates['shopgate'][0];
             foreach ($rates as $_key) {
                 foreach ($_key as $rate) {
                     /** @var Mage_Sales_Model_Quote_Address_Rate $rate */
                     if ($rate->getCode() == $addressRate->getMethodTitle()) {
                         $method = $addressRate->getMethodTitle();
                         $addressRate->setCarrierTitle($rate->getCarrierTitle());
                         $addressRate->setMethodTitle($rate->getMethodTitle());
                         $addressRate->save();
                         $title = $addressRate->getCarrierTitle() . " - " . $addressRate->getMethodTitle();
                         break;
                     }
                 }
             }
         }
         $title = $title ? $title : $order->getShippingInfos()->getDisplayName();
         $quote->getShippingAddress()->setShippingDescription($title);
         $quote->save();
         // due to compatibility with 3rd party modules which fetches the quote from the session (like phoenix_cod, SUE)
         // needed before $service->submitAll() is called
         Mage::getSingleton('checkout/session')->replaceQuote($quote);
         $magentoOrder = $this->_getFactory()->createNewOrder($quote);
         $this->log("# Create order from quote", ShopgateLogger::LOGTYPE_DEBUG);
         $this->log("# Modify order", ShopgateLogger::LOGTYPE_DEBUG);
         $magentoOrder->setCanEdit(false);
         $magentoOrder->setCanShipPartially(true);
         $magentoOrder->setCanShipPartiallyItem(true);
         $magentoOrder = $this->executeLoaders($this->_getCreateOrderLoaders(), $magentoOrder, $order);
         $magentoOrder->setShippingDescription($title);
         $magentoOrder->setShippingMethod($method);
         //todo: move this out, intentionally here after executeLoaders?
         if ($magentoOrder->getTotalDue() > 0 && $order->getPaymentMethod() == ShopgateOrder::PP_WSPP_CC) {
             if (!$magentoOrder->getPayment()->getIsTransactionPending()) {
                 $magentoOrder->setTotalPaid($magentoOrder->getGrandTotal());
                 $magentoOrder->setBaseTotalPaid($magentoOrder->getBaseGrandTotal());
                 $magentoOrder->setTotalDue(0);
                 $magentoOrder->setBaseTotalDue(0);
             }
         }
         $magentoOrder->save();
         $this->log("# Commit Transaction", ShopgateLogger::LOGTYPE_DEBUG);
         Mage::getModel("sales/order")->getResource()->commit();
         $this->log("## Order saved successful", ShopgateLogger::LOGTYPE_DEBUG);
         Mage::dispatchEvent('shopgate_add_order_after', array('shopgate_order' => $order, 'order' => $magentoOrder));
         $warnings = array();
         $totalShopgate = $order->getAmountComplete();
         $totalMagento = $magentoOrder->getTotalDue();
         $this->log("\n\t\t\t\t\tTotal Shopgate: {$totalShopgate} {$order->getCurrency()}\n\t\t\t\t\tTotal Magento: {$totalMagento} {$order->getCurrency()}\n\t\t\t\t\t", ShopgateLogger::LOGTYPE_DEBUG);
         $result = array("external_order_id" => $magentoOrder->getId(), "external_order_number" => $magentoOrder->getIncrementId());
         $msg = "";
         if (!$this->_getHelper()->isOrderTotalCorrect($order, $magentoOrder, $msg)) {
             $this->log($msg);
             $warnings[] = array("message" => $msg);
             $result["warnings"] = $warnings;
         }
         $this->_setShopgateOrder($magentoOrder, $order);
     } catch (ShopgateLibraryException $e) {
         Mage::getModel("sales/order")->getResource()->rollback();
         throw $e;
     } catch (Exception $e) {
         Mage::getModel("sales/order")->getResource()->rollback();
         throw new ShopgateLibraryException(ShopgateLibraryException::UNKNOWN_ERROR_CODE, "{$e->getMessage()}\n{$e->getTraceAsString()}", true);
     }
     return $result;
 }
コード例 #17
0
ファイル: shopgate.php プロジェクト: ventsiwad/presta_addons
 private function log($message, $type)
 {
     ShopgateLogger::getInstance()->log($message, $type);
 }
コード例 #18
0
ファイル: Shopgate.php プロジェクト: buttasg/cowgirlk
 /**
  * @return string
  */
 public function getDefaultMethod()
 {
     ShopgateLogger::getInstance()->log("# " . __METHOD__, ShopgateLogger::LOGTYPE_DEBUG);
     return self::DEFAULT_SHIPPING_METHOD;
 }
コード例 #19
0
ファイル: Carrier.php プロジェクト: buttasg/cowgirlk
 /**
  * @return mixed
  */
 public function getCarrier()
 {
     ShopgateLogger::getInstance()->log("# " . __FUNCTION__, ShopgateLogger::LOGTYPE_DEBUG);
     ShopgateLogger::getInstance()->log("  Shipping carrier is mapped to: '" . $this->_carrier . "'", ShopgateLogger::LOGTYPE_DEBUG);
     return $this->_carrier;
 }
コード例 #20
0
ファイル: AbstractPayol.php プロジェクト: buttasg/cowgirlk
 /**
  * Checks if we have all the correct data passed
  *
  * @return bool
  */
 public function checkGenericValid()
 {
     $info = $this->getShopgateOrder()->getPaymentInfos();
     if (!isset($info['unique_id'])) {
         $error = $this->_getHelper()->__('Unique ID was missing in paymentInfo of add_order');
         ShopgateLogger::getInstance()->log($error, ShopgateLogger::LOGTYPE_ERROR);
         return false;
     }
     return true;
 }
コード例 #21
0
 /**
  * @param $message
  * @param string $type
  */
 public static function log($message, $type = ShopgateLogger::LOGTYPE_ERROR)
 {
     ShopgateLogger::getInstance()->log($message, $type);
 }
コード例 #22
0
ファイル: Config.php プロジェクト: buttasg/cowgirlk
 /**
  * Clears config cache after saving altered configuration
  */
 protected function _clearCache()
 {
     $result = Mage::app()->getCacheInstance()->clean(Mage_Core_Model_Config::CACHE_TAG);
     ShopgateLogger::getInstance()->log(' Config cache cleared with result: ' . ($result ? '[OK]' : '[ERROR]'), ShopgateLogger::LOGTYPE_DEBUG);
 }
コード例 #23
0
ファイル: Abstract.php プロジェクト: buttasg/cowgirlk
 /**
  * Retrieve PayOne response based on ShopgateOrder
  *
  * @return Payone_Api_Response_Authorization_Approved|Payone_Api_Response_Preauthorization_Approved|false
  */
 protected function _getPayoneResponse()
 {
     $info = $this->getShopgateOrder()->getPaymentInfos();
     if ($info['status'] == 'APPROVED') {
         if ($info['request_type'] === 'authorization') {
             return new Payone_Api_Response_Authorization_Approved();
         } else {
             return new Payone_Api_Response_Preauthorization_Approved();
         }
     }
     $debug = mage::helper('shopgate')->__('Order "status" was not approved');
     ShopgateLogger::getInstance()->log($debug, ShopgateLogger::LOGTYPE_ERROR);
     return false;
 }
コード例 #24
0
ファイル: Mapper.php プロジェクト: buttasg/cowgirlk
 /**
  * Getter for shipping method
  *
  * @return String
  */
 public function getMethod()
 {
     ShopgateLogger::getInstance()->log("# " . __FUNCTION__, ShopgateLogger::LOGTYPE_DEBUG);
     if (is_null($this->_method) && is_object($this->_order) && !is_null($this->_carrier)) {
         $this->_method = $this->_fetchMethod($this->_order);
     } else {
         if (is_null($this->_carrier)) {
             Mage::throwException('Error: no carrier set');
         }
     }
     return $this->_method;
 }
コード例 #25
0
ファイル: Data.php プロジェクト: buttasg/cowgirlk
 /**
  * Sets the correct Shipping Carrier and Method
  * in relation to
  *        ShopgateOrder->{shipping_group} [carrier]
  *        ShopgateOrder->{shipping_info}    [method]
  *
  * @param Mage_Sales_Model_Quote_Address $shippingAddress
  * @param ShopgateCartBase               $order
  */
 public function setShippingMethod(Mage_Sales_Model_Quote_Address $shippingAddress, ShopgateCartBase $order)
 {
     /* dont set shipping method when the order does not contain any shipping information (e.g. checkCart) */
     if (!$order->getShippingGroup()) {
         ShopgateLogger::getInstance()->log("# setShippingMethod skipped, no Shipping information in " . get_class($order) . " available", ShopgateLogger::LOGTYPE_DEBUG);
         return;
     }
     ShopgateLogger::getInstance()->log("# Start of setShippingMethod process", ShopgateLogger::LOGTYPE_DEBUG);
     $mapper = Mage::getModel('shopgate/shopgate_shipping_mapper')->init($shippingAddress, $order);
     $shippingAddress->setShippingMethod($mapper->getCarrier() . '_' . $mapper->getMethod());
     ShopgateLogger::getInstance()->log("  Shipping method set: '" . $shippingAddress->getShippingMethod() . "'", ShopgateLogger::LOGTYPE_DEBUG);
     ShopgateLogger::getInstance()->log("# End of setShippingMethod process", ShopgateLogger::LOGTYPE_DEBUG);
 }
コード例 #26
0
ファイル: Gateway.php プロジェクト: buttasg/cowgirlk
 /**
  * AuthnCIM extension library did not allow us to make this
  * request at the time. Had to inherit from gateway to use
  * protected _runTransaction() method. We are creating a
  * profileId and profilePaymentId base off of transactionId.
  *
  * @return array
  */
 public function createCustomerProfileFromTransactionRequest()
 {
     $result = array();
     $params = array('transId' => $this->getParameter('transId'));
     $response = $this->_runTransaction('createCustomerProfileFromTransactionRequest', $params);
     $errorCode = $response['messages']['message']['code'];
     $errorText = $response['messages']['message']['text'];
     if (isset($response['customerProfileId'], $response['customerPaymentProfileIdList']['numericString'])) {
         $result['customerProfileId'] = $response['customerProfileId'];
         $result['customerPaymentProfileId'] = $response['customerPaymentProfileIdList']['numericString'];
     } elseif (isset($errorText) && strpos($errorText, 'duplicate') !== false) {
         $profileId = preg_replace('/[^0-9]/', '', $errorText);
         /**
          * If we have profileID from error, try to get paymentID based on card's last 4 digits
          */
         if (!empty($profileId)) {
             $this->setParameter('customerProfileId', $profileId);
             $profile = $this->getCustomerProfile();
             $result['customerProfileId'] = $profileId;
             if (isset($profile['profile']['paymentProfiles']) && count($profile['profile']['paymentProfiles']) > 0) {
                 $lastFour = $this->getParameter('cardNumber');
                 //match profile that has the same last 4 card digits
                 foreach ($profile['profile']['paymentProfiles'] as $card) {
                     if (isset($card['payment']['creditCard']) && $lastFour == substr($card['payment']['creditCard']['cardNumber'], -4)) {
                         $result['customerPaymentProfileId'] = $card['customerPaymentProfileId'];
                         break;
                     }
                 }
             } else {
                 /**
                  * They don't have any cards in profile! Remove CIM profile & recurse.
                  * This can fail on refunding if original payment card bound to transaction
                  * does not match the imported card via Shopgate.
                  */
                 $this->deleteCustomerProfile();
                 if ($this->recursion_counter < 2) {
                     $result = $this->createCustomerProfileFromTransactionRequest();
                     $this->recursion_counter++;
                     //not necessary, but protects from recursion leaks
                 }
             }
         } else {
             /**
              * weird gateway error that passed _runTransaction() error throw
              */
             $error = mage::helper('shopgate')->__('Unknown error passed through _runTransaction validation. Code "%s" Message: "%s"', $errorCode, $errorText);
             ShopgateLogger::getInstance()->log($error, ShopgateLogger::LOGTYPE_ERROR);
         }
     }
     return $result;
 }
コード例 #27
0
ファイル: apis.php プロジェクト: buttasg/cowgirlk
 /**
  * Prepares the request and sends it to the configured Shopgate Merchant API.
  *
  * @param mixed[] $parameters The parameters to send.
  * @param mixed[] $curlOptOverride cURL options to override for this request.
  * @return ShopgateMerchantApiResponse The response object.
  * @throws ShopgateLibraryException in case the connection can't be established, the response is invalid or an error occured.
  */
 protected function sendRequest($parameters = array(), $curlOptOverride = array())
 {
     if (!empty($this->shopNumber)) {
         $parameters['shop_number'] = $this->shopNumber;
     }
     $parameters = !empty($parameters) ? array_merge($this->authService->getAuthPostParams(), $parameters) : $this->authService->getAuthPostParams();
     $parameters['trace_id'] = 'spa-' . uniqid();
     $this->log('Sending request to "' . $this->apiUrl . '": ' . ShopgateLogger::getInstance()->cleanParamsForLog($parameters), ShopgateLogger::LOGTYPE_REQUEST);
     // init new auth session and generate cURL options
     $this->authService->startNewSession();
     $curlOpt = $this->getCurlOptArray($curlOptOverride);
     // init cURL connection and send the request
     $curl = curl_init($this->apiUrl);
     curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($parameters));
     curl_setopt_array($curl, $curlOpt);
     $response = curl_exec($curl);
     $info = curl_getinfo($curl);
     curl_close($curl);
     // check the result
     if (!$response) {
         // exception without logging - this might cause spamming your logs and we will know when our API is offline anyways
         throw new ShopgateLibraryException(ShopgateLibraryException::MERCHANT_API_NO_CONNECTION, null, false, false);
     }
     $decodedResponse = $this->jsonDecode($response, true);
     if (empty($decodedResponse)) {
         // exception without logging - this might cause spamming your logs and we will know when our API is offline anyways
         throw new ShopgateLibraryException(ShopgateLibraryException::MERCHANT_API_INVALID_RESPONSE, 'Response: ' . $response, true, false);
     }
     $responseObject = new ShopgateMerchantApiResponse($decodedResponse);
     if ($decodedResponse['error'] != 0) {
         throw new ShopgateMerchantApiException($decodedResponse['error'], $decodedResponse['error_text'], $responseObject);
     }
     return $responseObject;
 }
コード例 #28
0
 /**
  * Issues a PHP deprecated warning and log entry for calls to deprecated ShopgateConfigOld methods.
  *
  * @param string $methodName The name of the called method.
  */
 private static function deprecated($methodName)
 {
     $message = 'Use of ' . $methodName . ' and the whole ShopgateConfigOld class is deprecated.';
     trigger_error($message, E_USER_DEPRECATED);
     ShopgateLogger::getInstance()->log($message);
 }
コード例 #29
0
ファイル: Authncim.php プロジェクト: buttasg/cowgirlk
 /**
  * Pulls a card from the database using last 4 digits
  * or creates on from transaction_id. On most errors,
  * returns false.
  *
  * @return false|ParadoxLabs_TokenBase_Model_Card
  */
 public function getCustomerCard()
 {
     $paymentInfos = $this->getShopgateOrder()->getPaymentInfos();
     $lastFour = substr($paymentInfos['credit_card']['masked_number'], -4);
     $card = $this->_getCardByLastFour($lastFour);
     if (!$card->getData()) {
         /** @var ParadoxLabs_TokenBase_Model_Card $card */
         $card = Mage::getModel('authnetcim/card');
         //for actual authentication
         $card->setAdditional('cc_owner', $paymentInfos['credit_card']['holder']);
         $card->setAdditional('customer_email', $this->getShopgateOrder()->getMail());
         $card->setAdditional('cc_number', $lastFour);
         $card->setAdditional('cc_last4', $lastFour);
         $card->setMethod('authnetcim');
         $card->setCustomer($this->_getCustomer());
         /** @var Shopgate_Framework_Model_Payment_Cc_Authncim_Gateway $gateway */
         $gateway = Mage::getModel('shopgate/payment_cc_authncim_method')->gateway();
         try {
             $response = $gateway->setParameter('transId', $paymentInfos['transaction_id'])->setParameter('cardNumber', 'XXXX' . $lastFour)->createCustomerProfileFromTransactionRequest();
         } catch (Exception $e) {
             ShopgateLogger::getInstance()->log($e->getMessage(), ShopgateLogger::LOGTYPE_DEBUG);
             return false;
         }
         if (!isset($response['customerPaymentProfileId'])) {
             $error = $this->_getHelper()->__('Could not retrieve AuthorizeCIM ProfileID from response');
             ShopgateLogger::getInstance()->log($error, ShopgateLogger::LOGTYPE_DEBUG);
             return false;
         }
         $card->setProfileId($response['customerProfileId']);
         $card->setPaymentId($response['customerPaymentProfileId']);
         $card->save();
     }
     return $card;
 }
コード例 #30
0
ファイル: AuthnAbstract.php プロジェクト: buttasg/cowgirlk
 /**
  * Sets order status
  *
  * @param Mage_Sales_Model_Order $order
  *
  * @return Mage_Sales_Model_Order
  */
 public function setOrderStatus($order)
 {
     $captured = $this->_order->getBaseCurrency()->formatTxt($this->_order->getBaseTotalInvoiced());
     $state = Mage_Sales_Model_Order::STATE_PROCESSING;
     $status = $this->_getHelper()->getStatusFromState($state);
     $message = '';
     switch ($this->_responseCode) {
         case self::RESPONSE_CODE_APPROVED:
             $duePrice = $this->_order->getBaseCurrency()->formatTxt($this->_order->getTotalDue());
             $message = Mage::helper('paypal')->__('Authorized amount of %s.', $duePrice);
             if ($this->_transactionType == self::SHOPGATE_PAYMENT_STATUS_AUTH_CAPTURE) {
                 $message = Mage::helper('sales')->__('Captured amount of %s online.', $captured);
             }
             break;
         case self::RESPONSE_CODE_HELD:
             $state = $this->_getHelper()->getStateForStatus('payment_review');
             $status = $this->_getHelper()->getStatusFromState($state);
             if ($this->_isOrderPendingReview()) {
                 $message = Mage::helper('sales')->__('Capturing amount of %s is pending approval on gateway.', $captured);
             } else {
                 $paymentInfos = $this->getShopgateOrder()->getPaymentInfos();
                 if (!empty($paymentInfos['response_reason_code'])) {
                     $message = $this->_getHelper()->__('[SHOPGATE] Unrecognized response reason: %s', $paymentInfos['response_reason_code']);
                     ShopgateLogger::getInstance()->log($message, ShopgateLogger::LOGTYPE_ERROR);
                 }
             }
             break;
         default:
             $message = $this->_getHelper()->__('[SHOPGATE] Unrecognized response code: %s', $this->_responseCode);
             ShopgateLogger::getInstance()->log($message, ShopgateLogger::LOGTYPE_ERROR);
     }
     $this->_order->setState($state, $status, $message);
     $order->setShopgateStatusSet(true);
     return $order;
 }