コード例 #1
0
 protected function _convert($currencyFrom, $currencyTo, $retry = 0)
 {
     try {
         $response = \Ebanx\Ebanx::doExchange(array('currency_code' => $currencyFrom, 'currency_base_code' => $currencyTo));
         return (double) $response->currency_rate->rate * 1.0;
     } catch (Exception $e) {
         $this->_messages[] = Mage::helper('directory')->__('Cannot retrieve rate from EBANX.');
         return null;
     }
     $this->_messages[] = Mage::helper('directory')->__('Cannot retrieve rate from EBANX: unsupported currencies.');
     return null;
 }
コード例 #2
0
 public function getCallbackOwnerTransaction()
 {
     $this->callEbanxLib();
     $request = \XLite\Core\Request::getInstance();
     $hashes = explode(',', $request->hash_codes);
     $result = \Ebanx\Ebanx::doQuery(array('hash' => $hashes[0]));
     return $result->payment->merchant_payment_code ? \XLite\Core\Database::getRepo('XLite\\Model\\Payment\\Transaction')->find($result->payment->merchant_payment_code) : null;
 }
コード例 #3
0
ファイル: Payment.php プロジェクト: jonathanweb/ebanx-magento
 /**
  * Authorizes a transaction
  * @param  Varien_Object $payment
  * @param  float $amount
  * @return Mage_Payment_Model_Method_Abstract
  */
 public function authorize(Varien_Object $payment, $amount)
 {
     parent::authorize($payment, $amount);
     $session = Mage::getSingleton('checkout/session');
     $order = $payment->getOrder();
     $ebanx = Mage::app()->getRequest()->getParam('ebanx');
     Mage::log('Authorizing order [' . $order->getApiOrderId() . ']');
     $birthDate = str_pad($ebanx['birth_day'], 2, '0', STR_PAD_LEFT) . '/' . str_pad($ebanx['birth_month'], 2, '0', STR_PAD_LEFT) . '/' . $ebanx['birth_year'];
     // Street number workaround
     $streetNumber = preg_replace('/[\\D]/', '', $order->getBillingAddress()->getData('street'));
     $streetNumber = $streetNumber > 0 ? $streetNumber : '1';
     // Defines the order ID, if in test append time() to avoid errors
     $testMode = intval(Mage::getStoreConfig('payment/ebanx/testing')) == 1;
     $orderId = $order->getIncrementId() . ($testMode ? time() : '');
     // Cut order ID in test mode
     if (strlen($orderId) > 20 && $testMode) {
         $orderId = substr($orderId, 0, 20);
     }
     // Gets the currency code and total
     // Backend/base currency
     if (Mage::getStoreConfig('payment/ebanx_express/paymentcurrency') == 'base') {
         $amountTotal = $order->getBaseGrandTotal();
         $currencyCode = $order->getBaseCurrencyCode();
     } else {
         $amountTotal = $order->getGrandTotal();
         $currencyCode = $order->getOrderCurrency()->getCurrencyCode();
     }
     // On guest checkout, get billing email address
     $email = $order->getCustomerEmail() ?: $order->getBillingAddress()->getEmail();
     $state = $order->getBillingAddress()->getRegionCode();
     if (strlen($state) > 2) {
         $state = 'PR';
     }
     $ccExpiration = str_pad($ebanx['cc_expiration_month'], 2, '0', STR_PAD_LEFT) . '/' . $ebanx['cc_expiration_year'];
     $params = array('mode' => 'full', 'operation' => 'request', 'payment' => array('name' => $order->getCustomerFirstname() . ' ' . $order->getCustomerLastname(), 'document' => $ebanx['cpf'], 'birth_date' => $birthDate, 'email' => $email, 'phone_number' => $order->getBillingAddress()->getTelephone(), 'currency_code' => $currencyCode, 'amount_total' => $amountTotal, 'payment_type_code' => $ebanx['cc_type'], 'merchant_payment_code' => $orderId, 'order_number' => $order->getIncrementId(), 'zipcode' => $order->getBillingAddress()->getData('postcode'), 'address' => $order->getBillingAddress()->getData('street'), 'street_number' => $streetNumber, 'city' => $order->getBillingAddress()->getData('city'), 'state' => $state, 'country' => 'br', 'creditcard' => array('card_name' => $ebanx['cc_name'], 'card_number' => $ebanx['cc_number'], 'card_cvv' => $ebanx['cc_cvv'], 'card_due_date' => $ccExpiration)));
     // If has installments, adjust total
     if (isset($ebanx['installments'])) {
         if (intval($ebanx['installments']) > 1) {
             $interestRate = floatval(Mage::getStoreConfig('payment/ebanx_express/interest_installments'));
             $interestMode = Mage::getStoreConfig('payment/ebanx_express/installments_mode');
             $params['payment']['instalments'] = intval($ebanx['installments']);
             $params['payment']['amount_total'] = Ebanx_Express_Utils::calculateTotalWithInterest($interestMode, $interestRate, $amountTotal, intval($ebanx['installments']));
         }
     }
     try {
         // Set DirectMode as true
         \Ebanx\Config::setDirectMode(true);
         $response = \Ebanx\Ebanx::doRequest($params);
         Mage::log('Authorizing order [' . $order->getIncrementId() . '] - calling EBANX');
         if (!empty($response) && $response->status == 'SUCCESS') {
             $hash = $response->payment->hash;
             // Add the EBANX hash in the order data
             $order->getPayment()->setData('ebanx_hash', $hash)->save();
             // Redirect to bank page if the client chose TEF
             if (isset($response->redirect_url)) {
                 $_SESSION['ebxRedirectUrl'] = $response->redirect_url;
             } else {
                 $_SESSION['ebxRedirectUrl'] = Mage::getUrl('checkout/onepage/success') . '?hash=' . $hash;
             }
             Mage::log('Authorizing order [' . $order->getIncrementId() . '] - success');
         } else {
             Mage::log('Authorizing order [' . $order->getIncrementId() . '] - error: ' . $response->status_message);
             Mage::throwException($this->getEbanxErrorMessage($response->status_code));
         }
     } catch (Exception $e) {
         Mage::throwException($e->getMessage());
     }
     return $this;
 }
