diff --git a/README.rst b/Readme.md old mode 100755 new mode 100644 similarity index 100% rename from README.rst rename to Readme.md diff --git a/classes/PayplugLock.php b/classes/PayplugLock.php index fb8eef3..f965c3f 100644 --- a/classes/PayplugLock.php +++ b/classes/PayplugLock.php @@ -1,6 +1,6 @@ 'isInt' - ); - protected $fieldsValidateLang = array( - ); - - public function __construct($id = false, $id_lang = false) - { - parent::__construct($id, $id_lang); +class PayplugLock extends ObjectModel +{ + const MAX_CHECK_TIME = 5; + + public static $definition; + + public $id_payplug_lock; + public $id_cart; + public $date_add; + public $date_upd; + + protected $table = 'payplug_lock'; + protected $identifier = 'id_payplug_lock'; + protected $fieldsRequired = array( + 'id_cart' + ); + protected $fieldsValidate = array( + 'id_cart' => 'isInt' + ); + protected $fieldsValidateLang = array( + ); + + public function __construct($id = false, $id_lang = false) + { + parent::__construct($id, $id_lang); self::$definition = array( - 'table' => $this->table, - 'primary' => $this->identifier, - 'fields' => array( - 'id_cart' => array('type' => self::TYPE_STRING, 'validate' => 'isInt'), - ), - ); - } - - /** - * Check - * @param integer $id_cart Cart identifier - * @return boolean if locked - */ - public static function check($id_cart, $loop_time = 1) - { - $locked = false; - - $time = 0; - - while (($locked = self::exists($id_cart)) && $time < PayplugLock::MAX_CHECK_TIME) - { - if (function_exists('usleep')) - usleep($loop_time * 1000000); - else - self::usleep($loop_time * 1000); - - $time++; - } - } - - /** - * Check if exists - * @param integer $id_cart Cart identifier - * @return boolean If exists - */ - public static function exists($id_cart) - { - $lock = self::getInstanceByCart((int)$id_cart); - - return Validate::isLoadedObject($lock); - } - - /** - * Set instance of PayplugLock - * @param integer $id_cart Cart identifier - * @return \PayplugLock Instance - */ - public static function getInstanceByCart($id_cart) - { - $query = 'SELECT `id_payplug_lock` - FROM `'._DB_PREFIX_.'payplug_lock` - WHERE `id_cart` = '.(int)$id_cart.' '; - - return new PayplugLock((int)Db::getInstance()->getValue($query)); - } - - /** - * Create lock - * @param integer $id_cart Cart identifier - * @return boolean Create successfull - */ - public static function addLock($id_cart) - { - $lock = new PayplugLock(); - $lock->id_cart = (int)$id_cart; - - return $lock->save(); - } - - /** - * Delete lock - * @param integer $id_cart Cart identifier - * @return boolean Delete successfull - */ - public static function deleteLock($id_cart) - { - $lock = self::getInstanceByCart((int)$id_cart); - - return $lock->delete(); - } - - /** - * Sleep time - */ - private static function usleep($seconds) - { - $start = microtime(); - - do - { - // Wait ! - $current = microtime(); - } while (($current - $start) < $seconds); - } + 'table' => $this->table, + 'primary' => $this->identifier, + 'fields' => array( + 'id_cart' => array('type' => self::TYPE_STRING, 'validate' => 'isInt'), + ), + ); + } + + /** + * Check + * @param integer $id_cart Cart identifier + * @return boolean if locked + */ + public static function check($id_cart, $loop_time = 1) + { + $locked = false; + + $time = 0; + + while (($locked = self::exists($id_cart)) && $time < PayplugLock::MAX_CHECK_TIME) { + if (function_exists('usleep')) { + usleep($loop_time * 1000000); + } else { + self::usleep($loop_time * 1000); + } + + $time++; + } + } + + /** + * Check if exists + * @param integer $id_cart Cart identifier + * @return boolean If exists + */ + public static function exists($id_cart) + { + $lock = self::getInstanceByCart((int)$id_cart); + + return Validate::isLoadedObject($lock); + } + + /** + * Set instance of PayplugLock + * @param integer $id_cart Cart identifier + * @return \PayplugLock Instance + */ + public static function getInstanceByCart($id_cart) + { + $query = 'SELECT `id_payplug_lock` + FROM `'._DB_PREFIX_.'payplug_lock` + WHERE `id_cart` = '.(int)$id_cart.' '; + + return new PayplugLock((int)Db::getInstance()->getValue($query)); + } + + /** + * Create lock + * @param integer $id_cart Cart identifier + * @return boolean Create successfull + */ + public static function addLock($id_cart) + { + $lock = new PayplugLock(); + $lock->id_cart = (int)$id_cart; + + return $lock->save(); + } + + /** + * Delete lock + * @param integer $id_cart Cart identifier + * @return boolean Delete successfull + */ + public static function deleteLock($id_cart) + { + $lock = self::getInstanceByCart((int)$id_cart); + + return $lock->delete(); + } + + /** + * Sleep time + */ + private static function usleep($seconds) + { + $start = microtime(); + + do { + // Wait ! + $current = microtime(); + } while (($current - $start) < $seconds); + } } diff --git a/classes/index.php b/classes/index.php index 4f6e5df..0f9074a 100644 --- a/classes/index.php +++ b/classes/index.php @@ -1,6 +1,6 @@ cart; -if (version_compare(_PS_VERSION_, '1.5', '<')) - $result_currency['iso_code'] = Currency::getCurrent()->iso_code; -else -{ - $currency = $cart->id_currency; - $result_currency = Currency::getCurrency($currency); +if (version_compare(_PS_VERSION_, '1.5', '<')) { + $result_currency['iso_code'] = Currency::getCurrent()->iso_code; +} else { + $currency = $cart->id_currency; + $result_currency = Currency::getCurrency($currency); } $supported_currencies = explode(';', Configuration::get('PAYPLUG_MODULE_CURRENCIES')); -if (!in_array($result_currency['iso_code'], $supported_currencies)) - return false; +if (!in_array($result_currency['iso_code'], $supported_currencies)) { + return false; +} /** * Check amount */ $amount = $context->cart->getOrderTotal(true, Cart::BOTH) * 100; -if ($amount < Configuration::get('PAYPLUG_MODULE_MIN_AMOUNT') * 100 || $amount > Configuration::get('PAYPLUG_MODULE_MAX_AMOUNT') * 100) - return false; +if ($amount < Configuration::get('PAYPLUG_MODULE_MIN_AMOUNT') * 100 || $amount > Configuration::get('PAYPLUG_MODULE_MAX_AMOUNT') * 100) { + return false; +} /** * Parameters for payment url @@ -68,27 +70,28 @@ $url_payment = Configuration::get('PAYPLUG_MODULE_URL'); $base_return_url = _PS_BASE_URL_.__PS_BASE_URI__.'modules/payplug/controllers/front/validation.php'; -if (version_compare(_PS_VERSION_, '1.5', '<')) - $customer = new Customer ($context->cookie->id_customer); -else - $customer = $context->customer; +if (version_compare(_PS_VERSION_, '1.5', '<')) { + $customer = new Customer($context->cookie->id_customer); +} else { + $customer = $context->customer; +} $params = array('amount'=>$amount, - 'custom_data'=>$context->cart->id, - 'origin'=>'Prestashop '._PS_VERSION_.' module '.$payplug->version, - 'currency'=>$result_currency['iso_code'], - 'ipn_url'=>_PS_BASE_URL_.__PS_BASE_URI__.'modules/payplug/ipn.php', - 'cancel_url'=>$base_return_url.'?ps=2&cartid='.$context->cart->id, - 'return_url'=>$base_return_url.'?ps=1&cartid='.$context->cart->id, - 'email'=>$customer->email, - 'firstname'=>$customer->firstname, - 'lastname'=>$customer->lastname, - 'order'=>$context->cart->id, - 'customer'=>$customer->id - ); + 'custom_data'=>$context->cart->id, + 'origin'=>'Prestashop '._PS_VERSION_.' module '.$payplug->version, + 'currency'=>$result_currency['iso_code'], + 'ipn_url'=>_PS_BASE_URL_.__PS_BASE_URI__.'modules/payplug/ipn.php', + 'cancel_url'=>$base_return_url.'?ps=2&cartid='.$context->cart->id, + 'return_url'=>$base_return_url.'?ps=1&cartid='.$context->cart->id, + 'email'=>$customer->email, + 'firstname'=>$customer->firstname, + 'lastname'=>$customer->lastname, + 'order'=>$context->cart->id, + 'customer'=>$customer->id + ); $url_params = http_build_query($params); $privatekey = Configuration::get('PAYPLUG_MODULE_KEY'); openssl_sign($url_params, $signature, $privatekey, $signature_alg = OPENSSL_ALGO_SHA1); $url_param_base_encode = base64_encode($url_params); $signature = base64_encode($signature); -Payplug::redirectForVersion($url_payment.'?data='.urlencode($url_param_base_encode).'&sign='.urlencode($signature)); \ No newline at end of file +Payplug::redirectForVersion($url_payment.'?data='.urlencode($url_param_base_encode).'&sign='.urlencode($signature)); diff --git a/controllers/front/validation.php b/controllers/front/validation.php index 6ad6e08..69823c8 100755 --- a/controllers/front/validation.php +++ b/controllers/front/validation.php @@ -1,6 +1,6 @@ iso_code; - $order_confirmation_url = 'order-confirmation.php?'; +if (version_compare(_PS_VERSION_, '1.4', '<')) { + return; } -else -{ - $context = Context::getContext(); - $currency = $context->currency; - $order_confirmation_url = 'index.php?controller=order-confirmation&'; + +if (version_compare(_PS_VERSION_, '1.5', '<')) { + $currency = Currency::getCurrent()->iso_code; + $order_confirmation_url = 'order-confirmation.php?'; +} else { + $context = Context::getContext(); + $currency = $context->currency; + $order_confirmation_url = 'index.php?controller=order-confirmation&'; } -if (!($cart_id = Tools::getValue('cartid'))) - Payplug::redirectForVersion('index.php?controller=order&step=1'); +if (!($cart_id = Tools::getValue('cartid'))) { + Payplug::redirectForVersion('index.php?controller=order&step=1'); +} $cart = new Cart($cart_id); /** * If no current cart, redirect to order page */ -if (!$cart->id) - Payplug::redirectForVersion('index.php?controller=order&step=1'); +if (!$cart->id) { + Payplug::redirectForVersion('index.php?controller=order&step=1'); +} /** * If no GET parameter with payment status code */ -if (!($ps = Tools::getValue('ps')) || $ps != 1) - Payplug::redirectForVersion('index.php?controller=order&step=1'); -if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$payplug->active) - Payplug::redirectForVersion('index.php?controller=order&step=1'); +if (!($ps = Tools::getValue('ps')) || $ps != 1) { + Payplug::redirectForVersion('index.php?controller=order&step=1'); +} +if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$payplug->active) { + Payplug::redirectForVersion('index.php?controller=order&step=1'); +} /** * Check that this payment option is still available in case the customer changed his address just before the end of the checkout process */ -if (!Payplug::moduleIsActive()) - die($payplug->l('This payment method is not available.', 'validation')); +if (!Payplug::moduleIsActive()) { + die($payplug->l('This payment method is not available.', 'validation')); +} $customer = new Customer((int)$cart->id_customer); -if (!Validate::isLoadedObject($customer)) - Payplug::redirectForVersion('index.php?controller=order&step=1'); +if (!Validate::isLoadedObject($customer)) { + Payplug::redirectForVersion('index.php?controller=order&step=1'); +} $total = (float)$cart->getOrderTotal(true, Cart::BOTH); @@ -84,18 +88,17 @@ $order_id = Order::getOrderByCartId($cart->id); -if (!$order_id) -{ - PayplugLock::addLock($cart->id); - /** Get the right order status following module configuration (Sandbox or not) */ - $order_state = Payplug::getOsConfiguration('waiting'); - $payplug->validateOrder($cart->id, $order_state, $total, $payplug->displayName, false, array(), (int)$currency->id, false, $customer->secure_key); - PayplugLock::deleteLock($cart->id); +if (!$order_id) { + PayplugLock::addLock($cart->id); + /** Get the right order status following module configuration (Sandbox or not) */ + $order_state = Payplug::getOsConfiguration('waiting'); + $payplug->validateOrder($cart->id, $order_state, $total, $payplug->displayName, false, array(), (int)$currency->id, false, $customer->secure_key); + PayplugLock::deleteLock($cart->id); + + $order_id = $payplug->currentOrder; - $order_id = $payplug->currentOrder; - } /** Change variable name, because $link is already instanciated */ $link_redirect = $order_confirmation_url.'id_cart='.$cart->id.'&id_module='.$payplug->id.'&id_order='.$order_id.'&key='.$customer->secure_key; -Payplug::redirectForVersion($link_redirect); \ No newline at end of file +Payplug::redirectForVersion($link_redirect); diff --git a/controllers/index.php b/controllers/index.php index 73fc04e..ca9555d 100755 --- a/controllers/index.php +++ b/controllers/index.php @@ -1,6 +1,6 @@ payplug_5fcaf79f4f4e91a7a3ae186d3f74bf08'] = 'PayPlug no es compatible con las versiones de PrestaShop anteriores a la 1.4. Para conseguir un funcionamiento normal, elimina el directorio /payplug del directorio de tus módulos de PrestaShop.'; $_MODULE['<{payplug}prestashop>payplug_bbf04ff90578fd1c19834db5809c55f4'] = 'PayPlug: pago en línea sencillo y seguro'; $_MODULE['<{payplug}prestashop>payplug_8bc3c9271813cb30ad64d959e30ee7e2'] = 'La solución de pago en línea más sencilla: inscripción gratuita, sin necesidad de suscripción y sin contrato de venta a distancia.'; diff --git a/index.php b/index.php index 4f6e5df..0f9074a 100755 --- a/index.php +++ b/index.php @@ -1,6 +1,6 @@ status type, value => Prestashop Default Configuration - $state_key = array( - 'paid' => 'PS_OS_PAYMENT', - 'refund' => 'PS_OS_REFUND', - 'waiting' => null, - ); - - // Loop keys - foreach ($state_key as $key => $cfg) - { - // Configuration key - $key_config = 'PAYPLUG_ORDER_STATE_'.Tools::strtoupper($key); - - // If config is not null - if ($cfg != null) - { - // Update OS PayPlug payment - if (defined('_'.$cfg.'_') || Payplug::getConfiguration($cfg)) - { - // If is in configuration (since 1.5) - if (!($os = Configuration::get($cfg))) - $os = constant('_'.$cfg.'_'); - - // Update configuration - Payplug::updateConfiguration($key_config, (int)$os); - } - } - // Create Order State if "Prestashop Default Configuration" is null - else - $this->createOrderStateSpecifc($key); - - // Create os tests - $this->createOrderStateSpecifc($key, true); - } - - } - - /** - * Create order - * @param string $key OS Key - * @param boolean $test if os test - */ - private function createOrderStateSpecifc($key, $test = false) - { - // Logo source - $source = dirname(__FILE__).'/logo.gif'; - - // If is an OS test - if ($test == true) - $key .= '_test'; - - // Configuration key - $key_config = 'PAYPLUG_ORDER_STATE_'.Tools::strtoupper($key); - - // If configuration not exists - if (!($os = Payplug::getConfiguration($key_config))) - { - // New state - $order_state = new OrderState(); - // Init state - $this->initOrderState($order_state, Tools::strtolower($key)); - // Add state - if ($order_state->add()) - { - // Change - $destination = _PS_IMG_DIR_.'os/'.(int)$order_state->id.'.gif'; - copy($source, $destination); - } - - // Update configuration - Payplug::updateConfiguration($key_config, (int)$order_state->id); - } - // if configuration exists update status - else - { - // Get status - $order_state = new OrderState($os); - // Init status - $this->initOrderState($order_state, Tools::strtolower($key)); - // Update status - $order_state->update(); - } - } - - /** - * Init parameters of PayPlug order states - */ - private function initOrderState(&$order_state = null, $type = null) - { - // Check if parameters is not null & if $type is an available type - if (is_null($order_state) || is_null($type) || !in_array($type, self::$available_types)) - return; - - $order_state->name = $this->getOrderStateName($type); - $order_state->send_email = false; - - // OS Waiting or Waiting test - if ($type == 'waiting' || $type == 'waiting_test') - { - $order_state->color = '#a1f8a1'; - $order_state->logable = false; - } - // OS Refund or Refund test - else if ($type == 'refund' || $type == 'refund_test') - { - $order_state->color = '#EA3737'; - $order_state->logable = false; - } - // OS Paid or Paid test - else if ($type == 'paid' || $type == 'paid_test') - { - $order_state->color = '#04B404'; - $order_state->send_email = true; - if (version_compare(_PS_VERSION_, '1.5', '<')) - { - $template = array(); - foreach (Language::getLanguages() as $language) - $template[$language['id_lang']] = 'payment'; - $order_state->template = $template; - } - else - { - $order_state->template = 'payment'; - $order_state->paid = true; - } - $order_state->logable = true; - } - - $order_state->module_name = 'payplug'; - $order_state->hidden = false; - $order_state->delivery = false; - $order_state->invoice = true; - } - - /** - * Get names in different languages for PayPlug order states waiting and paid - */ - private function getOrderStateName($type = null) - { - // Check if parameters is not null & if $type is an available type - if (is_null($type) || !in_array($type, self::$available_types)) - return; - - $order_state_name = array(); - foreach (Language::getLanguages() as $language) - { - if (Tools::strtolower($language['iso_code']) == 'fr') - { - if ($type == 'waiting') - $order_state_name[$language['id_lang']] = 'Paiement en cours [PayPlug]'; - else if ($type == 'waiting_test') - $order_state_name[$language['id_lang']] = 'Paiement en cours [TEST]'; - else if ($type == 'refund_test') - $order_state_name[$language['id_lang']] = 'Remboursé [TEST]'; - elseif ($type == 'paid_test') - $order_state_name[$language['id_lang']] = 'Paiement effectué [TEST]'; - } - else if (Tools::strtolower($language['iso_code']) == 'es') - { - if ($type == 'waiting') - $order_state_name[$language['id_lang']] = 'Pago en curso [PayPlug]'; - else if ($type == 'waiting_test') - $order_state_name[$language['id_lang']] = 'Pago en curso [TEST]'; - else if ($type == 'refund_test') - $order_state_name[$language['id_lang']] = 'Reembolsado [TEST]'; - elseif ($type == 'paid_test') - $order_state_name[$language['id_lang']] = 'Pago efectuado [TEST]'; - } - - else if (Tools::strtolower($language['iso_code']) == 'it') - { - if ($type == 'waiting') - $order_state_name[$language['id_lang']] = 'Pagamento in corso [PayPlug]'; - else if ($type == 'waiting_test') - $order_state_name[$language['id_lang']] = 'Pagamento in corso [TEST]'; - else if ($type == 'refund_test') - $order_state_name[$language['id_lang']] = 'Rimborsato [TEST]'; - elseif ($type == 'paid_test') - $order_state_name[$language['id_lang']] = 'Pagamento effettuato [TEST]'; - } - else - { - if ($type == 'waiting') - $order_state_name[$language['id_lang']] = 'Payment in progress [PayPlug]'; - if ($type == 'waiting_test') - $order_state_name[$language['id_lang']] = 'Payment in progress [TEST]'; - else if ($type == 'refund_test') - $order_state_name[$language['id_lang']] = 'Refunded [TEST]'; - elseif ($type == 'paid_test') - $order_state_name[$language['id_lang']] = 'Payment successful [TEST]'; - } - } - return $order_state_name; - } - - public function installPayplugLock() - { - - $SQL = " - CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_."payplug_lock` ( - `id_payplug_lock` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, - `id_cart` INT NOT NULL, - `date_add` DATETIME NOT NULL, - `date_upd` DATETIME NOT NULL - ) ENGINE="._MYSQL_ENGINE_." "; - - $return = DB::getInstance()->Execute($SQL); - } - - public function uninstallPayplugLock() - { - - $SQL = " DROP TABLE IF EXISTS `"._DB_PREFIX_."payplug_lock` "; - - $return = DB::getInstance()->Execute($SQL); - } -} \ No newline at end of file + status type, value => Prestashop Default Configuration + $state_key = array( + 'paid' => 'PS_OS_PAYMENT', + 'refund' => 'PS_OS_REFUND', + 'waiting' => null, + ); + + // Loop keys + foreach ($state_key as $key => $cfg) { + // Configuration key + $key_config = 'PAYPLUG_ORDER_STATE_'.Tools::strtoupper($key); + + // If config is not null + if ($cfg != null) { + // Update OS PayPlug payment + if (defined('_'.$cfg.'_') || Payplug::getConfiguration($cfg)) { + // If is in configuration (since 1.5) + if (!($os = Configuration::get($cfg))) { + $os = constant('_'.$cfg.'_'); + } + + // Update configuration + Payplug::updateConfiguration($key_config, (int)$os); + } + } else { + // Create Order State if "Prestashop Default Configuration" is null + $this->createOrderStateSpecifc($key); + } + + // Create os tests + $this->createOrderStateSpecifc($key, true); + } + + } + + /** + * Create order + * @param string $key OS Key + * @param boolean $test if os test + */ + private function createOrderStateSpecifc($key, $test = false) + { + // Logo source + $source = dirname(__FILE__).'/logo.gif'; + + // If is an OS test + if ($test == true) { + $key .= '_test'; + } + + // Configuration key + $key_config = 'PAYPLUG_ORDER_STATE_'.Tools::strtoupper($key); + + // If configuration not exists + if (!($os = Payplug::getConfiguration($key_config))) { + // New state + $order_state = new OrderState(); + // Init state + $this->initOrderState($order_state, Tools::strtolower($key)); + // Add state + if ($order_state->add()) { + // Change + $destination = _PS_IMG_DIR_.'os/'.(int)$order_state->id.'.gif'; + copy($source, $destination); + } + + // Update configuration + Payplug::updateConfiguration($key_config, (int)$order_state->id); + } else { + // if configuration exists update status + // Get status + $order_state = new OrderState($os); + // Init status + $this->initOrderState($order_state, Tools::strtolower($key)); + // Update status + $order_state->update(); + } + } + + /** + * Init parameters of PayPlug order states + */ + private function initOrderState(&$order_state = null, $type = null) + { + // Check if parameters is not null & if $type is an available type + if (is_null($order_state) || is_null($type) || !in_array($type, self::$available_types)) { + return; + } + + $order_state->name = $this->getOrderStateName($type); + $order_state->send_email = false; + + // OS Waiting or Waiting test + if ($type == 'waiting' || $type == 'waiting_test') { + $order_state->color = '#a1f8a1'; + $order_state->logable = false; + } elseif ($type == 'refund' || $type == 'refund_test') { + // OS Refund or Refund test + $order_state->color = '#EA3737'; + $order_state->logable = false; + } elseif ($type == 'paid' || $type == 'paid_test') { + // OS Paid or Paid test + $order_state->color = '#04B404'; + $order_state->send_email = true; + if (version_compare(_PS_VERSION_, '1.5', '<')) { + $template = array(); + foreach (Language::getLanguages() as $language) { + $template[$language['id_lang']] = 'payment'; + } + $order_state->template = $template; + } else { + $order_state->template = 'payment'; + $order_state->paid = true; + } + $order_state->logable = true; + } + + $order_state->module_name = 'payplug'; + $order_state->hidden = false; + $order_state->delivery = false; + $order_state->invoice = true; + } + + /** + * Get names in different languages for PayPlug order states waiting and paid + */ + private function getOrderStateName($type = null) + { + // Check if parameters is not null & if $type is an available type + if (is_null($type) || !in_array($type, self::$available_types)) { + return; + } + + $order_state_name = array(); + foreach (Language::getLanguages() as $language) { + if (Tools::strtolower($language['iso_code']) == 'fr') { + if ($type == 'waiting') { + $order_state_name[$language['id_lang']] = 'Paiement en cours [PayPlug]'; + } elseif ($type == 'waiting_test') { + $order_state_name[$language['id_lang']] = 'Paiement en cours [TEST]'; + } elseif ($type == 'refund_test') { + $order_state_name[$language['id_lang']] = 'Remboursé [TEST]'; + } elseif ($type == 'paid_test') { + $order_state_name[$language['id_lang']] = 'Paiement effectué [TEST]'; + } + } elseif (Tools::strtolower($language['iso_code']) == 'es') { + if ($type == 'waiting') { + $order_state_name[$language['id_lang']] = 'Pago en curso [PayPlug]'; + } elseif ($type == 'waiting_test') { + $order_state_name[$language['id_lang']] = 'Pago en curso [TEST]'; + } elseif ($type == 'refund_test') { + $order_state_name[$language['id_lang']] = 'Reembolsado [TEST]'; + } elseif ($type == 'paid_test') { + $order_state_name[$language['id_lang']] = 'Pago efectuado [TEST]'; + } + } elseif (Tools::strtolower($language['iso_code']) == 'it') { + if ($type == 'waiting') { + $order_state_name[$language['id_lang']] = 'Pagamento in corso [PayPlug]'; + } elseif ($type == 'waiting_test') { + $order_state_name[$language['id_lang']] = 'Pagamento in corso [TEST]'; + } elseif ($type == 'refund_test') { + $order_state_name[$language['id_lang']] = 'Rimborsato [TEST]'; + } elseif ($type == 'paid_test') { + $order_state_name[$language['id_lang']] = 'Pagamento effettuato [TEST]'; + } + } else { + if ($type == 'waiting') { + $order_state_name[$language['id_lang']] = 'Payment in progress [PayPlug]'; + } elseif ($type == 'waiting_test') { + $order_state_name[$language['id_lang']] = 'Payment in progress [TEST]'; + } elseif ($type == 'refund_test') { + $order_state_name[$language['id_lang']] = 'Refunded [TEST]'; + } elseif ($type == 'paid_test') { + $order_state_name[$language['id_lang']] = 'Payment successful [TEST]'; + } + } + } + return $order_state_name; + } + + public function installPayplugLock() + { + $SQL = " + CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_."payplug_lock` ( + `id_payplug_lock` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, + `id_cart` INT NOT NULL, + `date_add` DATETIME NOT NULL, + `date_upd` DATETIME NOT NULL + ) ENGINE="._MYSQL_ENGINE_." "; + + DB::getInstance()->Execute($SQL); + } + + public function uninstallPayplugLock() + { + $SQL = " DROP TABLE IF EXISTS `"._DB_PREFIX_."payplug_lock` "; + + DB::getInstance()->Execute($SQL); + } +} diff --git a/ipn.php b/ipn.php index 5a25ead..a3bf4a9 100755 --- a/ipn.php +++ b/ipn.php @@ -1,6 +1,6 @@ $value) - { - if (Tools::substr($name, 0, 5) == 'HTTP_') - { - $name = str_replace(' ', '-', ucwords(Tools::strtolower(str_replace('_', ' ', Tools::substr($name, 5))))); - $headers[$name] = $value; - } - else if ($name == 'CONTENT_TYPE') - $headers['Content-Type'] = $value; - else if ($name == 'CONTENT_LENGTH') - $headers['Content-Length'] = $value; - else - $headers[$name] = $value; - } - return $headers; - } +if (!function_exists('getallheaders')) { + function getallheaders() + { + $headers = array(); + foreach ($_SERVER as $name => $value) { + if (Tools::substr($name, 0, 5) == 'HTTP_') { + $name = str_replace(' ', '-', ucwords(Tools::strtolower(str_replace('_', ' ', Tools::substr($name, 5))))); + $headers[$name] = $value; + } elseif ($name == 'CONTENT_TYPE') { + $headers['Content-Type'] = $value; + } elseif ($name == 'CONTENT_LENGTH') { + $headers['Content-Length'] = $value; + } else { + $headers[$name] = $value; + } + } + return $headers; + } } /** @@ -82,10 +79,9 @@ function getallheaders() */ $headers = array_change_key_case($headers, CASE_UPPER); -if (!isset($headers['PAYPLUG-SIGNATURE'])) -{ - header($_SERVER['SERVER_PROTOCOL'].' 403 Signature not provided', true, 403); - die; +if (!isset($headers['PAYPLUG-SIGNATURE'])) { + header($_SERVER['SERVER_PROTOCOL'].' 403 Signature not provided', true, 403); + die; } $signature = base64_decode($headers['PAYPLUG-SIGNATURE']); @@ -97,165 +93,139 @@ function getallheaders() $status = (int)$data->status; /** Available status */ $status_available = array( - Payplug::PAYMENT_STATUS_PAID, - Payplug::PAYMENT_STATUS_REFUND + Payplug::PAYMENT_STATUS_PAID, + Payplug::PAYMENT_STATUS_REFUND ); /** if status is an available status */ -if (in_array($status, $status_available)) -{ - $public_key = Configuration::get('PAYPLUG_MODULE_PUBLIC_KEY'); - $check_signature = openssl_verify($body, $signature, $public_key, OPENSSL_ALGO_SHA1); - $bool_sign = false; - - if ($check_signature == 1) - $bool_sign = true; - else if ($check_signature == 0) - { - echo 'Invalid signature'; - header($_SERVER['SERVER_PROTOCOL'].' 403 Invalid signature', true, 403); - die; - } - else - { - echo 'Error while checking signature'; - header($_SERVER['SERVER_PROTOCOL'].' 500 Error while checking signature', true, 500); - die; - } - - if ($data && $bool_sign) - { - /** Data is an object */ - $cart = new Cart($data->custom_data); - if (Validate::isLoadedObject($cart)) - { - $address = new Address((int)$cart->id_address_invoice); - - if (Validate::isLoadedObject($address)) - { - Context::getContext()->country = new Country((int)$address->id_country); - Context::getContext()->customer = new Customer((int)$cart->id_customer); - Context::getContext()->language = new Language((int)$cart->id_lang); - Context::getContext()->currency = new Currency((int)$cart->id_currency); - - - PayplugLock::check($cart->id); - - $order = new Order(); - $order_id = $order->getOrderByCartId($cart->id); - - - /** - * If existing order - */ - if ($order_id) - { - - /** - * If status paid - */ - if ($status == Payplug::PAYMENT_STATUS_PAID) - { - $order = new Order($order_id); - /** Get the right order status following module configuration (Sandbox or not) */ - $order_state = Payplug::getOsConfiguration('waiting'); - $current_state = $order->getCurrentState(); - - if ($current_state == $order_state) - { - $order_history = new OrderHistory(); - /** - * Change order state to payment paid by payplug - */ - $order_history->id_order = $order_id; - - /** Get the right order status following module configuration (Sandbox or not) */ - $new_order_state = Payplug::getOsConfiguration('paid'); - $order_history->changeIdOrderState((int)$new_order_state, $order_id); - $order_history->save(); - if (version_compare(_PS_VERSION_, '1.5', '>') && version_compare(_PS_VERSION_, '1.5.2', '<')) - { - $order->current_state = $order_history->id_order_state; - $order->update(); - } - } - } - /** - * If status refund - */ - else if ($status == Payplug::PAYMENT_STATUS_REFUND) - { - $order_history = new OrderHistory(); - /** - * Change order state to refund by payplug - */ - $order_history->id_order = $order_id; - /** Get the right order status following module configuration (Sandbox or not) */ - $new_order_state = Payplug::getOsConfiguration('refund'); - $order_history->changeIdOrderState((int)$new_order_state, $order_id); - $order_history->save(); - if (version_compare(_PS_VERSION_, '1.5', '>') && version_compare(_PS_VERSION_, '1.5.2', '<')) - { - $order->current_state = $order_history->id_order_state; - $order->update(); - } - } - } - /** - * Else validate order - */ - else - { - - PayplugLock::addLock($cart->id); - - if ($status == Payplug::PAYMENT_STATUS_PAID) - { - $extra_vars = array(); - /** Data is an object */ - $extra_vars['transaction_id'] = $data->id_transaction; - $currency = (int)$cart->id_currency; - $customer = new Customer((int)$cart->id_customer); - /** Get the right order status following module configuration (Sandbox or not) */ - $order_state = Payplug::getOsConfiguration('paid'); - $amount = (float)$data->amount / 100; - $payplug->validateOrder($cart->id, $order_state, $amount, $payplug->displayName, null, $extra_vars, $currency, false, $customer->secure_key); - if (version_compare(_PS_VERSION_, '1.5', '>') && version_compare(_PS_VERSION_, '1.5.2', '<')) - { - $order_id = Order::getOrderByCartId($cart->id); - $order = new Order($order_id); - $order_payment = end($order->getOrderPayments()); - $order_payment->transaction_id = $extra_vars['transaction_id']; - $order_payment->update(); - } - } - - PayplugLock::deleteLock($cart->id); - } - Configuration::updateValue('PAYPLUG_CONFIGURATION_OK', true); - } - else - { - echo 'Error : missing or wrong parameters.'; - header($_SERVER['SERVER_PROTOCOL'].' 400 Missing or wrong parameters for address', true, 400); - die; - } - } - else - { - echo 'Error : missing or wrong parameters.'; - header($_SERVER['SERVER_PROTOCOL'].' 400 Missing or wrong parameters for cart', true, 400); - die; - } - } - else - { - echo 'Error : missing or wrong parameters.'; - header($_SERVER['SERVER_PROTOCOL'].' 400 Missing or wrong parameters', true, 400); - die; - } +if (in_array($status, $status_available)) { + $public_key = Configuration::get('PAYPLUG_MODULE_PUBLIC_KEY'); + $check_signature = openssl_verify($body, $signature, $public_key, OPENSSL_ALGO_SHA1); + $bool_sign = false; + + if ($check_signature == 1) { + $bool_sign = true; + } elseif ($check_signature == 0) { + echo 'Invalid signature'; + header($_SERVER['SERVER_PROTOCOL'].' 403 Invalid signature', true, 403); + die; + } else { + echo 'Error while checking signature'; + header($_SERVER['SERVER_PROTOCOL'].' 500 Error while checking signature', true, 500); + die; + } + + if ($data && $bool_sign) { + /** Data is an object */ + $cart = new Cart($data->custom_data); + if (Validate::isLoadedObject($cart)) { + $address = new Address((int)$cart->id_address_invoice); + + if (Validate::isLoadedObject($address)) { + Context::getContext()->country = new Country((int)$address->id_country); + Context::getContext()->customer = new Customer((int)$cart->id_customer); + Context::getContext()->language = new Language((int)$cart->id_lang); + Context::getContext()->currency = new Currency((int)$cart->id_currency); + + PayplugLock::check($cart->id); + + $order = new Order(); + $order_id = $order->getOrderByCartId($cart->id); + + /** + * If existing order + */ + if ($order_id) { + /** + * If status paid + */ + if ($status == Payplug::PAYMENT_STATUS_PAID) { + $order = new Order($order_id); + /** Get the right order status following module configuration (Sandbox or not) */ + $order_state = Payplug::getOsConfiguration('waiting'); + $current_state = $order->getCurrentState(); + + if ($current_state == $order_state) { + $order_history = new OrderHistory(); + /** + * Change order state to payment paid by payplug + */ + $order_history->id_order = $order_id; + + /** Get the right order status following module configuration (Sandbox or not) */ + $new_order_state = Payplug::getOsConfiguration('paid'); + $order_history->changeIdOrderState((int)$new_order_state, $order_id); + $order_history->save(); + if (version_compare(_PS_VERSION_, '1.5', '>') && version_compare(_PS_VERSION_, '1.5.2', '<')) { + $order->current_state = $order_history->id_order_state; + $order->update(); + } + } + } elseif ($status == Payplug::PAYMENT_STATUS_REFUND) { + /** + * If status refund + */ + + $order_history = new OrderHistory(); + /** + * Change order state to refund by payplug + */ + $order_history->id_order = $order_id; + /** Get the right order status following module configuration (Sandbox or not) */ + $new_order_state = Payplug::getOsConfiguration('refund'); + $order_history->changeIdOrderState((int)$new_order_state, $order_id); + $order_history->save(); + if (version_compare(_PS_VERSION_, '1.5', '>') && version_compare(_PS_VERSION_, '1.5.2', '<')) { + $order->current_state = $order_history->id_order_state; + $order->update(); + } + } + } else { + /** + * Else validate order + */ + + PayplugLock::addLock($cart->id); + + if ($status == Payplug::PAYMENT_STATUS_PAID) { + $extra_vars = array(); + /** Data is an object */ + $extra_vars['transaction_id'] = $data->id_transaction; + $currency = (int)$cart->id_currency; + $customer = new Customer((int)$cart->id_customer); + /** Get the right order status following module configuration (Sandbox or not) */ + $order_state = Payplug::getOsConfiguration('paid'); + $amount = (float)$data->amount / 100; + $payplug->validateOrder($cart->id, $order_state, $amount, $payplug->displayName, null, $extra_vars, $currency, false, $customer->secure_key); + if (version_compare(_PS_VERSION_, '1.5', '>') && version_compare(_PS_VERSION_, '1.5.2', '<')) { + $order_id = Order::getOrderByCartId($cart->id); + $order = new Order($order_id); + $order_payment = end($order->getOrderPayments()); + $order_payment->transaction_id = $extra_vars['transaction_id']; + $order_payment->update(); + } + } + + PayplugLock::deleteLock($cart->id); + } + Configuration::updateValue('PAYPLUG_CONFIGURATION_OK', true); + } else { + echo 'Error : missing or wrong parameters.'; + header($_SERVER['SERVER_PROTOCOL'].' 400 Missing or wrong parameters for address', true, 400); + die; + } + } else { + echo 'Error : missing or wrong parameters.'; + header($_SERVER['SERVER_PROTOCOL'].' 400 Missing or wrong parameters for cart', true, 400); + die; + } + } else { + echo 'Error : missing or wrong parameters.'; + header($_SERVER['SERVER_PROTOCOL'].' 400 Missing or wrong parameters', true, 400); + die; + } } /** Restore display errors configuration */ -if (Payplug::getConfiguration('PAYPLUG_DEBUG')) - @ini_set('display_errors', $display_errors); - +if (Payplug::getConfiguration('PAYPLUG_DEBUG')) { + @ini_set('display_errors', $display_errors); +} diff --git a/it.php b/it.php index e3b4a0e..c5f1f4f 100644 --- a/it.php +++ b/it.php @@ -1,7 +1,7 @@ payplug_5fcaf79f4f4e91a7a3ae186d3f74bf08'] = 'PayPlug non è compatibile con le versioni inferiori a 1.4 di PrestaShop. Per ripristinare il funzionamento normale, elimina la directory /payplug nella directory dei tuoi moduli di PrestaShop.'; $_MODULE['<{payplug}prestashop>payplug_bbf04ff90578fd1c19834db5809c55f4'] = 'PayPlug – Pagamento on-line semplice e sicuro'; $_MODULE['<{payplug}prestashop>payplug_8bc3c9271813cb30ad64d959e30ee7e2'] = 'La soluzione di pagamento on-line più semplice: iscrizione gratuita, senza abbonamento e senza contratto VAD!'; diff --git a/payplug.php b/payplug.php index b8a02e9..88171e9 100755 --- a/payplug.php +++ b/payplug.php @@ -1,6 +1,6 @@ name = 'payplug'; - $this->tab = 'payments_gateways'; - $this->version = '0.9.10'; - $this->author = 'PayPlug'; - $this->module_key = '1ee28a8fb5e555e274bd8c2e1c45e31a'; - - parent::__construct(); - - // Backward compatibility - if (version_compare(_PS_VERSION_, '1.5', '<')) - require(_PS_MODULE_DIR_.$this->name.'/backward_compatibility/backward.php'); - - // Add warning if prestashop is an older version than 1.4 - if (version_compare(_PS_VERSION_, '1.4', '<')) - $this->warning = $this->l('Sorry Payplug is not compatible with Prestashop for versions < 1.4. Please delete the payplug directory in the Prestashop modules directory for your Prestashop system to get back to normal.'); - - $this->currencies = true; - $this->currencies_mode = 'checkbox'; - // Change descriptionn and display name - $this->displayName = $this->l('PayPlug – Simple and secure online payments'); - $this->description = $this->l('The simplest online payment solution: no setup fees, no fixed fees, and no merchant account required!'); - $this->confirmUninstall = $this->l('Are you sure you wish to uninstall this module and delete your settings?'); - if (version_compare(_PS_VERSION_, '1.5', '<')) - { - $cookie_admin = new Cookie('psAdmin', Tools::substr($_SERVER['PHP_SELF'], Tools::strlen(__PS_BASE_URI__), -10)); - if (Tools::getValue('tab') == 'AdminPayment' && Tools::getValue('token') != Tools::getAdminTokenLite('AdminPayment')) - { - // Force admin status - $this->context->cookie->profile = $cookie_admin->profile; - $url = 'index.php?tab=AdminPayment'; - $url .= '&token='.Tools::getAdminTokenLite('AdminPayment'); - Tools::redirectAdmin($url); - } - } - } - - /** - * Update configuration - * @var string Configuration key - * @var mixed Configuration value - * @var boolean If is global configuration - */ - public static function updateConfiguration($key, $value, $global = false) - { - if (version_compare(_PS_VERSION_, '1.5', '>=') && $global) - Configuration::updateGlobalValue($key, $value); - else - Configuration::updateValue($key, $value); - } - - /** - * Get configuration - * @var string Configuration key - * @var boolean If is global configuration - * @return mixed Value of key, or false if not exists - */ - public static function getConfiguration($key, $global = false) - { - if (version_compare(_PS_VERSION_, '1.5', '>=') && $global) - $value = Configuration::getGlobalValue($key); - else - $value = Configuration::get($key); - - return $value; - } - - /** - * Get Order State configuration - * @param string $state_name State name - * @return integer Value - */ - public static function getOsConfiguration($state_name) - { - $key = 'PAYPLUG_ORDER_STATE_'.Tools::strtoupper($state_name); - - if (self::getConfiguration('PAYPLUG_SANDBOX')) - $key .= '_TEST'; - - return self::getConfiguration($key, false); - } - - public function install() - { - if (version_compare(_PS_VERSION_, '1.4', '<') || !parent::install() || !$this->registerHook('payment') || !$this->registerHook('paymentReturn')) - return false; - - if (!$this->registerHook('header')) - return false; - - $payplug_install = new InstallPayplug(); - $payplug_install->createConfig(); - $payplug_install->createOrderState(); - - $payplug_install->installPayplugLock(); - - return true; - } - - public function uninstall() - { - $payplug_install = new InstallPayplug(); - $payplug_install->deleteConfig(); - $payplug_install->uninstallPayplugLock(); - - return parent::uninstall(); - } - - public static function moduleIsActive() - { - if (self::$is_active == -1) - { - // This override is part of the cloudcache module, so the cloudcache.php file exists - require_once(dirname(__FILE__).'/../../modules/cloudcache/cloudcache.php'); - $module = new CloudCache(); - self::$is_active = $module->active; - } - return self::$is_active; - } - - public function assignForVersion($variable, $contenue = null) - { - if (version_compare(_PS_VERSION_, '1.5', '<')) - $this->context->smarty->assign($variable, $contenue); - else - $this->smarty->assign($variable, $contenue); - } - - public static function redirectForVersion($link) - { - if (version_compare(_PS_VERSION_, '1.5', '<')) - Tools::redirectLink($link); - else - Tools::redirect($link); - } - - public function getContent() - { - // if ps version is not available - if (version_compare(_PS_VERSION_, '1.4', '<')) - return; - - // Link base - if (version_compare(_PS_VERSION_, '1.5', '>')) - $this->_link = 'index.php?controller='.Tools::getValue('controller'); - else - $this->_link = 'index.php?tab='.Tools::getValue('tab'); - - $this->_link .= '&configure='.$this->name.'&token='.Tools::getValue('token').'&tab_module='.$this->tab.'&module_name='.$this->name; - - $display_form = true; - // For 1.6 - $this->bootstrap = true; - // Check extensions - $curl_exists = extension_loaded('curl'); - $openssl_exists = extension_loaded('openssl'); - $errors = array(); - // Add msg if extension not exists - if (!$curl_exists || !$openssl_exists) - { - - // cURL not found - if (!$curl_exists) - $errors[] = sprintf($this->l('Connection error: %s library is missing. Please ask your hosting provider to install the %s library on your server, and try configuring the PayPlug module on Prestashop again.'), 'cURL', 'cURL'); - - // OpenSSL not found - if (!$openssl_exists) - $errors[] = sprintf($this->l('Connection error: %s library is missing. Please ask your hosting provider to install the %s library on your server, and try configuring the PayPlug module on Prestashop again.'), 'OpenSSL', 'OpenSSL'); - } - - // Check if form was sent - if (Tools::getValue('payplug_email') && Tools::getValue('payplug_password')) - { - $this->assignForVersion('email', Tools::getValue('payplug_email')); - // if extensions exist - if ($curl_exists && $openssl_exists) - { - - $sandbox_button = Tools::isSubmit('sandboxButton'); - // Get url to curl - $url = $sandbox_button ? Payplug::URL_TEST_AUTOCONFIG : Payplug::URL_AUTOCONFIG; - - $curl_version = curl_version(); - - $process = curl_init($url); - curl_setopt($process, CURLOPT_USERPWD, Tools::getValue('payplug_email').':'.Tools::getValue('payplug_password')); - curl_setopt($process, CURLOPT_RETURNTRANSFER, true); - // CURL const are in uppercase - curl_setopt($process, CURLOPT_SSLVERSION, defined('CURL_SSLVERSION_TLSV1') ? CURL_SSLVERSION_TLSV1 : 1); - curl_setopt($process, CURLOPT_SSL_VERIFYPEER, true); - # >= 7.26 to 7.28.1 add a notice message for value 1 will be remove - curl_setopt($process, CURLOPT_SSL_VERIFYHOST, (version_compare($curl_version['version'], '7.21', '<') ? true : 2)); - curl_setopt($process, CURLOPT_CAINFO, realpath(dirname(__FILE__).'/cacert.pem')); //work only wiht cURL 7.10+ - $answer = curl_exec($process); - - $error_curl = curl_errno($process); - curl_close($process); - - // if no error - if ($error_curl == 0) - { - $json_answer = Tools::jsonDecode($answer); - // if account is just in test mod - if ($json_answer->status == 403) - { - $errors[] = sprintf( - $this->l('To set up the module in LIVE mode, you first need %s to request your account to be activated %s.'), - '', - ''); - } - else if ($json_answer->status == 200) - { - $payplug_install = new InstallPayplug(); - - if (!is_array($json_answer->currencies)) - $currencies = implode(Tools::jsonDecode($json_answer->currencies), ';'); - else - $currencies = $json_answer->currencies[0]; - - $private_key = $json_answer->yourPrivateKey; - $public_key = $json_answer->payplugPublicKey; - - // explode for validator - $payplug_install->updateConfig( - $private_key, - $public_key, - $json_answer->url, - $json_answer->amount_min, - $json_answer->amount_max, - $currencies, - (string)(int)$sandbox_button); - - $display_form = false; - // redirect for update message - Tools::redirectAdmin($this->_link.'&conf=4'); - } - else - $errors[] = $this->l('Your email or password is incorrect.'); - } - else - $errors[] = $error_curl; - } - } - // toggle debug mode - else if (Tools::getIsset('debug_mode')) - { - self::updateConfiguration('PAYPLUG_DEBUG', !self::getConfiguration('PAYPLUG_DEBUG')); - Tools::redirectAdmin($this->_link.'&conf=4'); - } - - if (Configuration::get('PAYPLUG_MODULE_KEY') != '' - && Configuration::get('PAYPLUG_MODULE_PUBLIC_KEY') != '' - && Configuration::get('PAYPLUG_MODULE_URL') != '' - && Configuration::get('PAYPLUG_MODULE_MIN_AMOUNT') != '' - && Configuration::get('PAYPLUG_MODULE_MAX_AMOUNT') != '' - && Configuration::get('PAYPLUG_MODULE_CURRENCIES') != '') - { - $this->assignForVersion( - array( - 'moduleInstalled' => true, - 'minAmount' => Configuration::get('PAYPLUG_MODULE_MIN_AMOUNT'), - 'maxAmount' => Configuration::get('PAYPLUG_MODULE_MAX_AMOUNT'), - 'currencies' => Configuration::get('PAYPLUG_MODULE_CURRENCIES'), - 'sandboxMode' => Payplug::getConfiguration('PAYPLUG_SANDBOX'), // Assign sandbox mode - 'debugMode' => Payplug::getConfiguration('PAYPLUG_DEBUG'), // assign debug mode - ) - ); - } - - // Assign datas - $datas = array( - 'this_path' => $this->_path, - 'displayForm' => $display_form, - 'errors' => $errors, - 'this_link' => $this->_link, - ); - - $this->assignForVersion($datas); - - return $this->display(__FILE__, './views/templates/admin/admin.tpl'); - } - - public function hookPayment() - { - $cart = $this->context->cart; - - $iso_code = $this->context->currency->iso_code; - $supported_currencies = explode(';', Configuration::get('PAYPLUG_MODULE_CURRENCIES')); - if (!in_array($iso_code, $supported_currencies)) - return; - // Check amount - $amount = $cart->getOrderTotal(true, Cart::BOTH) * 100; - - if ($amount < Configuration::get('PAYPLUG_MODULE_MIN_AMOUNT') * 100 || $amount > Configuration::get('PAYPLUG_MODULE_MAX_AMOUNT') * 100) - return; - - $this->assignForVersion('this_path', $this->_path); - $this->assignForVersion('iso_lang', $this->context->language->iso_code); - - // Different tpl depending version - if (version_compare(_PS_VERSION_, '1.6', '<')) - { - if (version_compare(_PS_VERSION_, '1.5', '<')) - return $this->display(__FILE__, './views/templates/hook/payment.tpl'); - else - return $this->display(__FILE__, 'payment.tpl'); - } - else - return $this->display(__FILE__, 'payment_16.tpl'); - } - - public function hookPaymentReturn() - { - if (!$this->active) - return null; - $order_id = Tools::getValue('id_order'); - $order = new Order($order_id); - // Check order state to display appropriate message - $state = null; - if (isset($order->current_state) && $order->current_state == Configuration::get('PAYPLUG_ORDER_STATE_WAITING')) - $state = 'waiting'; - elseif (isset($order->current_state) && $order->current_state == Configuration::get('PAYPLUG_ORDER_STATE_PAID')) - $state = 'paid'; - // if waiting_test state - else if (isset($order->current_state) && $order->current_state == Configuration::get('PAYPLUG_ORDER_STATE_WAITING_TEST')) - $state = 'waiting_test'; - // if paid_test state - elseif (isset($order->current_state) && $order->current_state == Configuration::get('PAYPLUG_ORDER_STATE_PAID_TEST')) - $state = 'paid_test'; - - $this->assignForVersion('state', $state); - // Get order information for display - $total_paid = number_format($order->total_paid, 2, ',', ''); - $context = array('totalPaid' => $total_paid); - if (isset($order->reference)) - $context['reference'] = $order->reference; - $this->assignForVersion($context); - if (version_compare(_PS_VERSION_, '1.5', '<')) - return $this->display(__FILE__, './views/templates/hook/confirmation.tpl'); - else - return $this->display(__FILE__, 'confirmation.tpl'); - } - - /** - * Hook for 1.4 - */ - public function hookHeader() - { - if (version_compare(_PS_VERSION_, '1.6', '<')) - return; - - $controller = $this->context->controller; - - if ($controller instanceof OrderOpcController || ($controller instanceof OrderController && $controller->step == 3)) - { - $file = 'css/front.css'; - $this->context->controller->addCss($this->getLocalPath().$file); - } - } + public static $is_active = 1; + const PAYMENT_STATUS_PAID = 0; + const PAYMENT_STATUS_REFUND = 4; + const PAYMENT_STATUS_CANCEL = 2; + const URL_AUTOCONFIG = 'https://www.payplug.fr/portal/ecommerce/autoconfig'; + /** Url to sandbox */ + const URL_TEST_AUTOCONFIG = 'https://www.payplug.fr/portal/test/ecommerce/autoconfig'; + + public function __construct() + { + $this->name = 'payplug'; + $this->tab = 'payments_gateways'; + $this->version = '0.9.10'; + $this->author = 'PayPlug'; + $this->module_key = '1ee28a8fb5e555e274bd8c2e1c45e31a'; + + parent::__construct(); + + // Backward compatibility + if (version_compare(_PS_VERSION_, '1.5', '<')) { + require(_PS_MODULE_DIR_.$this->name.'/backward_compatibility/backward.php'); + } + + // Add warning if prestashop is an older version than 1.4 + if (version_compare(_PS_VERSION_, '1.4', '<')) { + $this->warning = $this->l('Sorry Payplug is not compatible with Prestashop for versions < 1.4. Please delete the payplug directory in the Prestashop modules directory for your Prestashop system to get back to normal.'); + } + + $this->currencies = true; + $this->currencies_mode = 'checkbox'; + // Change descriptionn and display name + $this->displayName = $this->l('PayPlug – Simple and secure online payments'); + $this->description = $this->l('The simplest online payment solution: no setup fees, no fixed fees, and no merchant account required!'); + $this->confirmUninstall = $this->l('Are you sure you wish to uninstall this module and delete your settings?'); + if (version_compare(_PS_VERSION_, '1.5', '<')) { + $cookie_admin = new Cookie('psAdmin', Tools::substr($_SERVER['PHP_SELF'], Tools::strlen(__PS_BASE_URI__), -10)); + if (Tools::getValue('tab') == 'AdminPayment' && Tools::getValue('token') != Tools::getAdminTokenLite('AdminPayment')) { + // Force admin status + $this->context->cookie->profile = $cookie_admin->profile; + $url = 'index.php?tab=AdminPayment'; + $url .= '&token='.Tools::getAdminTokenLite('AdminPayment'); + Tools::redirectAdmin($url); + } + } + } + + /** + * Update configuration + * @var string Configuration key + * @var mixed Configuration value + * @var boolean If is global configuration + */ + public static function updateConfiguration($key, $value, $global = false) + { + if (version_compare(_PS_VERSION_, '1.5', '>=') && $global) { + Configuration::updateGlobalValue($key, $value); + } else { + Configuration::updateValue($key, $value); + } + } + + /** + * Get configuration + * @var string Configuration key + * @var boolean If is global configuration + * @return mixed Value of key, or false if not exists + */ + public static function getConfiguration($key, $global = false) + { + if (version_compare(_PS_VERSION_, '1.5', '>=') && $global) { + $value = Configuration::getGlobalValue($key); + } else { + $value = Configuration::get($key); + } + + return $value; + } + + /** + * Get Order State configuration + * @param string $state_name State name + * @return integer Value + */ + public static function getOsConfiguration($state_name) + { + $key = 'PAYPLUG_ORDER_STATE_'.Tools::strtoupper($state_name); + + if (self::getConfiguration('PAYPLUG_SANDBOX')) { + $key .= '_TEST'; + } + + return self::getConfiguration($key, false); + } + + public function install() + { + if (version_compare(_PS_VERSION_, '1.4', '<') || !parent::install() || !$this->registerHook('payment') || !$this->registerHook('paymentReturn')) { + return false; + } + + if (!$this->registerHook('header')) { + return false; + } + + $payplug_install = new InstallPayplug(); + $payplug_install->createConfig(); + $payplug_install->createOrderState(); + + $payplug_install->installPayplugLock(); + + return true; + } + + public function uninstall() + { + $payplug_install = new InstallPayplug(); + $payplug_install->deleteConfig(); + $payplug_install->uninstallPayplugLock(); + + return parent::uninstall(); + } + + public static function moduleIsActive() + { + if (self::$is_active == -1) { + // This override is part of the cloudcache module, so the cloudcache.php file exists + require_once(dirname(__FILE__).'/../../modules/cloudcache/cloudcache.php'); + $module = new CloudCache(); + self::$is_active = $module->active; + } + return self::$is_active; + } + + public function assignForVersion($variable, $contenue = null) + { + if (version_compare(_PS_VERSION_, '1.5', '<')) { + $this->context->smarty->assign($variable, $contenue); + } else { + $this->smarty->assign($variable, $contenue); + } + } + + public static function redirectForVersion($link) + { + if (version_compare(_PS_VERSION_, '1.5', '<')) { + Tools::redirectLink($link); + } else { + Tools::redirect($link); + } + } + + public function getContent() + { + // if ps version is not available + if (version_compare(_PS_VERSION_, '1.4', '<')) { + return; + } + + // Link base + if (version_compare(_PS_VERSION_, '1.5', '>')) { + $this->_link = 'index.php?controller='.Tools::getValue('controller'); + } else { + $this->_link = 'index.php?tab='.Tools::getValue('tab'); + } + + $this->_link .= '&configure='.$this->name.'&token='.Tools::getValue('token').'&tab_module='.$this->tab.'&module_name='.$this->name; + + $display_form = true; + // For 1.6 + $this->bootstrap = true; + // Check extensions + $curl_exists = extension_loaded('curl'); + $openssl_exists = extension_loaded('openssl'); + $errors = array(); + // Add msg if extension not exists + if (!$curl_exists || !$openssl_exists) { + // cURL not found + if (!$curl_exists) { + $errors[] = sprintf($this->l('Connection error: %s library is missing. Please ask your hosting provider to install the %s library on your server, and try configuring the PayPlug module on Prestashop again.'), 'cURL', 'cURL'); + } + + // OpenSSL not found + if (!$openssl_exists) { + $errors[] = sprintf($this->l('Connection error: %s library is missing. Please ask your hosting provider to install the %s library on your server, and try configuring the PayPlug module on Prestashop again.'), 'OpenSSL', 'OpenSSL'); + } + } + + // Check if form was sent + if (Tools::getValue('payplug_email') && Tools::getValue('payplug_password')) { + $this->assignForVersion('email', Tools::getValue('payplug_email')); + // if extensions exist + if ($curl_exists && $openssl_exists) { + $sandbox_button = Tools::isSubmit('sandboxButton'); + // Get url to curl + $url = $sandbox_button ? Payplug::URL_TEST_AUTOCONFIG : Payplug::URL_AUTOCONFIG; + + $curl_version = curl_version(); + + $process = curl_init($url); + curl_setopt($process, CURLOPT_USERPWD, Tools::getValue('payplug_email').':'.Tools::getValue('payplug_password')); + curl_setopt($process, CURLOPT_RETURNTRANSFER, true); + // CURL const are in uppercase + curl_setopt($process, CURLOPT_SSLVERSION, defined('CURL_SSLVERSION_TLSV1') ? CURL_SSLVERSION_TLSV1 : 1); + curl_setopt($process, CURLOPT_SSL_VERIFYPEER, true); + # >= 7.26 to 7.28.1 add a notice message for value 1 will be remove + curl_setopt($process, CURLOPT_SSL_VERIFYHOST, (version_compare($curl_version['version'], '7.21', '<') ? true : 2)); + curl_setopt($process, CURLOPT_CAINFO, realpath(dirname(__FILE__).'/cacert.pem')); //work only wiht cURL 7.10+ + $answer = curl_exec($process); + + $error_curl = curl_errno($process); + curl_close($process); + + // if no error + if ($error_curl == 0) { + $json_answer = Tools::jsonDecode($answer); + // if account is just in test mod + if ($json_answer->status == 403) { + $errors[] = sprintf( + $this->l('To set up the module in LIVE mode, you first need %s to request your account to be activated %s.'), + '', + '' + ); + } elseif ($json_answer->status == 200) { + $payplug_install = new InstallPayplug(); + + if (!is_array($json_answer->currencies)) { + $currencies = implode(Tools::jsonDecode($json_answer->currencies), ';'); + } else { + $currencies = $json_answer->currencies[0]; + } + + $private_key = $json_answer->yourPrivateKey; + $public_key = $json_answer->payplugPublicKey; + + // explode for validator + $payplug_install->updateConfig( + $private_key, + $public_key, + $json_answer->url, + $json_answer->amount_min, + $json_answer->amount_max, + $currencies, + (string)(int)$sandbox_button + ); + + $display_form = false; + // redirect for update message + Tools::redirectAdmin($this->_link.'&conf=4'); + } else { + $errors[] = $this->l('Your email or password is incorrect.'); + } + } else { + $errors[] = $error_curl; + } + } + } elseif (Tools::getIsset('debug_mode')) { + // toggle debug mode + self::updateConfiguration('PAYPLUG_DEBUG', !self::getConfiguration('PAYPLUG_DEBUG')); + Tools::redirectAdmin($this->_link.'&conf=4'); + } + + if (Configuration::get('PAYPLUG_MODULE_KEY') != '' + && Configuration::get('PAYPLUG_MODULE_PUBLIC_KEY') != '' + && Configuration::get('PAYPLUG_MODULE_URL') != '' + && Configuration::get('PAYPLUG_MODULE_MIN_AMOUNT') != '' + && Configuration::get('PAYPLUG_MODULE_MAX_AMOUNT') != '' + && Configuration::get('PAYPLUG_MODULE_CURRENCIES') != '') { + $this->assignForVersion( + array( + 'moduleInstalled' => true, + 'minAmount' => Configuration::get('PAYPLUG_MODULE_MIN_AMOUNT'), + 'maxAmount' => Configuration::get('PAYPLUG_MODULE_MAX_AMOUNT'), + 'currencies' => Configuration::get('PAYPLUG_MODULE_CURRENCIES'), + 'sandboxMode' => Payplug::getConfiguration('PAYPLUG_SANDBOX'), // Assign sandbox mode + 'debugMode' => Payplug::getConfiguration('PAYPLUG_DEBUG'), // assign debug mode + ) + ); + } + + // Assign datas + $datas = array( + 'this_path' => $this->_path, + 'displayForm' => $display_form, + 'errors' => $errors, + 'this_link' => $this->_link, + ); + + $this->assignForVersion($datas); + + return $this->display(__FILE__, './views/templates/admin/admin.tpl'); + } + + public function hookPayment() + { + $cart = $this->context->cart; + + $iso_code = $this->context->currency->iso_code; + $supported_currencies = explode(';', Configuration::get('PAYPLUG_MODULE_CURRENCIES')); + if (!in_array($iso_code, $supported_currencies)) { + return; + } + // Check amount + $amount = $cart->getOrderTotal(true, Cart::BOTH) * 100; + + if ($amount < Configuration::get('PAYPLUG_MODULE_MIN_AMOUNT') * 100 || $amount > Configuration::get('PAYPLUG_MODULE_MAX_AMOUNT') * 100) { + return; + } + + $this->assignForVersion('this_path', $this->_path); + $this->assignForVersion('iso_lang', $this->context->language->iso_code); + + // Different tpl depending version + if (version_compare(_PS_VERSION_, '1.6', '<')) { + if (version_compare(_PS_VERSION_, '1.5', '<')) { + return $this->display(__FILE__, './views/templates/hook/payment.tpl'); + } else { + return $this->display(__FILE__, 'payment.tpl'); + } + } else { + return $this->display(__FILE__, 'payment_16.tpl'); + } + } + + public function hookPaymentReturn() + { + if (!$this->active) { + return null; + } + $order_id = Tools::getValue('id_order'); + $order = new Order($order_id); + // Check order state to display appropriate message + $state = null; + if (isset($order->current_state) && $order->current_state == Configuration::get('PAYPLUG_ORDER_STATE_WAITING')) { + $state = 'waiting'; + } elseif (isset($order->current_state) && $order->current_state == Configuration::get('PAYPLUG_ORDER_STATE_PAID')) { + $state = 'paid'; + } elseif (isset($order->current_state) && $order->current_state == Configuration::get('PAYPLUG_ORDER_STATE_WAITING_TEST')) { + // if waiting_test state + $state = 'waiting_test'; + } elseif (isset($order->current_state) && $order->current_state == Configuration::get('PAYPLUG_ORDER_STATE_PAID_TEST')) { + // if paid_test state + $state = 'paid_test'; + } + + $this->assignForVersion('state', $state); + // Get order information for display + $total_paid = number_format($order->total_paid, 2, ',', ''); + $context = array('totalPaid' => $total_paid); + if (isset($order->reference)) { + $context['reference'] = $order->reference; + } + $this->assignForVersion($context); + if (version_compare(_PS_VERSION_, '1.5', '<')) { + return $this->display(__FILE__, './views/templates/hook/confirmation.tpl'); + } else { + return $this->display(__FILE__, 'confirmation.tpl'); + } + } + + /** + * Hook for 1.4 + */ + public function hookHeader() + { + if (version_compare(_PS_VERSION_, '1.6', '<')) { + return; + } + + $controller = $this->context->controller; + + if ($controller instanceof OrderOpcController || ($controller instanceof OrderController && $controller->step == 3)) { + $file = 'css/front.css'; + $this->context->controller->addCss($this->getLocalPath().$file); + } + } } diff --git a/upgrade/Upgrade-0.9.2.php b/upgrade/Upgrade-0.9.2.php index 9a4ed41..42e4a40 100644 --- a/upgrade/Upgrade-0.9.2.php +++ b/upgrade/Upgrade-0.9.2.php @@ -1,21 +1,46 @@ \ No newline at end of file + Payplug::updateConfiguration('PAYPLUG_ORDER_STATE_PAID', (int)$os_payment); + } + return true; // Return true if success. +} diff --git a/upgrade/Upgrade-0.9.7.php b/upgrade/Upgrade-0.9.7.php index c036004..974c9b3 100644 --- a/upgrade/Upgrade-0.9.7.php +++ b/upgrade/Upgrade-0.9.7.php @@ -1,21 +1,46 @@ createOrderState(); + Payplug::updateConfiguration('PAYPLUG_SANDBOX', '0'); - $module->registerHook('header'); + $install = new InstallPayplug(); + $install->createOrderState(); - $install->installPayplugLock(); + $module->registerHook('header'); - return true; // Return true if success. - } + $install->installPayplugLock(); -?> \ No newline at end of file + return true; // Return true if success. +} diff --git a/upgrade/index.php b/upgrade/index.php index 4f6e5df..0f9074a 100644 --- a/upgrade/index.php +++ b/upgrade/index.php @@ -1,6 +1,6 @@ - +
- logoPayPlug + logoPayPlug

{l s='The simplest online payment solution' mod='payplug'}

{l s='PayPlug provides small e-merchants all the benefits of a full online payment solution.' mod='payplug'}

diff --git a/views/templates/admin/index.php b/views/templates/admin/index.php index 4f6e5df..0f9074a 100755 --- a/views/templates/admin/index.php +++ b/views/templates/admin/index.php @@ -1,6 +1,6 @@ - {l s='VISA / MASTERCARD' mod='payplug'} + {l s='VISA / MASTERCARD' mod='payplug'} {l s='Credit card checkout' mod='payplug'}

diff --git a/views/templates/index.php b/views/templates/index.php index 4f6e5df..0f9074a 100755 --- a/views/templates/index.php +++ b/views/templates/index.php @@ -1,6 +1,6 @@