diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 36ba39fcd..000000000 Binary files a/.DS_Store and /dev/null differ diff --git a/conektapaymentsprestashop.php b/conektapaymentsprestashop.php index 4d1b8c715..c8c7473f6 100644 --- a/conektapaymentsprestashop.php +++ b/conektapaymentsprestashop.php @@ -30,6 +30,8 @@ } define("METADATA_LIMIT", 12); +define("CANCELLED_ID", 6); +define("REFUNDED_ID", 7); /** * ConektaPaymentsPrestashop Class Doc Comment @@ -89,6 +91,7 @@ public function __construct() 'TEST_PUBLIC_KEY', 'LIVE_PRIVATE_KEY', 'LIVE_PUBLIC_KEY', + 'PRE_AUTHORIZE_CONEKTA', 'CHARGE_ON_DEMAND_ENABLE', '3DS_FORCE' ); @@ -155,6 +158,10 @@ public function __construct() $this->live_public_key = $config['LIVE_PUBLIC_KEY']; } + if (isset($config['PRE_AUTHORIZE_CONEKTA'])) { + $this->pre_authorize = $config['PRE_AUTHORIZE_CONEKTA']; + } + if (isset($config['CHARGE_ON_DEMAND_ENABLE'])) { $this->charge_on_demand = $config['CHARGE_ON_DEMAND_ENABLE']; } @@ -209,6 +216,7 @@ public function install() || !$this->registerHook('paymentReturn') || !$this->registerHook('adminOrder') || !$this->registerHook('updateOrderStatus') + || !$this->registerHook('actionValidateOrder') && Configuration::updateValue('PAYMENT_METHS_CARD', 1) && Configuration::updateValue('PAYMENT_METHS_INSTALLMET', 1) && Configuration::updateValue('PAYMENT_METHS_CASH', 1) @@ -224,6 +232,36 @@ public function install() return true; } + /** + * Adding the reference code of the Conekta order to the order generated by Prestashop. + * + * @param array $params Array with order data + * + * @return boolean + */ + public function hookActionValidateOrder($params) + { + + $key = Configuration::get('CONEKTA_MODE') ? + Configuration::get('CONEKTA_PRIVATE_KEY_LIVE') : Configuration::get('CONEKTA_PRIVATE_KEY_TEST'); + $iso_code = $this->context->language->iso_code; + + \Conekta\Conekta::setApiKey($key); + \Conekta\Conekta::setPlugin("Prestashop 1.7"); + \Conekta\Conekta::setApiVersion("2.0.0"); + \Conekta\Conekta::setPluginVersion($this->version); + \Conekta\Conekta::setLocale($iso_code); + + if (!empty(filter_input(INPUT_GET, 'conektaOrdenID'))) { + try { + $order = \Conekta\Order::find(filter_input(INPUT_GET, 'conektaOrdenID')); + $params['order']->reference = $order->metadata['reference_id']; + return true; + } catch (\Exception $e) { + return false; + } + } + } /** * Delete configuration and drop table in database. * @@ -323,8 +361,7 @@ public function hookPaymentReturn($params) */ public function hookUpdateOrderStatus($params) { - if ($params['newOrderStatus']->id == 7) { - //order refunded + if ($params['newOrderStatus']->id == CANCELLED_ID || $params['newOrderStatus']->id == REFUNDED_ID) { $key = Configuration::get('CONEKTA_MODE') ? Configuration::get('CONEKTA_PRIVATE_KEY_LIVE') : Configuration::get('CONEKTA_PRIVATE_KEY_TEST'); @@ -341,12 +378,19 @@ public function hookUpdateOrderStatus($params) $conekta_tran_details = Database::getOrderById($id_order); //only credit card refund - if (!$conekta_tran_details['barcode'] + if (!empty($conekta_tran_details) + && !$conekta_tran_details['barcode'] && !(isset($conekta_tran_details['reference']) && !empty($conekta_tran_details['reference'])) ) { $order = \Conekta\Order::find($conekta_tran_details['id_conekta_order']); - $order->refund(['reason' => 'requested_by_client']); + if (!empty($order) && $order->charges[0]->payment_method->object == "card_payment") { + if ($order->payment_status == 'pre_authorized') { + $order->void(); + } else { + $order->refund(['reason' => 'requested_by_client']); + } + } } } } @@ -473,14 +517,21 @@ private function createPendingSpeiState() */ public function hookHeader() { - $key = Configuration::get('CONEKTA_MODE') ? Configuration::get('CONEKTA_PRIVATE_KEY_LIVE') : Configuration::get('CONEKTA_PRIVATE_KEY_TEST'); + $key = Configuration::get('CONEKTA_MODE') ? + Configuration::get('CONEKTA_PRIVATE_KEY_LIVE') : Configuration::get('CONEKTA_PRIVATE_KEY_TEST'); $iso_code = $this->context->language->iso_code; \Conekta\Conekta::setApiKey($key); \Conekta\Conekta::setPlugin("Prestashop1.7"); \Conekta\Conekta::setApiVersion("2.0.0"); \Conekta\Conekta::setLocale($iso_code); - if (Tools::getValue('controller') != 'order-opc' && (!($_SERVER['PHP_SELF'] == __PS_BASE_URI__ . 'order.php' || $_SERVER['PHP_SELF'] == __PS_BASE_URI__ . 'order-opc.php' || Tools::getValue('controller') == 'order' || Tools::getValue('controller') == 'orderopc' || Tools::getValue('step') == 3))) { + if (Tools::getValue('controller') != 'order-opc' + && (!($_SERVER['PHP_SELF'] == __PS_BASE_URI__ . 'order.php' + || $_SERVER['PHP_SELF'] == __PS_BASE_URI__ . 'order-opc.php' + || Tools::getValue('controller') == 'order' + || Tools::getValue('controller') == 'orderopc' + || Tools::getValue('step') == 3)) + ) { return; } Media::addJsDef( @@ -499,7 +550,8 @@ public function hookHeader() $this->smarty->assign("path", $this->_path); $cart = $this->context->cart; - $customer = $this->context->customer; + $customerPrestashop = $this->context->customer; + $address_delivery = new Address((int) $cart->id_address_delivery); $payment_options = array(); if (Configuration::get('PAYMENT_METHS_SPEI')) { @@ -514,10 +566,9 @@ public function hookHeader() array_push($payment_options, 'card'); } - // $msi = false; + $pre_authorize = false; $force_3ds = false; $on_demand_enabled = false; - $address_delivery = new Address((int) $cart->id_address_delivery); $state = State::getNameById($address_delivery->id_state); $country = Country::getIsoById($address_delivery->id_country); $carrier = new Carrier((int) $cart->id_carrier); @@ -528,36 +579,33 @@ public function hookHeader() $items = $cart->getProducts(); $shippingLines = null; $shippingContact = null; - + if (isset($carrier)) { if ($carrier->name != null) { $shp_carrier = $carrier->name; $shp_service = implode(",", $carrier->delay); $shippingLines = Config::getShippingLines($shp_service, $shp_carrier, $shp_price); + } elseif ($this->isDigital($items)) { + $shp_carrier = "Producto digital"; + $shp_service = "Digital"; + $shippingLines = Config::getShippingLines($shp_service, $shp_carrier, $shp_price); } } - - $shippingContact = Config::getShippingContact($customer, $address_delivery, $state, $country); - $customerInfo = Config::getCustomerInfo($customer); - $result = Database::getConektaMetadata($customer->id, $this->conekta_mode, "conekta_customer_id"); + $shippingContact = Config::getShippingContact($customerPrestashop, $address_delivery, $state, $country); + $customerInfo = Config::getCustomerInfo($customerPrestashop, $address_delivery); - if (count($payment_options) > 0 && !empty($shippingContact['address']['postal_code']) && !empty($shippingLines)) { + if (count($payment_options) > 0 + && !empty($shippingContact['address']['postal_code']) + && !empty($shippingLines) + ) { $order_details = array(); $taxlines = array(); - if (empty($result['meta_value'])) { - $customer_id = $this->createCustomer($customer, $customerInfo); - } else { - $customer_id = $result['meta_value']; - $customerConekta = \Conekta\Customer::find($customer_id); - $customerConekta->update($customerInfo); + if (Configuration::get('PRE_AUTHORIZE_CONEKTA')) { + $pre_authorize = true; } - if ((Configuration::get('PAYMENT_METHS_INSTALLMET'))) { - $msi = true; - } - if (Configuration::get('CHARGE_ON_DEMAND_ENABLE')) { $on_demand_enabled = true; } @@ -576,28 +624,33 @@ public function hookHeader() ]; if (in_array('cash', $payment_options)) { - $checkout["expires_at"] = time() + (Configuration::get('EXPIRATION_DATE_LIMIT') * (Configuration::get('EXPIRATION_DATE_TYPE') == 0 ? 86400 : 3600)); + $checkout["expires_at"] = time() + + (Configuration::get('EXPIRATION_DATE_LIMIT') * + (Configuration::get('EXPIRATION_DATE_TYPE') == 0 ? 86400 : 3600)); } $order_details = [ 'currency' => $this->context->currency->iso_code, 'line_items' => Config::getLineItems($items), - 'customer_info' => array("customer_id" => $customer_id), + 'customer_info' => array(), 'discount_lines' => Config::getDiscountLines($discounts), 'shipping_lines' => array(), 'shipping_contact' => $shippingContact, + 'pre_authorize' => $pre_authorize, 'tax_lines' => array(), 'metadata' => [ "plugin" => "Prestashop", "plugin_version" => _PS_VERSION_, - "reference_id" => $this->context->cart->id + "reference_id" => Order::generateReference() ], 'checkout' => $checkout ]; $order_elements = array_keys(get_class_vars('Cart')); foreach ($order_elements as $element) { - if (!empty(Configuration::get('ORDER_'.Tools::strtoupper($element))) && property_exists($this->context->cart, $element)) { + if (!empty(Configuration::get('ORDER_'.Tools::strtoupper($element))) + && property_exists($this->context->cart, $element) + ) { $order_details['metadata'][$element] = $this->context->cart->$element; } } @@ -656,11 +709,17 @@ public function hookHeader() } } - $result = Database::getConektaOrder($customer->id, $this->conekta_mode, $this->context->cart->id); - try { - if ($order_details['currency'] == 'MXN' && $amount < $this->amount_min) { - $message = "El monto minimo de compra con Conekta tiene que ser mayor a $20.00 "; + // Validate, create and update the customer in conekta + + $cust_db = Database::getConektaMetadata( + $customerPrestashop->id, + $this->conekta_mode, + "conekta_customer_id" + ); + + $message = $this->checkedFields($customerInfo['phone'], $order_details, $amount); + if ($message !== true) { $this->context->smarty->assign( array( 'message' => $message, @@ -668,29 +727,83 @@ public function hookHeader() ); return false; } - if (isset($result) && $result['status'] == 'unpaid') { - $order = \Conekta\Order::find($result['id_conekta_order']); - - if (isset($order->charges[0]->status) && $order->charges[0]->status == 'paid') { - Database::updateConektaOrder($customer->id, $this->context->cart->id, $this->conekta_mode, $order->id, $order->charges[0]->status); + + if (empty($cust_db['meta_value'])) { + $customerConekta = \conekta\Customer::create($customerInfo); + $customerConekta_id = $customerConekta->id; + Database::updateConektaMetadata( + $customerPrestashop->id, + $this->conekta_mode, + "conekta_customer_id", + $customerConekta_id + ); + } else { + $customerConekta_id = $cust_db['meta_value']; + $customerConekta = \Conekta\Customer::find($customerConekta_id); + $customerConekta->update($customerInfo); + } + + $order_details['customer_info'] = array("customer_id" => $customerConekta_id); + + // Validate, create and update the order in Conekta + + $ord_db = Database::getConektaOrder( + $customerPrestashop->id, + $this->conekta_mode, + $this->context->cart->id + ); + + if (isset($ord_db) && $ord_db['status'] == 'unpaid') { + $order = \Conekta\Order::find($ord_db['id_conekta_order']); + + if (isset($order->charges[0]->status) && $order->charges[0]->status != 'unpaid') { + Database::updateConektaOrder( + $customerPrestashop->id, + $this->context->cart->id, + $this->conekta_mode, + $order->id, + $order->charges[0]->status + ); } } if (empty($order)) { $order = \Conekta\Order::create($order_details); - Database::updateConektaOrder($customer->id, $this->context->cart->id, $this->conekta_mode, $order->id, 'unpaid'); - } elseif (empty($order->charges[0]->status) || $order->charges[0]->status != 'paid') { + Database::updateConektaOrder( + $customerPrestashop->id, + $this->context->cart->id, + $this->conekta_mode, + $order->id, + 'unpaid' + ); + } elseif (empty($order->charges[0]->status) || $order->charges[0]->status == 'unpaid') { + $order->update([ + 'customer_info' => $customerInfo + ]); unset($order_details['customer_info']); $order->update($order_details); } else { $order = \Conekta\Order::create($order_details); - Database::updateConektaOrder($customer->id, $this->context->cart->id, $this->conekta_mode, $order->id, 'unpaid'); + Database::updateConektaOrder( + $customerPrestashop->id, + $this->context->cart->id, + $this->conekta_mode, + $order->id, + 'unpaid' + ); } } catch (\Exception $e) { $log_message = $e->getMessage() . ' '; if (class_exists('Logger')) { - Logger::addLog($this->l('Payment transaction failed') . ' ' . $log_message, 2, null, 'Cart', (int) $this->context->cart->id, true); + Logger::addLog( + $this->l('Payment transaction failed') . ' ' . $log_message, + 2, + null, + 'Cart', + (int) $this->context->cart->id, + true + ); } $message = $e->getMessage() . ' '; @@ -829,8 +942,16 @@ public function checkCurrency($cart) public function getConektaPaymentOption() { $embeddedOption = new PaymentOption(); - $embeddedOption->setModuleName($this->name)->setCallToActionText($this->l('Pago por medio de Conekta '))->setAction($this->context->link->getModuleLink($this->name, 'validation', array(), true))->setForm($this->generateCardPaymentForm())->setLogo(Media::getMediaPath(_PS_MODULE_DIR_ . $this->name . '/views/img/cards2.png')); - + $embeddedOption->setModuleName($this->name)->setCallToActionText( + $this->l('Pago por medio de Conekta ') + )->setAction($this->context->link->getModuleLink( + $this->name, + 'validation', + array(), + true + ))->setForm($this->generateCardPaymentForm())->setLogo( + Media::getMediaPath(_PS_MODULE_DIR_ . $this->name . '/views/img/cards2.png') + ); return $embeddedOption; } @@ -843,23 +964,55 @@ private function postValidation() { if (Tools::isSubmit('btnSubmit')) { if (!Tools::getValue('PAYEE_NAME')) { - $this->postErrors[] = $this->trans('The "Payee" field is required.', array(), 'Modules.ConektaPaymentsPrestashop.Admin'); + $this->postErrors[] = $this->trans( + 'The "Payee" field is required.', + array(), + 'Modules.ConektaPaymentsPrestashop.Admin' + ); } elseif (!Tools::getValue('PAYEE_ADDRESS')) { - $this->postErrors[] = $this->trans('The "Address" field is required.', array(), 'Modules.ConektaPaymentsPrestashop.Admin'); + $this->postErrors[] = $this->trans( + 'The "Address" field is required.', + array(), + 'Modules.ConektaPaymentsPrestashop.Admin' + ); } if (!Tools::getValue('WEB_HOOK')) { - $this->postErrors[] = $this->trans('The "Web Hook" field is required.', array(), 'Modules.ConektaPaymentsPrestashop.Admin'); + $this->postErrors[] = $this->trans( + 'The "Web Hook" field is required.', + array(), + 'Modules.ConektaPaymentsPrestashop.Admin' + ); } - if (Tools::getValue('PAYMENT_METHS_CASH') && !Tools::getValue('EXPIRATION_DATE_LIMIT')) { - $this->postErrors[] = $this->trans('The "Expiration date limit" field is required.', array(), 'Modules.ConektaPaymentsPrestashop.Admin'); + $this->postErrors[] = $this->trans( + 'The "Expiration date limit" field is required.', + array(), + 'Modules.ConektaPaymentsPrestashop.Admin' + ); } - if (Tools::getValue('PAYMENT_METHS_CASH') && ( (Tools::getValue('EXPIRATION_DATE_TYPE')==0 && (Tools::getValue('EXPIRATION_DATE_LIMIT')<0 || Tools::getValue('EXPIRATION_DATE_LIMIT')>31)) || (Tools::getValue('EXPIRATION_DATE_TYPE')==1 && (Tools::getValue('EXPIRATION_DATE_LIMIT')<0 || Tools::getValue('EXPIRATION_DATE_LIMIT')>24)) )) { - $this->postErrors[] = $this->trans('The "Expiration date limit" is out of range.', array(), 'Modules.ConektaPaymentsPrestashop.Admin'); + + if (Tools::getValue('PAYMENT_METHS_CASH') + && ( (Tools::getValue('EXPIRATION_DATE_TYPE')==0 + && (Tools::getValue('EXPIRATION_DATE_LIMIT')<0 + || Tools::getValue('EXPIRATION_DATE_LIMIT')>31)) + || (Tools::getValue('EXPIRATION_DATE_TYPE')==1 + && (Tools::getValue('EXPIRATION_DATE_LIMIT')<0 + || Tools::getValue('EXPIRATION_DATE_LIMIT')>24)) + )) { + $this->postErrors[] = $this->trans( + 'The "Expiration date limit" is out of range.', + array(), + 'Modules.ConektaPaymentsPrestashop.Admin' + ); } + if (Tools::getValue('PAYMENT_METHS_CASH') && !is_numeric(Tools::getValue('EXPIRATION_DATE_LIMIT'))) { - $this->postErrors[] = $this->trans('The "Expiration date limit" must be a number.', array(), 'Modules.ConektaPaymentsPrestashop.Admin'); + $this->postErrors[] = $this->trans( + 'The "Expiration date limit" must be a number.', + array(), + 'Modules.ConektaPaymentsPrestashop.Admin' + ); } $order_elements = array_keys(get_class_vars('Cart')); @@ -879,24 +1032,45 @@ private function postValidation() } $i++; } + if ($attributes_count > METADATA_LIMIT) { - $this->postErrors[] = $this->trans('No more than 12 attributes can be sent as metadata', array(), 'Modules.ConektaPaymentsPrestashop.Admin'); + $this->postErrors[] = $this->trans( + 'No more than '. METADATA_LIMIT .' attributes can be sent as metadata', + array(), + 'Modules.ConektaPaymentsPrestashop.Admin' + ); } if (!Tools::getValue('TEST_PRIVATE_KEY')) { - $this->postErrors[] = $this->trans('The "Test Private Key" field is required.', array(), 'Modules.ConektaPaymentsPrestashop.Admin'); + $this->postErrors[] = $this->trans( + 'The "Test Private Key" field is required.', + array(), + 'Modules.ConektaPaymentsPrestashop.Admin' + ); } if (!Tools::getValue('TEST_PUBLIC_KEY')) { - $this->postErrors[] = $this->trans('The "Test Public Key" field is required.', array(), 'Modules.ConektaPaymentsPrestashop.Admin'); + $this->postErrors[] = $this->trans( + 'The "Test Public Key" field is required.', + array(), + 'Modules.ConektaPaymentsPrestashop.Admin' + ); } if (Tools::getValue('LIVE_PRIVATE_KEY') && !Tools::getValue('LIVE_PUBLIC_KEY')) { - $this->postErrors[] = $this->trans('The "Live Public Key" field is required.', array(), 'Modules.ConektaPaymentsPrestashop.Admin'); + $this->postErrors[] = $this->trans( + 'The "Live Public Key" field is required.', + array(), + 'Modules.ConektaPaymentsPrestashop.Admin' + ); } if (!Tools::getValue('LIVE_PRIVATE_KEY') && Tools::getValue('LIVE_PUBLIC_KEY')) { - $this->postErrors[] = $this->trans('The "Live Private Key" field is required.', array(), 'Modules.ConektaPaymentsPrestashop.Admin'); + $this->postErrors[] = $this->trans( + 'The "Live Private Key" field is required.', + array(), + 'Modules.ConektaPaymentsPrestashop.Admin' + ); } } } @@ -916,28 +1090,52 @@ private function postProcess() Configuration::updateValue('PAYMENT_METHS_CARD', Tools::getValue('PAYMENT_METHS_CARD')); Configuration::updateValue('PAYMENT_METHS_INSTALLMET', Tools::getValue('PAYMENT_METHS_INSTALLMET')); Configuration::updateValue('PAYMENT_METHS_CASH', Tools::getValue('PAYMENT_METHS_CASH')); - Configuration::updateValue('PAYMENT_METHS_BANORTE', Tools::getValue('PAYMENT_METHS_BANORTE')); + Configuration::updateValue( + 'PAYMENT_METHS_BANORTE', + Tools::getValue('PAYMENT_METHS_BANORTE') + ); Configuration::updateValue('PAYMENT_METHS_SPEI', Tools::getValue('PAYMENT_METHS_SPEI')); Configuration::updateValue('EXPIRATION_DATE_TYPE', Tools::getValue('EXPIRATION_DATE_TYPE')); - Configuration::updateValue('EXPIRATION_DATE_LIMIT', Tools::getValue('EXPIRATION_DATE_LIMIT')); - Configuration::updateValue('TEST_PRIVATE_KEY', Tools::getValue('TEST_PRIVATE_KEY')); - Configuration::updateValue('TEST_PUBLIC_KEY', Tools::getValue('TEST_PUBLIC_KEY')); - Configuration::updateValue('LIVE_PRIVATE_KEY', Tools::getValue('LIVE_PRIVATE_KEY')); - Configuration::updateValue('LIVE_PUBLIC_KEY', Tools::getValue('LIVE_PUBLIC_KEY')); + Configuration::updateValue( + 'EXPIRATION_DATE_LIMIT', + Tools::getValue('EXPIRATION_DATE_LIMIT') + ); + Configuration::updateValue( + 'PRE_AUTHORIZE_CONEKTA', + Tools::getValue('PRE_AUTHORIZE_CONEKTA') + ); Configuration::updateValue('CHARGE_ON_DEMAND_ENABLE', Tools::getValue('CHARGE_ON_DEMAND_ENABLE')); Configuration::updateValue('3DS_FORCE', Tools::getValue('3DS_FORCE')); + + if (Tools::getValue('TEST_PUBLIC_KEY') && Tools::getValue('TEST_PRIVATE_KEY')) { + Configuration::updateValue('TEST_PRIVATE_KEY', Tools::getValue('TEST_PRIVATE_KEY')); + Configuration::updateValue('TEST_PUBLIC_KEY', Tools::getValue('TEST_PUBLIC_KEY')); + } + + if (Tools::getValue('LIVE_PUBLIC_KEY') && Tools::getValue('LIVE_PUBLIC_KEY')) { + Configuration::updateValue('LIVE_PRIVATE_KEY', Tools::getValue('LIVE_PRIVATE_KEY')); + Configuration::updateValue('LIVE_PUBLIC_KEY', Tools::getValue('LIVE_PUBLIC_KEY')); + } $order_elements = array_keys(get_class_vars('Cart')); foreach ($order_elements as $element) { - Configuration::updateValue('ORDER_'.Tools::strtoupper($element), Tools::getValue('ORDER_'.Tools::strtoupper($element))); + Configuration::updateValue( + 'ORDER_'.Tools::strtoupper($element), + Tools::getValue('ORDER_'.Tools::strtoupper($element)) + ); } $product_elements = self::CART_PRODUCT_ATTR; foreach ($product_elements as $element) { - Configuration::updateValue('PRODUCT_'.Tools::strtoupper($element), Tools::getValue('PRODUCT_'.Tools::strtoupper($element))); + Configuration::updateValue( + 'PRODUCT_'.Tools::strtoupper($element), + Tools::getValue('PRODUCT_'.Tools::strtoupper($element)) + ); } } - $this->html .= $this->displayConfirmation($this->trans('Settings updated', array(), 'Admin.Notifications.Success')); + $this->html .= $this->displayConfirmation( + $this->trans('Settings updated', array(), 'Admin.Notifications.Success') + ); } /** @@ -963,17 +1161,36 @@ public function getConfigFieldsValues() 'MODE' => Tools::getValue('MODE', Configuration::get('MODE')), 'WEB_HOOK' => Tools::getValue('WEB_HOOK', Configuration::get('WEB_HOOK')), 'PAYMENT_METHS_CARD' => Tools::getValue('PAYMENT_METHS_CARD', Configuration::get('PAYMENT_METHS_CARD')), - 'PAYMENT_METHS_INSTALLMET' => Tools::getValue('PAYMENT_METHS_INSTALLMET', Configuration::get('PAYMENT_METHS_INSTALLMET')), + 'PAYMENT_METHS_INSTALLMET' => Tools::getValue( + 'PAYMENT_METHS_INSTALLMET', + Configuration::get('PAYMENT_METHS_INSTALLMET') + ), 'PAYMENT_METHS_CASH' => Tools::getValue('PAYMENT_METHS_CASH', Configuration::get('PAYMENT_METHS_CASH')), - 'PAYMENT_METHS_BANORTE' => Tools::getValue('PAYMENT_METHS_BANORTE', Configuration::get('PAYMENT_METHS_BANORTE')), + 'PAYMENT_METHS_BANORTE' => Tools::getValue( + 'PAYMENT_METHS_BANORTE', + Configuration::get('PAYMENT_METHS_BANORTE') + ), 'PAYMENT_METHS_SPEI' => Tools::getValue('PAYMENT_METHS_SPEI', Configuration::get('PAYMENT_METHS_SPEI')), - 'EXPIRATION_DATE_TYPE' => Tools::getValue('EXPIRATION_DATE_TYPE', Configuration::get('EXPIRATION_DATE_TYPE')), - 'EXPIRATION_DATE_LIMIT' => Tools::getValue('EXPIRATION_DATE_LIMIT', Configuration::get('EXPIRATION_DATE_LIMIT')), + 'EXPIRATION_DATE_TYPE' => Tools::getValue( + 'EXPIRATION_DATE_TYPE', + Configuration::get('EXPIRATION_DATE_TYPE') + ), + 'EXPIRATION_DATE_LIMIT' => Tools::getValue( + 'EXPIRATION_DATE_LIMIT', + Configuration::get('EXPIRATION_DATE_LIMIT') + ), 'TEST_PRIVATE_KEY' => Tools::getValue('TEST_PRIVATE_KEY', Configuration::get('TEST_PRIVATE_KEY')), 'TEST_PUBLIC_KEY' => Tools::getValue('TEST_PUBLIC_KEY', Configuration::get('TEST_PUBLIC_KEY')), 'LIVE_PRIVATE_KEY' => Tools::getValue('LIVE_PRIVATE_KEY', Configuration::get('LIVE_PRIVATE_KEY')), 'LIVE_PUBLIC_KEY' => Tools::getValue('LIVE_PUBLIC_KEY', Configuration::get('LIVE_PUBLIC_KEY')), - 'CHARGE_ON_DEMAND_ENABLE' => Tools::getValue('CHARGE_ON_DEMAND_ENABLE', Configuration::get('CHARGE_ON_DEMAND_ENABLE')), + 'PRE_AUTHORIZE_CONEKTA' => Tools::getValue( + 'PRE_AUTHORIZE_CONEKTA', + Configuration::get('PRE_AUTHORIZE_CONEKTA') + ), + 'CHARGE_ON_DEMAND_ENABLE' => Tools::getValue( + 'CHARGE_ON_DEMAND_ENABLE', + Configuration::get('CHARGE_ON_DEMAND_ENABLE') + ), '3DS_FORCE' => Tools::getValue('3DS_FORCE', Configuration::get('3DS_FORCE')) ); $order_elements = array_keys(get_class_vars('Cart')); @@ -988,7 +1205,21 @@ public function getConfigFieldsValues() return $ret; } - const CART_PRODUCT_ATTR = array("id_product_attribute", "id_product", "cart_quantity", "id_shop", "id_customization", "name", "is_virtual", "description_short", "available_now", "available_later", "id_category_default", "id_supplier", "id_manufacturer", "manufacturer_name", "on_sale", "ecotax", "additional_shipping_cost", "available_for_order", "show_price", "price", "active", "unity", "unit_price_ratio", "quantity_available", "width", "height", "depth", "out_of_stock", "weight", "available_date", "date_add", "date_upd", "quantity", "link_rewrite", "category", "unique_id", "id_address_delivery", "advanced_stock_management", "supplier_reference", "customization_quantity", "price_attribute", "ecotax_attr", "reference", "weight_attribute", "ean13", "isbn", "upc", "minimal_quantity", "wholesale_price", "id_image", "legend", "reduction_type", "is_gift", "reduction", "reduction_without_tax", "price_without_reduction", "attributes", "attributes_small", "rate", "tax_name", "stock_quantity", "price_without_reduction_without_tax", "price_with_reduction", "price_with_reduction_without_tax", "total", "total_wt", "price_wt", "reduction_applies", "quantity_discount_applies", "allow_oosp"); + const CART_PRODUCT_ATTR = array( + "id_product_attribute", "id_product", "cart_quantity", "id_shop", "id_customization", "name", + "is_virtual", "description_short", "available_now", "available_later", "id_category_default", + "id_supplier", "id_manufacturer", "manufacturer_name", "on_sale", "ecotax", + "additional_shipping_cost", "available_for_order", "show_price", "price", "active", + "unity", "unit_price_ratio", "quantity_available", "width", "height", "depth", + "out_of_stock", "weight", "available_date", "date_add", "date_upd", "quantity", + "link_rewrite", "category", "unique_id", "id_address_delivery", "advanced_stock_management", + "supplier_reference", "customization_quantity", "price_attribute", "ecotax_attr", "reference", + "weight_attribute", "ean13", "isbn", "upc", "minimal_quantity", "wholesale_price", "id_image", + "legend", "reduction_type", "is_gift", "reduction", "reduction_without_tax", "price_without_reduction", + "attributes", "attributes_small", "rate", "tax_name", "stock_quantity", "price_without_reduction_without_tax", + "price_with_reduction", "price_with_reduction_without_tax", "total", "total_wt", "price_wt", + "reduction_applies", "quantity_discount_applies", "allow_oosp" + ); /** * Build Admin Content @@ -998,7 +1229,12 @@ public function getConfigFieldsValues() public function buildAdminContent() { $this->context->controller->addJS($this->_path . 'views/js/functions.js'); - $order_elements = array_keys(array_diff_key(get_class_vars('Cart'), array('definition' => '', 'htmlFields' => ''))); + $order_elements = array_keys( + array_diff_key( + get_class_vars('Cart'), + array('definition' => '', 'htmlFields' => '') + ) + ); sort($order_elements); $order_meta = array(); foreach ($order_elements as $val) { @@ -1021,20 +1257,36 @@ public function buildAdminContent() $fields_form = array( 'form' => array( 'legend' => array( - 'title' => $this->trans('Contact details', array(), 'Modules.ConektaPaymentsPrestashop.Admin'), + 'title' => $this->trans( + 'Contact details', + array(), + 'Modules.ConektaPaymentsPrestashop.Admin' + ), 'icon' => 'icon-envelope' ), 'input' => array( array( 'type' => 'text', - 'label' => $this->trans('Payee (name)', array(), 'Modules.ConektaPaymentsPrestashop.Admin'), + 'label' => $this->trans( + 'Payee (name)', + array(), + 'Modules.ConektaPaymentsPrestashop.Admin' + ), 'name' => 'PAYEE_NAME', 'required' => true ), array( 'type' => 'textarea', - 'label' => $this->trans('Address', array(), 'Modules.ConektaPaymentsPrestashop.Admin'), - 'desc' => $this->trans('Address where the check should be sent to.', array(), 'Modules.ConektaPaymentsPrestashop.Admin'), + 'label' => $this->trans( + 'Address', + array(), + 'Modules.ConektaPaymentsPrestashop.Admin' + ), + 'desc' => $this->trans( + 'Address where the check should be sent to.', + array(), + 'Modules.ConektaPaymentsPrestashop.Admin' + ), 'name' => 'PAYEE_ADDRESS', 'required' => true ), @@ -1064,7 +1316,11 @@ public function buildAdminContent() 'values' => array( 'query' => array( array( 'id' => 'CARD', 'name' => $this->l('Card'), 'val' => 'card_payment_method'), - array( 'id' => 'INSTALLMET', 'name' => $this->l('Monthly Installents'), 'val' => 'installment_payment_method' ), + array( + 'id' => 'INSTALLMET', + 'name' => $this->l('Monthly Installents'), + 'val' => 'installment_payment_method' + ), array( 'id' => 'CASH', 'name' => $this->l('Cash'), 'val' => 'cash_payment_method' ), array( 'id' => 'SPEI', 'name' => $this->l('SPEI'), 'val' => 'spei_payment_method' ) ), @@ -1091,33 +1347,13 @@ public function buildAdminContent() ), array( 'type' => 'text', - 'label' => $this->trans('Expiration date limit', array(), 'Modules.ConektaPaymentsPrestashop.Admin'), + 'label' => $this->trans( + 'Expiration date limit', + array(), + 'Modules.ConektaPaymentsPrestashop.Admin' + ), 'name' => 'EXPIRATION_DATE_LIMIT', ), - array( - 'type' => 'text', - 'label' => $this->trans('Test Private Key', array(), 'Modules.ConektaPaymentsPrestashop.Admin'), - 'name' => 'TEST_PRIVATE_KEY', - 'required' => true - ), - array( - 'type' => 'text', - 'label' => $this->trans('Test Public Key', array(), 'Modules.ConektaPaymentsPrestashop.Admin'), - 'name' => 'TEST_PUBLIC_KEY', - 'required' => true - ), - array( - 'type' => 'password', - 'label' => $this->trans('Live Private Key', array(), 'Modules.ConektaPaymentsPrestashop.Admin'), - 'name' => 'LIVE_PRIVATE_KEY', - 'required' => true - ), - array( - 'type' => 'password', - 'label' => $this->trans('Live Public Key', array(), 'Modules.ConektaPaymentsPrestashop.Admin'), - 'name' => 'LIVE_PUBLIC_KEY', - 'required' => true - ), array( 'type' => 'checkbox', 'label' => $this->l('Additional Order Metadata'), @@ -1193,14 +1429,75 @@ public function buildAdminContent() 'id' => 'id', 'name' => 'name', ) + ), + array( + 'type' => 'checkbox', + 'label' => $this->l('Preauthorize'), + 'name' => 'PRE_AUTHORIZE', + 'values' => array( + 'query' => array( + array( + 'id' => 'CONEKTA', + 'name' => $this->l('Enable Preauthorization'), + 'val' => 'pre_authorize' + ), + ), + 'id' => 'id', + 'name' => 'name', + ) ) + ) + ) + ); + return $fields_form; + } + + /** + * Build the content of the fields of the keys + * + * @return array + */ + public function buildAdminContentKey() + { + $this->context->controller->addJS($this->_path . 'views/js/functions.js'); + $fields_form_keys = array( + 'form' => array( + 'legend' => array( + 'title' => $this->trans('KEYS', array(), 'Modules.ConektaPaymentsPrestashop.Admin'), + 'icon' => 'icon-key' + ), + 'input' => array( + array( + 'type' => 'text', + 'label' => $this->trans('Test Private Key', array(), 'Modules.ConektaPaymentsPrestashop.Admin'), + 'name' => 'TEST_PRIVATE_KEY', + 'required' => true + ), + array( + 'type' => 'text', + 'label' => $this->trans('Test Public Key', array(), 'Modules.ConektaPaymentsPrestashop.Admin'), + 'name' => 'TEST_PUBLIC_KEY', + 'required' => true, + ), + array( + 'type' => 'password', + 'label' => $this->trans('Live Private Key', array(), 'Modules.ConektaPaymentsPrestashop.Admin'), + 'name' => 'LIVE_PRIVATE_KEY', + 'required' => true + ), + array( + 'type' => 'password', + 'label' => $this->trans('Live Public Key', array(), 'Modules.ConektaPaymentsPrestashop.Admin'), + 'name' => 'LIVE_PUBLIC_KEY', + 'required' => true + ), ), 'submit' => array( - 'title' => $this->trans('Save', array(), 'Admin.Actions') + 'title' => $this->trans('Save All', array(), 'Admin.Actions') ) ) ); - return $fields_form; + return $fields_form_keys; } /** @@ -1211,16 +1508,19 @@ public function buildAdminContent() public function renderForm() { $fields_form = $this->buildAdminContent(); + $fields_form_keys = $this->buildAdminContentKey(); $helper = new HelperForm(); $helper->show_toolbar = false; $helper->id = (int) Tools::getValue('id_carrier'); $helper->identifier = $this->identifier; $helper->submit_action = 'btnSubmit'; - $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false) . '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name; + $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false) + . '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name; $helper->token = Tools::getAdminTokenLite('AdminModules'); $helper->tpl_vars = array( 'fields_value' => $this->getConfigFieldsValues() ); $this->fields_form = array(); - return $helper->generateForm(array( $fields_form )); + $this->fields_form_keys = array(); + return $helper->generateForm(array( $fields_form, $fields_form_keys )); } /** @@ -1239,9 +1539,11 @@ public function checkSettings($mode = 'global') $valid = false; if ($mode) { - $valid = Configuration::get('CONEKTA_PUBLIC_KEY_LIVE') != '' && Configuration::get('CONEKTA_PRIVATE_KEY_LIVE') != ''; + $valid = Configuration::get('CONEKTA_PUBLIC_KEY_LIVE') != '' + && Configuration::get('CONEKTA_PRIVATE_KEY_LIVE') != ''; } else { - $valid = Configuration::get('CONEKTA_PUBLIC_KEY_TEST') != '' && Configuration::get('CONEKTA_PRIVATE_KEY_TEST') != ''; + $valid = Configuration::get('CONEKTA_PUBLIC_KEY_TEST') != '' + && Configuration::get('CONEKTA_PRIVATE_KEY_TEST') != ''; } return $valid; @@ -1266,7 +1568,9 @@ public function checkRequirements() if (Configuration::get('CONEKTA_MODE')) { $tests['ssl'] = array( 'name' => $this->l('SSL must be enabled on your store (before entering Live mode)'), - 'result' => (integer) Configuration::get('PS_SSL_ENABLED') || (!empty(filter_input(INPUT_SERVER, 'HTTPS')) && Tools::strtolower(filter_input(INPUT_SERVER, 'HTTPS')) != 'off') + 'result' => ((integer) Configuration::get('PS_SSL_ENABLED') + || (!empty(filter_input(INPUT_SERVER, 'HTTPS')) + && Tools::strtolower(filter_input(INPUT_SERVER, 'HTTPS')) != 'off')) ); } @@ -1318,9 +1622,7 @@ public function getContent() $configuration_values = array( 'CONEKTA_MODE' => Tools::getValue('MODE'), 'CONEKTA_PUBLIC_KEY_TEST' => rtrim(Tools::getValue('TEST_PUBLIC_KEY')), - 'CONEKTA_PUBLIC_KEY_LIVE' => rtrim(Tools::getValue('LIVE_PUBLIC_KEY')), 'CONEKTA_PRIVATE_KEY_TEST' => rtrim(Tools::getValue('TEST_PRIVATE_KEY')), - 'CONEKTA_PRIVATE_KEY_LIVE' => rtrim(Tools::getValue('LIVE_PRIVATE_KEY')), 'CONEKTA_CARDS' => rtrim(Tools::getValue('PAYMENT_METHS_CARD')), 'CONEKTA_MSI' => rtrim(Tools::getValue('PAYMENT_METHS_INSTALLMET')), 'PAYMENT_METHS_CASH' => rtrim(Tools::getValue('PAYMENT_METHS_CASH')), @@ -1329,6 +1631,16 @@ public function getContent() 'EXPIRATION_DATE_TYPE' => rtrim(Tools::getValue('EXPIRATION_DATE_TYPE')), ); + if (Tools::getValue('LIVE_PUBLIC_KEY') && Tools::getValue('LIVE_PRIVATE_KEY')) { + $configuration_values = array_merge( + $configuration_values, + array( + 'CONEKTA_PUBLIC_KEY_LIVE' => rtrim(Tools::getValue('LIVE_PUBLIC_KEY')), + 'CONEKTA_PRIVATE_KEY_LIVE' => rtrim(Tools::getValue('LIVE_PRIVATE_KEY')), + ) + ); + } + foreach ($configuration_values as $configuration_key => $configuration_value) { Configuration::updateValue($configuration_key, $configuration_value); } @@ -1350,7 +1662,10 @@ public function getContent() $this->smarty->assign("requirements", $requirements); $this->smarty->assign("config_check", $requirements['result']); if ($requirements['result']) { - $this->smarty->assign("msg_show", $this->l('All the checks were successfully performed. You can now start using your module.')); + $this->smarty->assign( + "msg_show", + $this->l('All the checks were successfully performed. You can now start using your module.') + ); } else { $this->smarty->assign("msg_show", $this->l('Please resolve the following errors:')); } @@ -1375,24 +1690,80 @@ public function getContent() } /** - * Create customer of Conekta + * Check if the product is digital * - * @param $customer Info user in Prestashop - * @param $params Info of user + * @param array $items Products * - * @return string + * @return boolean */ - public function createCustomer($customer, $params) + private function isDigital($items) { - try { - $customerConekta = \Conekta\Customer::create($params); + $all_digital = true; + if (empty($items)) { + return false; + } - Database::updateConektaMetadata($customer->id, $this->conekta_mode, "conekta_customer_id", $customerConekta->id); + $i = 0; + do { + if (!$items[$i]['is_virtual']) { + $all_digital = false; + } + $i++; + } while ($i < count($items) && $all_digital); - return $customerConekta->id; - } catch (\Exception $e) { - return null; + return $all_digital; + } + + /** + * Validate fields + * + * @param string $phone Customer's phone number + * @param array $order_details Order details + * @param int $amount Total amount + * + * @return boolean + */ + public function checkedFields($phone = null, $order_details = null, $amount = null) + { + if (!empty($phone)) { + if (strpos($phone, '+') !== false) { + return $this->trans( + 'The phone number must not contain "+"', + array(), + 'Modules.ConektaPaymentsPrestashop.Admin' + ); + } elseif (Tools::strlen($phone) != 10) { + return $this->trans( + 'The field Phone must be a string with a maximum length of 10. (Example: 52XXXXXXXX)', + array(), + 'Modules.ConektaPaymentsPrestashop.Admin' + ); + } elseif (!is_numeric($phone)) { + return $this->trans( + 'The Phone field is not a valid phone number', + array(), + 'Modules.ConektaPaymentsPrestashop.Admin' + ); + } + } else { + return $this->trans( + 'The phone number is empty', + array(), + 'Modules.ConektaPaymentsPrestashop.Admin' + ); + } + + if (!empty($order_details)) { + if ($order_details['currency'] == 'MXN' && $amount < $this->amount_min) { + return $this->trans( + 'The minimum purchase amount with Conekta must be greater than $ 20.00', + array(), + 'Modules.ConektaPaymentsPrestashop.Admin' + ); + } } + + return true; } /** @@ -1402,7 +1773,8 @@ public function createCustomer($customer, $params) */ private function createWebhook() { - $key = Configuration::get('CONEKTA_MODE') ? Configuration::get('CONEKTA_PRIVATE_KEY_LIVE') : Configuration::get('CONEKTA_PRIVATE_KEY_TEST'); + $key = Configuration::get('CONEKTA_MODE') ? + Configuration::get('CONEKTA_PRIVATE_KEY_LIVE') : Configuration::get('CONEKTA_PRIVATE_KEY_TEST'); $iso_code = $this->context->language->iso_code; \Conekta\Conekta::setApiKey($key); @@ -1428,7 +1800,11 @@ private function createWebhook() $failed_attempts = (integer) Configuration::get('CONEKTA_WEBHOOK_FAILED_ATTEMPTS'); // If input is valid, has not been stored and has not failed more than 5 times - if ($is_valid_url && ($config_url != $url) && ($failed_attempts < 5 && $url != Configuration::get('CONEKTA_WEBHOOK_FAILED_URL'))) { + if ($is_valid_url + && ($config_url != $url) + && ($failed_attempts < 5 + && $url != Configuration::get('CONEKTA_WEBHOOK_FAILED_URL')) + ) { try { $webhooks = \Conekta\Webhook::where(); @@ -1470,15 +1846,24 @@ private function createWebhook() } } else { if ($url == Configuration::get('CONEKTA_WEBHOOK_FAILED_URL')) { - Configuration::updateValue('CONEKTA_WEBHOOK_ERROR_MESSAGE', "Webhook was already register, try changing webhook!"); + Configuration::updateValue( + 'CONEKTA_WEBHOOK_ERROR_MESSAGE', + "Webhook was already register, try changing webhook!" + ); Configuration::deleteByName('CONEKTA_WEBHOOK_FAILED_ATTEMPTS'); $failed_attempts = 0; } elseif ($failed_attempts >= 5) { - Configuration::updateValue('CONEKTA_WEBHOOK_ERROR_MESSAGE', "Maximum failed attempts reached!"); + Configuration::updateValue( + 'CONEKTA_WEBHOOK_ERROR_MESSAGE', + "Maximum failed attempts reached!" + ); } elseif (!$is_valid_url) { Configuration::updateValue('CONEKTA_WEBHOOK_ERROR_MESSAGE', "Not a valid url!"); } else { - Configuration::updateValue('CONEKTA_WEBHOOK_ERROR_MESSAGE', "Webhook was already registered in your shop!"); + Configuration::updateValue( + 'CONEKTA_WEBHOOK_ERROR_MESSAGE', + "Webhook was already registered in your shop!" + ); } } if (!empty(Configuration::get('CONEKTA_WEBHOOK_ERROR_MESSAGE'))) { @@ -1518,10 +1903,8 @@ public function getJumps($total, $jumps) protected function generateCardPaymentForm() { //value by default - $msi = 0; $jumps = array( 1 ); if (Configuration::get('PAYMENT_METHS_INSTALLMET')) { - $msi = 1; $total = $this->context->cart->getOrderTotal(); $jumps = $this->getJumps($total, $jumps); } @@ -1538,15 +1921,10 @@ protected function generateCardPaymentForm() $this->context->smarty->assign( array( 'action' => $this->context->link->getModuleLink($this->name, 'validation', array(), true), - 'months' => $months, - 'years' => $years, - 'msi' => $msi, - 'msi_jumps' => $jumps[0], - 'test_private_key' => Configuration::get('TEST_PRIVATE_KEY'), - 'charge_on_demand' => $this->charge_on_demand, 'path' => $this->_path ) ); + return $this->context->smarty->fetch('module:conektapaymentsprestashop/views/templates/front/payment_form.tpl'); } @@ -1559,7 +1937,8 @@ protected function generateCardPaymentForm() */ public function processPayment($conektaOrderId) { - $key = Configuration::get('CONEKTA_MODE') ? Configuration::get('CONEKTA_PRIVATE_KEY_LIVE') : Configuration::get('CONEKTA_PRIVATE_KEY_TEST'); + $key = Configuration::get('CONEKTA_MODE') ? + Configuration::get('CONEKTA_PRIVATE_KEY_LIVE') : Configuration::get('CONEKTA_PRIVATE_KEY_TEST'); $iso_code = $this->context->language->iso_code; \Conekta\Conekta::setApiKey($key); @@ -1572,10 +1951,31 @@ public function processPayment($conektaOrderId) $order = \Conekta\Order::find($conektaOrderId); $charge_response = $order->charges[0]; $order_status = (int) Configuration::get('PS_OS_PAYMENT'); - - $message = $this->l('Conekta Transaction Details:') . "\n\n" . $this->l('Amount:') . ' ' . ($charge_response->amount * 0.01) . "\n" . $this->l('Status:') . ' ' . ($charge_response->status == 'paid' ? $this->l('Paid') : $this->l('Unpaid')) . "\n" . $this->l('Processed on:') . ' ' . strftime('%Y-%m-%d %H:%M:%S', $charge_response->created_at) . "\n" . $this->l('Currency:') . ' ' . Tools::strtoupper($charge_response->currency) . "\n" . $this->l('Mode:') . ' ' . ($charge_response->livemode == 'true' ? $this->l('Live') : $this->l('Test')) . "\n"; - $this->validateOrder((int) $this->context->cart->id, (int) $order_status, $order->amount / 100, $this->displayName, $message, array(), null, false, $this->context->customer->secure_key); - + + $message = $this->l('Conekta Transaction Details:') + . "\n\n" . $this->l('Amount:') + . ' ' . ($charge_response->amount * 0.01) + . "\n" . $this->l('Status:') + . ' ' . ($charge_response->status == 'paid' ? $this->l('Paid') : $this->l('Unpaid')) + . "\n" . $this->l('Processed on:') + . ' ' . strftime('%Y-%m-%d %H:%M:%S', $charge_response->created_at) + . "\n" . $this->l('Currency:') + . ' ' . Tools::strtoupper($charge_response->currency) + . "\n" . $this->l('Mode:') . ' ' + . ($charge_response->livemode == 'true' ? $this->l('Live') : $this->l('Test')) . "\n"; + + $this->validateOrder( + (int) $this->context->cart->id, + (int) $order_status, + $order->amount / 100, + $this->displayName, + $message, + array(), + null, + false, + $this->context->customer->secure_key + ); + if (version_compare(_PS_VERSION_, '1.5', '>=')) { $new_order = new Order((int) $this->currentOrder); if (Validate::isLoadedObject($new_order)) { @@ -1586,16 +1986,39 @@ public function processPayment($conektaOrderId) } } } - - $reference = $charge_response->payment_method->reference; - if (isset($charge_response->id) && $charge_response->payment_method->type == "cash") { - Database::insertOxxoPayment($order, $charge_response, $reference, $this->currentOrder, $this->context->cart->id); - } elseif (isset($charge_response->id) && $charge_response->payment_method->type == "spei") { - Database::insertSpeiPayment($order, $charge_response, $reference, $this->currentOrder, $this->context->cart->id); + if (isset($charge_response->id) && Tools::strtolower($charge_response->payment_method->type) == "oxxo") { + Database::insertOxxoPayment( + $order, + $charge_response, + $charge_response->payment_method->reference, + $this->currentOrder, + $this->context->cart->id + ); + } elseif (isset($charge_response->id) + && Tools::strtolower($charge_response->payment_method->type) == "spei" + ) { + Database::insertSpeiPayment( + $order, + $charge_response, + $charge_response->payment_method->clabe, + $this->currentOrder, + $this->context->cart->id + ); } elseif (isset($charge_response->id)) { - Database::insertCardPayment($order, $charge_response, $this->currentOrder, $this->context->cart->id); + Database::insertCardPayment( + $order, + $charge_response, + $this->currentOrder, + $this->context->cart->id + ); } - Database::updateConektaOrder($this->context->customer->id, $this->context->cart->id, $this->conekta_mode, $order->id, $order->charges[0]->status); + Database::updateConektaOrder( + $this->context->customer->id, + $this->context->cart->id, + $this->conekta_mode, + $order->id, + $order->charges[0]->status + ); $redirect = $this->context->link->getPageLink( 'order-confirmation', @@ -1613,13 +2036,24 @@ public function processPayment($conektaOrderId) $log_message = $e->getMessage() . ' '; if (class_exists('Logger')) { - Logger::addLog($this->l('Payment transaction failed') . ' ' . $log_message, 2, null, 'Cart', (int) $this->context->cart->id, true); + Logger::addLog( + $this->l('Payment transaction failed'). ' ' . $log_message, + 2, + null, + 'Cart', + (int) $this->context->cart->id, + true + ); } $message = $e->getMessage() . ' '; - $controller = Configuration::get('PS_ORDER_PROCESS_TYPE') ? 'order-opc.php' : 'order.php'; - $location = $this->context->link->getPageLink($controller, true) . (strpos($controller, '?') !== false ? '&' : '?') . 'step=3&conekta_error=1&message=' . $message . '#conekta_error'; + $controller = Configuration::get('PS_ORDER_PROCESS_TYPE') ? + 'order-opc.php' : 'order.php'; + $location = $this->context->link->getPageLink($controller, true) + . (strpos($controller, '?') !== false ? '&' : '?') + . 'step=3&conekta_error=1&message=' + . $message . '#conekta_error'; Tools::redirectLink($location); } @@ -1686,8 +2120,8 @@ public function getTransactionStatus($order_id) $this->smarty->assign( "txt_mode", $this->l( - 'Test (No payment has been processed and you will' - .' need to enable the "Live" mode)' + "Test (No payment has been processed and you will" + ." need to enable the ''Live'' mode)" ) ); } diff --git a/controllers/front/validation.php b/controllers/front/validation.php index 44ac57694..57cd6c0c0 100644 --- a/controllers/front/validation.php +++ b/controllers/front/validation.php @@ -50,7 +50,11 @@ public function postProcess() } } if (!$authorized) { - print_r($this->getTranslator()->trans('This payment method is not available.', array(), 'Modules.ConektaPaymentsPrestashop.Shop')); + print_r($this->getTranslator()->trans( + 'This payment method is not available.', + array(), + 'Modules.ConektaPaymentsPrestashop.Shop' + )); } else { if (!Validate::isLoadedObject($customer)) { Tools::redirect('index.php?controller=order&step=1'); diff --git a/model/Config.php b/model/Config.php index e809b2981..1bd2e5070 100644 --- a/model/Config.php +++ b/model/Config.php @@ -122,11 +122,11 @@ public static function getShippingContact($customer = '', $address_delivery = '' return $shipping_contact; } - public static function getCustomerInfo($customer = '') + public static function getCustomerInfo($customer = '', $address_delivery = '') { $customer_info = array( "name" => $customer->firstname . " " . $customer->lastname, - // "phone" => $address_delivery->phone, + "phone" => $address_delivery->phone, "email" => $customer->email, "metadata" => array("soft_validations" => true) ); diff --git a/model/Database.php b/model/Database.php index c791c5731..a32bdd313 100644 --- a/model/Database.php +++ b/model/Database.php @@ -42,7 +42,7 @@ public static function getOrderConekta($order_id) { return Db::getInstance()->getValue( 'SELECT module FROM ' . _DB_PREFIX_ . 'orders ' - .'WHERE id_order = ' . pSQL((int) $order_id) + . 'WHERE id_order = ' . pSQL((int) $order_id) ); } @@ -57,8 +57,8 @@ public static function getConektaTransaction($order_id) { return Db::getInstance()->getRow( 'SELECT * FROM ' . _DB_PREFIX_ . 'conekta_transaction ' - .'WHERE id_order = ' . pSQL((int) $order_id) . - ' AND type = \'payment\'' + . 'WHERE id_order = ' . pSQL((int) $order_id) + . ' AND type = \'payment\'' ); } @@ -76,10 +76,10 @@ public static function getConektaTransaction($order_id) public static function insertOxxoPayment($order, $charge_response, $reference, $currentOrder, $cartId) { return Db::getInstance()->Execute( - 'INSERT INTO ' . _DB_PREFIX_ . 'conekta_transaction ( - type, id_cart, id_order, id_conekta_order, id_transaction, amount, - status, currency, mode, date_add, reference, barcode, captured) - VALUES (\'payment\', ' . pSQL((int) $cartId) . ', ' . pSQL((int) $currentOrder) . ', \'' + 'INSERT INTO ' . _DB_PREFIX_ . 'conekta_transaction (' + . 'type, id_cart, id_order, id_conekta_order, id_transaction, amount,' + . 'status, currency, mode, date_add, reference, barcode, captured)' + . 'VALUES (\'payment\', ' . pSQL((int) $cartId) . ', ' . pSQL((int) $currentOrder) . ', \'' . pSQL($order->id) . '\', \'' . pSQL($charge_response->id) . '\',\'' . (float) ($order->amount * 0.01) . '\', \'' . ($charge_response->status == 'paid' ? 'paid' : 'unpaid') . '\', \'' @@ -158,7 +158,11 @@ public static function createTableConektaOrder() id_cart int(11) unsigned NOT NULL, `mode` enum(\"live\",\"test\") NOT NULL, id_conekta_order varchar(32) NOT NULL, - `status` enum(\"paid\",\"unpaid\") NOT NULL, + `status` enum(\"paid\",\"pre_authorized\",\"unpaid\",\"pending_payment\",\"expired\",\"voided\"," + . "\"fraudulent\",\"preauthorized\",\"canceled\",\"pending_confirmation\",\"charged_back\"," + . "\"partially_refunded\",\"refunded\",\"reversed\",\"approved\",\"declined\",\"in_review\"," + . "\"insufficient_funds\",\"card_declined\",\"stolen_card\",\"suspected_fraud\"," + . "\"unprocessable_card_type\") NOT NULL, PRIMARY KEY (id), KEY id_user (id_user), KEY id_cart (id_cart), @@ -184,10 +188,10 @@ public static function createTableConektaOrder() public static function insertSpeiPayment($order, $charge_response, $reference, $currentOrder, $cartId) { return Db::getInstance()->Execute( - 'INSERT INTO ' . _DB_PREFIX_ . 'conekta_transaction( - type, id_cart, id_order, id_conekta_order, id_transaction, amount, - status, currency, mode, date_add, reference, captured) - VALUES (\'payment\', ' . (int) $cartId . ', ' . (int) $currentOrder . ', \'' + 'INSERT INTO ' . _DB_PREFIX_ . 'conekta_transaction(' + . 'type, id_cart, id_order, id_conekta_order, id_transaction, amount,' + . 'status, currency, mode, date_add, reference, captured)' + . 'VALUES (\'payment\', ' . (int) $cartId . ', ' . (int) $currentOrder . ', \'' . pSQL($order->id) . '\', \'' . pSQL($charge_response->id) . '\', \'' . (float)($charge_response->amount * 0.01) . '\', \'' . ($charge_response->status == 'paid' ? 'paid' : 'unpaid') . '\', \'' @@ -210,10 +214,10 @@ public static function insertSpeiPayment($order, $charge_response, $reference, $ public static function insertCardPayment($order, $charge_response, $currentOrder, $cartId) { return Db::getInstance()->Execute( - 'INSERT INTO ' . _DB_PREFIX_ . 'conekta_transaction ( - type, id_cart, id_order, id_conekta_order, id_transaction, - amount, status, currency, mode, date_add, captured) - VALUES (\'payment\', ' . (int) $cartId . ', ' . (int) $currentOrder . ', \'' + 'INSERT INTO ' . _DB_PREFIX_ . 'conekta_transaction (' + . 'type, id_cart, id_order, id_conekta_order, id_transaction,' + . 'amount, status, currency, mode, date_add, captured)' + . 'VALUES (\'payment\', ' . (int) $cartId . ', ' . (int) $currentOrder . ', \'' . pSQL($order->id) . '\', \'' . pSQL($charge_response->id) . '\',\'' . (float)($charge_response->amount * 0.01) . '\', \'' . ($charge_response->status == 'paid' ? 'paid' : 'unpaid') . '\', \'' @@ -233,7 +237,7 @@ public static function getOrderById($id_order) { return Db::getInstance()->getRow( 'SELECT * FROM ' . _DB_PREFIX_ . 'conekta_transaction ' - .'WHERE id_order = ' . pSQL((int) $id_order) . ';' + . 'WHERE id_order = ' . pSQL((int) $id_order) . ';' ); } @@ -250,7 +254,9 @@ public static function getConektaMetadata($user_id, $mode, $meta_options) { $table = _DB_PREFIX_."conekta_metadata"; - $sql = "SELECT meta_value FROM $table WHERE id_user = '{$user_id}' AND meta_option = '{$meta_options}' AND `mode` = '{$mode}'"; + $sql = "SELECT meta_value FROM $table WHERE id_user = '{$user_id}' " + . "AND meta_option = '{$meta_options}' " + . "AND `mode` = '{$mode}'"; return Db::getInstance()->getRow($sql); } @@ -270,11 +276,13 @@ public static function updateConektaMetadata($user_id, $mode, $meta_options, $me $table = _DB_PREFIX_."conekta_metadata"; if (empty(Database::getConektaMetadata($user_id, $mode, $meta_options))) { - $sql = "INSERT INTO $table(id_user, mode, meta_option, meta_value) VALUES ('{$user_id}','{$mode}','{$meta_options}','{$meta_value}')"; + $sql = "INSERT INTO $table(id_user, mode, meta_option, meta_value) " + . "VALUES ('{$user_id}','{$mode}','{$meta_options}','{$meta_value}')"; } else { - $sql ="UPDATE $table SET id_user = '{$user_id}', meta_option = '{$meta_options}', meta_value = '{$meta_value}' WHERE id_user = '{$user_id}' AND meta_option = '{$meta_options}' AND `mode` = '{$mode}'"; + $sql ="UPDATE $table SET id_user = '{$user_id}', meta_option = '{$meta_options}', " + . "meta_value = '{$meta_value}' WHERE id_user = '{$user_id}' AND meta_option = '{$meta_options}' " + . "AND `mode` = '{$mode}'"; } - return Db::getInstance()->Execute($sql); } @@ -291,8 +299,9 @@ public static function getConektaOrder($user_id, $mode, $cart_id) { $table = _DB_PREFIX_."conekta_order_checkout"; - $sql = "SELECT id_conekta_order, `status` FROM $table WHERE id_user = '{$user_id}' AND `mode` = '{$mode}' AND `status` = 'unpaid' AND id_cart ='{$cart_id}'"; - + $sql = "SELECT id_conekta_order, `status` FROM $table WHERE id_user = '{$user_id}' " + . "AND `mode` = '{$mode}' AND `status` = 'unpaid' AND id_cart ='{$cart_id}'"; + return Db::getInstance()->getRow($sql); } @@ -310,13 +319,28 @@ public static function getConektaOrder($user_id, $mode, $cart_id) public static function updateConektaOrder($user_id, $cart_id, $mode, $id_conekta_order, $status) { $table = _DB_PREFIX_."conekta_order_checkout"; - + if (empty(Database::getConektaOrder($user_id, $mode, $cart_id))) { - $sql = "INSERT INTO $table(id_user, id_cart, mode, id_conekta_order, `status`) VALUES ('{$user_id}','{$cart_id}','{$mode}','{$id_conekta_order}', '{$status}')"; + $sql = "INSERT INTO $table(id_user, id_cart, mode, id_conekta_order, `status`) " + . "VALUES ('{$user_id}','{$cart_id}','{$mode}','{$id_conekta_order}', '{$status}')"; } else { - $sql = "UPDATE $table SET `status` = '{$status}' WHERE id_user = '{$user_id}' AND id_cart = '{$cart_id}' AND id_conekta_order = '{$id_conekta_order}' AND `mode` = '{$mode}'"; + $sql = "UPDATE $table SET `status` = '{$status}' WHERE id_user = '{$user_id}' " + . "AND id_cart = '{$cart_id}' AND id_conekta_order = '{$id_conekta_order}' AND `mode` = '{$mode}'"; } - return Db::getInstance()->Execute($sql); } + + /** + * Returns the id of the order related to the reference_id + * + * @param string $reference_id Alphabetical reference code assigned to the order. + * + * @return array|string + */ + public static function getOrderByReferenceId($reference_id) + { + $table = _DB_PREFIX_."orders"; + $sql = "SELECT id_order FROM $table WHERE reference = '{$reference_id}'"; + return Db::getInstance()->getRow($sql); + } } diff --git a/notification.php b/notification.php index bfee9294b..934b3aaf1 100644 --- a/notification.php +++ b/notification.php @@ -21,6 +21,7 @@ require_once dirname(__FILE__) . '/../../config/config.inc.php'; require_once dirname(__FILE__) . '/../../init.php'; +require_once dirname(__FILE__) . '/model/Database.php'; if (!defined('_PS_VERSION_')) { exit; @@ -41,8 +42,9 @@ if ($event_json->type == 'order.paid' && isset($event_json->data)) { $conekta_order = $event_json->data->object; - $reference_id = (integer) $conekta_order->metadata->reference_id; - $id_order = Order::getOrderByCartId($reference_id); + $reference_id = (string) $conekta_order->metadata->reference_id; + $result = Database::getOrderByReferenceId($reference_id); + $id_order = $result['id_order']; $order = new Order($id_order); $order_fields = $order->getFields(); $currency_payment = Currency::getPaymentCurrencies( @@ -51,7 +53,7 @@ ); $total_order_amount = $order->getOrdersTotalPaid(); $str_total_order_amount = (string) $total_order_amount * 100; - + if ($currency_payment[0]['iso_code'] === $conekta_order->currency) { if ($str_total_order_amount == $conekta_order->amount) { $orderHistory = new OrderHistory(); @@ -71,8 +73,9 @@ } elseif ($event_json->type == 'order.expired' && isset($event_json->data)) { $conekta_order = $event_json->data->object; - $reference_id = (integer) $conekta_order->metadata->reference_id; - $id_order = Order::getOrderByCartId($reference_id); + $reference_id = (string) $conekta_order->metadata->reference_id; + $result = Database::getOrderByReferenceId($reference_id); + $id_order = $result['id_order']; Db::getInstance()->Execute( 'UPDATE ' . _DB_PREFIX_ . 'orders SET current_state = '. ORDER_CANCELED .' WHERE id_order = ' @@ -80,9 +83,9 @@ ); } elseif ($event_json->type == 'order.canceled' && isset($event_json->data)) { $conekta_order = $event_json->data->object; - - $reference_id = (integer) $conekta_order->metadata->reference_id; - $id_order = Order::getOrderByCartId($reference_id); + $reference_id = (string) $conekta_order->metadata->reference_id; + $result = Database::getOrderByReferenceId($reference_id); + $id_order = $result['id_order']; Db::getInstance()->Execute( 'UPDATE ' . _DB_PREFIX_ . 'orders SET current_state = '. ORDER_CANCELED .' WHERE id_order = ' @@ -90,9 +93,9 @@ ); } elseif ($event_json->type == 'order.refunded' && isset($event_json->data)) { $conekta_order = $event_json->data->object; - - $reference_id = (integer) $conekta_order->metadata->reference_id; - $id_order = Order::getOrderByCartId($reference_id); + $reference_id = (string) $conekta_order->metadata->reference_id; + $result = Database::getOrderByReferenceId($reference_id); + $id_order = $result['id_order']; Db::getInstance()->Execute( 'UPDATE ' . _DB_PREFIX_ . 'orders SET current_state = '. ORDER_REFUNDED .' WHERE id_order = ' diff --git a/views/templates/hook/admin-order.tpl b/views/templates/hook/admin-order.tpl index 7db63d5b3..22e9411bf 100644 --- a/views/templates/hook/admin-order.tpl +++ b/views/templates/hook/admin-order.tpl @@ -46,7 +46,7 @@
{l s='Processed on:' mod='conektapaymentsprestashop'} {$processed_on|escape:'htmlall':'UTF-8'}
- {l s='Mode:' mod='conektapaymentsprestashop'} {$txt_mode|unescape:"htmlall"} + {l s='Mode:' mod='conektapaymentsprestashop'} {$txt_mode|escape:'htmlall':'UTF-8'}

{else} {l s='Warning:' mod='conektapaymentsprestashop'} {l s='The customer paid using Conekta and an error occured (check details at the bottom of this page)' mod='conektapaymentsprestashop'}