コード例 #4
0
 $conn = new PDO("mysql:host={$servername};dbname={$database}", $username, $password);
 // set the PDO error mode to exception
 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 // echo "Connected successfully 2\n";
 $sql = "SELECT * FROM ebanx_token WHERE DATE_FORMAT(data,'%d') = {$data}";
 //$sql = "SELECT * FROM ebanx_token";
 $result = $conn->query($sql);
 //$result = $result->fetch (PDO::FETCH_ASSOC);
 while ($data = $result->fetch(PDO::FETCH_ASSOC)) {
     $args = array('status' => '', 'customer_id' => $data['customer_id'], 'customer_note' => '', 'created_via' => 'EBANX Recurring cron', 'order_id' => 0);
     $order = new WC_Order($data['order_id']);
     $streetNumber = isset($order->billing_number) ? $order->billing_number : '1';
     $newOrder = wc_create_order($args);
     update_post_meta($newOrder->id, '_order_total', $order->order_total);
     $params = array('mode' => 'full', 'operation' => 'request', 'payment' => array('merchant_payment_code' => $newOrder->id, 'order_number' => $newOrder->id, 'amount_total' => $order->order_total, 'currency_code' => $data['currency_code'], 'name' => $order->billing_first_name . ' ' . $order->billing_last_name, 'email' => $order->billing_email, 'birth_date' => $data['birth_date'], 'address' => $order->billing_address_1, 'street_number' => $streetNumber, 'city' => $order->billing_city, 'state' => $order->billing_state, 'zipcode' => $order->billing_postcode, 'country' => $order->billing_country, 'phone_number' => $order->billing_phone, 'payment_type_code' => $data['payment_type_code'], 'document' => $order->billing_cpf, 'creditcard' => array('token' => $data['token'])));
     $response = \Ebanx\Ebanx::doRequest($params);
     if (isset($response->status) && $response->status == 'SUCCESS') {
         if ($response->payment->status == 'CA') {
             $newOrder->add_order_note('Payment failed.');
             $newOrder->cancel_order();
             echo "OK: Payment {$response->hash} was cancelled via IPN\n";
         }
         if ($response->payment->status == 'CO') {
             $newOrder->add_order_note('Payment confirmed.');
             $newOrder->update_status('completed');
             echo "OK: Payment {$response->hash} was confirmed via IPN\n";
         }
     }
 }
 // var_dump($result);
 $conn = null;
コード例 #5
0
/**
 * EBANX return response - gets called after returning from the EBANX checkout
 * @return void
 */
function ebanx_return_response()
{
    $ebanxWC = new WC_Gateway_Ebanx();
    $response = \Ebanx\Ebanx::doQuery(array('hash' => $_GET['hash']));
    $orderId = (int) $response->payment->order_number;
    $order = new WC_Order($orderId);
    if (isset($response->status) && $response->status == 'SUCCESS' && $response->payment->status == 'CO') {
        if ($response->payment->status == 'CO') {
            $order->add_order_note(__('EBANX payment completed, Hash: ' . $response->payment->hash, 'woocommerce'));
            $order->payment_complete();
        }
    }
    wp_redirect($ebanxWC->get_return_url($order));
    exit;
}
コード例 #6
0
 /**
  * Notification URI for the EBANX robot
  * @return void
  */
 public function notifyAction()
 {
     $hashes = $this->getRequest()->getParam('hash_codes');
     if (isset($hashes) && $hashes != null) {
         $hashes = explode(',', $hashes);
         foreach ($hashes as $hash) {
             $orderPayment = Mage::getModel('sales/order_payment')->getCollection()->addFieldToFilter('ebanx_hash', $hash)->getFirstItem();
             $response = \Ebanx\Ebanx::doQuery(array('hash' => $hash));
             if ($response->status == 'SUCCESS') {
                 try {
                     // Get the new status from Magento
                     $orderStatus = $this->_getOrderStatus($response->payment->status);
                     // Update order status
                     $order = Mage::getModel('sales/order')->load($orderPayment->getParentId(), 'entity_id');
                     // Checks if the order exists
                     if (!$order->getRealOrderId()) {
                         throw new Exception('Order cannot be found.');
                     }
                     // If payment status is CA - Canceled - AND order can be cancelled
                     if ($response->payment->status == 'CA' && $order->canCancel()) {
                         if (!$order->canCancel()) {
                             throw new Exception('Order cannot be canceled, assuming already processed.');
                         }
                         // Cancel order
                         $order->cancel();
                         // Set orderStatus to Generic canceled status - nothing more to do
                         $orderStatus = 'canceled';
                         // Comment on order
                         $order->addStatusHistoryComment('Automatically CANCELED by EBANX Notification.', false);
                     }
                     // If payment status is CO - Paid - AND order can be invoiced
                     if ($response->payment->status == 'CO') {
                         // If can NOT Invoice or order is not new
                         if (!$order->canInvoice()) {
                             throw new Exception('Order cannot be invoiced, assuming already processed.');
                         }
                         // Invoice
                         $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
                         $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
                         $invoice->register();
                         $invoice->getOrder()->setCustomerNoteNotify(true);
                         $invoice->getOrder()->setIsInProcess(true);
                         // Commit invoice to order
                         $transactionSave = Mage::getModel('core/resource_transaction')->addObject($invoice)->addObject($invoice->getOrder());
                         $transactionSave->save();
                         // Comment on order
                         $order->addStatusHistoryComment('Automatically INVOICED by EBANX Notification.', false);
                         $order->getSendConfirmation();
                         $order->setEmailSent(true);
                         $order->sendNewOrderEmail();
                     }
                     // Set status
                     $order->addStatusToHistory($orderStatus, 'Status changed by EBANX Notification.', false)->save();
                     echo 'OK: payment ' . $hash . ' was updated<br>';
                 } catch (Exception $e) {
                     echo 'NOK: payment ' . $hash . ' could not update order, Exception: ' . $e->getMessage() . '<br>';
                 }
             } else {
                 echo 'NOK: payment ' . $hash . ' could not be updated.<br>';
             }
         }
     } else {
         echo 'NOK: empty request.';
     }
 }
コード例 #7
0
ファイル: Payment.php プロジェクト: jonathanweb/ebanx-magento
 /**
  * Authorizes a transaction
  * @param  Varien_Object $payment
  * @param  float $amount
  * @return Mage_Payment_Model_Method_Abstract
  */
 public function authorize(Varien_Object $payment, $amount)
 {
     parent::authorize($payment, $amount);
     $country = strtolower($payment->getOrder()->getBillingAddress()->getCountry());
     $session = Mage::getSingleton('checkout/session');
     $order = $payment->getOrder();
     Mage::log('Authorizing order [' . $order->getApiOrderId() . ']');
     // Street number workaround
     $streetNumber = preg_replace('/[\\D]/', '', $order->getBillingAddress()->getData('street'));
     $streetNumber = $streetNumber > 0 ? $streetNumber : '1';
     // Defines the order ID, if in test append time() to avoid errors
     $testMode = intval(Mage::getStoreConfig('payment/ebanx/testing')) == 1;
     $orderId = $order->getIncrementId() . ($testMode ? time() : '');
     // Cut order ID in test mode
     if (strlen($orderId) > 20 && $testMode) {
         $orderId = substr($orderId, 0, 20);
     }
     // Gets the currency code and total
     // Backend/base currency
     if (Mage::getStoreConfig('payment/ebanx_standard/paymentcurrency') == 'base') {
         $amountTotal = $order->getBaseGrandTotal();
         $currencyCode = $order->getBaseCurrencyCode();
     } else {
         $amountTotal = $order->getGrandTotal();
         $currencyCode = $order->getOrderCurrency()->getCurrencyCode();
     }
     $dueDate = date('d/m/Y', strtotime('+' . intval(Mage::getStoreConfig('payment/ebanx_standard/due_date')) . $dueDays . 'days'));
     // On guest checkout, get billing email address
     $email = $order->getCustomerEmail() ?: $order->getBillingAddress()->getEmail();
     $params = array('name' => $order->getCustomerFirstname() . ' ' . $order->getCustomerLastname(), 'email' => $email, 'phone_number' => $order->getBillingAddress()->getTelephone(), 'currency_code' => $currencyCode, 'amount' => $amountTotal, 'payment_type_code' => '_all', 'merchant_payment_code' => $orderId, 'due_date' => $dueDate, 'order_number' => $order->getIncrementId(), 'zipcode' => $order->getBillingAddress()->getData('postcode'), 'address' => $order->getBillingAddress()->getData('street'), 'street_number' => $streetNumber, 'city' => $order->getBillingAddress()->getData('city'), 'state' => $order->getBillingAddress()->getRegionCode(), 'country' => strtolower($order->getBillingAddress()->getCountry()));
     try {
         $response = \Ebanx\Ebanx::doRequest($params);
         Mage::log('Authorizing order [' . $order->getIncrementId() . '] - calling EBANX');
         if (!empty($response) && $response->status == 'SUCCESS') {
             $hash = $response->payment->hash;
             // Add the EBANX hash in the order data
             $order->getPayment()->setData('ebanx_hash', $hash)->save();
             // Redirect to bank page if the client chose TEF
             if (isset($response->redirect_url)) {
                 $_SESSION['ebxRedirectUrl'] = $response->redirect_url;
             } else {
                 $_SESSION['ebxRedirectUrl'] = Mage::getUrl('checkout/onepage/success') . '?hash=' . $hash;
             }
             Mage::log('Authorizing order [' . $order->getIncrementId() . '] - success');
         } else {
             Mage::log('Authorizing order [' . $order->getIncrementId() . '] - error: ' . $response->status_message);
             Mage::throwException($this->getEbanxErrorMessage($response->status_code));
         }
     } catch (Exception $e) {
         Mage::throwException($e->getMessage());
     }
     return $this;
 }
コード例 #8
0
 /**
  * Generates the EBANX button link
  * @return string
  */
 public function generate_ebanx_form($order_id)
 {
     global $woocommerce;
     $servername = DB_HOST;
     $username = DB_USER;
     $password = DB_PASSWORD;
     $database = DB_NAME;
     // Set EBANX configs
     \Ebanx\Config::set(array('integrationKey' => $this->merchant_key, 'testMode' => $this->test_mode, 'directMode' => true));
     // Loads the current order
     $order = new WC_Order($order_id);
     // If is GET, do nothing, otherwise process the request
     if ($_SERVER['REQUEST_METHOD'] === 'GET') {
         $this->_renderCheckout($order_id);
         return;
     }
     $order = new WC_Order($order_id);
     $streetNumber = isset($order->billing_number) ? $order->billing_number : '1';
     $paymentMethod = isset($_POST['ebanx']['method']) ? $_POST['ebanx']['method'] : '';
     $countryCode = $order->billing_country;
     // Append timestamp on test mode
     $orderId = $this->test_mode ? $order_id . time() : $order_id;
     $params = array('mode' => 'full', 'operation' => 'request', 'payment' => array('merchant_payment_code' => $orderId, 'order_number' => $order_id, 'amount_total' => $order->order_total, 'currency_code' => get_woocommerce_currency(), 'name' => $order->billing_first_name . ' ' . $order->billing_last_name, 'email' => $order->billing_email, 'birth_date' => $this->getBirthdateFromRequest(true), 'address' => $order->billing_address_1, 'street_number' => $streetNumber, 'city' => $order->billing_city, 'state' => $order->billing_state, 'zipcode' => $order->billing_postcode, 'country' => $order->billing_country, 'phone_number' => $order->billing_phone, 'payment_type_code' => $_POST['ebanx']['cc_type'], 'document' => $order->billing_cpf));
     $ccExpiration = str_pad($_POST['ebanx']['cc_expiration_month'], 2, '0', STR_PAD_LEFT) . '/' . $_POST['ebanx']['cc_expiration_year'];
     try {
         $token = \Ebanx\Ebanx::doToken(['payment_type_code' => $_POST['ebanx']['cc_type'], 'creditcard' => ['card_number' => $_POST['ebanx']['cc_number'], 'card_name' => $_POST['ebanx']['cc_name'], 'card_due_date' => $ccExpiration, 'card_cvv' => $_POST['ebanx']['cc_cvv']]]);
     } catch (Exception $e) {
         $_SESSION['ebanxError'] = $e->getMessage();
         $this->_renderCheckout($order_id);
         return;
     }
     if ($token->status == "ERROR") {
         $_SESSION['ebanxError'] = "Erro ao processar pagamento: " . $token->status_message;
         $this->_renderCheckout($order_id);
         return;
     }
     $customer = wp_get_current_user();
     $customer_id = $customer->data->ID;
     $order_id_from_object = $order->id;
     $currency_code = $params['payment']['currency_code'];
     $payment_type_code = $params['payment']['payment_type_code'];
     $birth_date = $params['payment']['birth_date'];
     try {
         $conn = new PDO("mysql:host={$servername};dbname={$database}", $username, $password);
         // set the PDO error mode to exception
         $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     } catch (PDOException $e) {
         echo "Connection failed: " . $e->getMessage();
     }
     try {
         $params['payment']['creditcard'] = array('token' => $token->token);
         $response = \Ebanx\Ebanx::doRequest($params);
         if ($response->status == 'SUCCESS') {
             $sql = "CREATE TABLE IF NOT EXISTS `ebanx_token` (\n                `id` INT AUTO_INCREMENT NOT NULL,\n                `data` datetime NOT NULL,\n                `token` varchar(200),\n                `customer_id` varchar(200),\n                `order_id` varchar(200),\n                `currency_code` varchar(200),\n                `birth_date` varchar(200),\n                `payment_type_code` varchar(200),\n                PRIMARY KEY (`id`)) ";
             $conn->query($sql);
             date_default_timezone_set('America/Sao_Paulo');
             $month = date('m');
             $year = date('Y');
             $day = date('d');
             if ($day > '28' && $month == '02') {
                 $day = '28';
             } else {
                 if ($day == '31') {
                     $day = '01';
                 }
             }
             $date = $year . '-' . $month . '-' . $day;
             $sql = "INSERT INTO ebanx_token (data, token, customer_id, order_id, currency_code, birth_date, payment_type_code)\n                VALUES ('{$date}', '{$token->token}', '{$customer_id}', '{$order_id_from_object}', '{$currency_code}', '{$birth_date}', '{$payment_type_code}')";
             $conn->query($sql);
             // Clear cart
             $woocommerce->cart->empty_cart();
             if ($paymentMethod == 'boleto') {
                 $boletoUrl = $response->payment->boleto_url;
                 $orderUrl = $order->get_checkout_order_received_url($order);
                 $tplDir = dirname(__FILE__) . '/view/';
                 $template = file_get_contents($tplDir . 'success/boleto.php');
                 echo eval(' ?>' . $template . '<?php ');
             } else {
                 if ($paymentMethod == 'pagoefectivo') {
                     $cipUrl = $response->payment->cip_url;
                     $cipCode = $response->payment->cip_code;
                     $orderUrl = $order->get_checkout_order_received_url($order);
                     $tplDir = dirname(__FILE__) . '/view/';
                     $template = file_get_contents($tplDir . 'success/pagoefectivo.php');
                     echo eval(' ?>' . $template . '<?php ');
                 } else {
                     if ($paymentMethod == 'tef') {
                         wp_redirect($response->redirect_url);
                     } else {
                         wp_redirect($this->get_return_url($order));
                     }
                 }
             }
         } else {
             $_SESSION['ebanxError'] = $this->getEbanxErrorMessage($response->status_code, $countryCode);
             $this->_renderCheckout($order_id);
         }
     } catch (Exception $e) {
         $_SESSION['ebanxError'] = $e->getMessage();
         $this->_renderCheckout($order_id);
     }
     $conn = null;
 }