Hello guys, I like so much this forum because the support of this company is excellent and very fast.
So now i have a big problem, and as i saw on this post https://awodev.com/forum/awocoupon/help-section/error-coupon-equal-sales-price#comment-3071 I have the same problem, but for Pagseguro plugin.
If any body can help me, I think that it very simple.
Bellow is the code of my plugin - pagseguro:
Thank you in advanced
Paulo
So now i have a big problem, and as i saw on this post https://awodev.com/forum/awocoupon/help-section/error-coupon-equal-sales-price#comment-3071 I have the same problem, but for Pagseguro plugin.
If any body can help me, I think that it very simple.
Bellow is the code of my plugin - pagseguro:
<?php
if (!defined('_JEXEC'))
    die('Direct Access to ' . basename(__FILE__) . ' is not allowed.');
/**
 * Payment Plugin PagSeguro - Plugin do PagSeguro
 *
 * @version $Id: pagseguro.php, v1.2 20/04/2012 fsoares $
 * @package VirtueMart 2
 * @subpackage Plugins - payment
 * @author Fernando Soares <www.fernandosoares.com.br>
 * @copyright Copyright (C) 2006-2012 Fernando Soares. All rights reserved.
 *
 * VirtueMart is free software. <http://virtuemart.net>
 *
 */
if (!class_exists('vmPSPlugin'))
    require(JPATH_VM_PLUGINS . DS . 'vmpsplugin.php');
class plgVmPaymentPagseguro extends vmPSPlugin {
    // instance of class
    public static $_this = false;
    function __construct(& $subject, $config) {
        parent::__construct($subject, $config);
        $this->_loggable = true;
        $this->tableFields = array_keys($this->getTableSQLFields());
        $this->_tablepkey = 'id'; //virtuemart_pagseguro_id';
        $this->_tableId = 'id'; //'virtuemart_pagseguro_id';
        $varsToPush = array('pagseguro_merchant_email' => array('', 'char'),
        'pagseguro_token' => array('', 'char'),
        'pagseguro_botao' => array('', 'char'),
        'pagseguro_shipping' => array('', 'char'),
        'payment_logos' => array('', 'char'),
        'debug' => array(0, 'int'),
        'auto_open' => array('', 'char'),
        'new_window' => array('', 'char'),
        'payment_currency' => array('', 'int'),
        'status_pending' => array('', 'char'),
        'status_success' => array('', 'char'),
        'status_completed' => array('', 'char'),
        'status_dispute' => array('', 'char'),
        'status_refunded' => array('', 'char'),
        'status_canceled' => array('', 'char'),
        'countries' => array('', 'char'),
        'min_amount' => array('', 'int'),
        'max_amount' => array('', 'int'),
        'cost_per_transaction' => array('', 'int'),
        'cost_percent_total' => array('', 'int'),
        'tax_id' => array(0, 'int')
        );
        $this->setConfigParameterable($this->_configTableFieldName, $varsToPush);
    }
    public function getVmPluginCreateTableSQL() {
        return $this->createTableSQL('Payment Pagseguro Table');
    }
    function getTableSQLFields() {
        $SQLfields = array(
        'id' => ' INT(11) unsigned NOT NULL AUTO_INCREMENT ',
        'virtuemart_order_id' => ' int(1) UNSIGNED DEFAULT NULL',
        'order_number' => ' char(32) DEFAULT NULL',
        'virtuemart_paymentmethod_id' => ' mediumint(1) UNSIGNED DEFAULT NULL',
        'payment_name' => 'varchar(5000)',
        'payment_order_total' => 'decimal(15,5) NOT NULL DEFAULT \'0.00000\' ',
        'payment_currency' => 'char(3) ',
        'cost_per_transaction' => ' decimal(10,2) DEFAULT NULL ',
        'cost_percent_total' => ' decimal(10,2) DEFAULT NULL ',
        'tax_id' => ' smallint(1) DEFAULT NULL',
        'pagseguro_response_invoice' => ' char(32) DEFAULT NULL',
        'pagseguro_response_full_name' => ' char(128) DEFAULT NULL',
        'pagseguro_response_payer_email' => ' char(128) DEFAULT NULL',
        'pagseguro_response_payment_id' => ' char(40) DEFAULT NULL',
        'pagseguro_response_gross_amount' => ' decimal(10,2) DEFAULT NULL ',
        'pagseguro_response_discount_amount' => ' decimal(10,2) DEFAULT NULL ',
        'pagseguro_response_fee_amount' => ' decimal(10,2) DEFAULT NULL ',
        'pagseguro_response_net_amount' => ' decimal(10,2) DEFAULT NULL ',
        'pagseguro_response_payment_date' => ' char(28) DEFAULT NULL',
        'pagseguro_response_payment_method' => ' char(64) DEFAULT NULL',
        'pagseguro_response_installment_count' => ' char(4) DEFAULT NULL',
        'pagseguro_response_payment_status' => ' char(50) DEFAULT NULL'
        );
        return $SQLfields;
    }
    function plgVmConfirmedOrder($cart, $order) {
        if (!($method = $this->getVmPluginMethod($order['details']['BT']->virtuemart_paymentmethod_id))) {
            return null; // Another method was selected, do nothing
        }
        if (!$this->selectedThisElement($method->payment_element)) {
            return false;
        }
        $session = JFactory::getSession();
        $return_context = $session->getId();
        $this->_debug = $method->debug;
        $this->logInfo('plgVmConfirmedOrder order number: ' . $order['details']['BT']->order_number, 'message');
        if (!class_exists('PagSeguroLibrary')) {
            require('PagSeguroLibrary/PagSeguroLibrary.php');
        }
        if (!class_exists('VirtueMartModelOrders'))
            require( JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'orders.php' );
        if (!class_exists('VirtueMartModelCurrency'))
            require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'currency.php');
        $new_status = '';
        $usrBT = $order['details']['BT'];
        $address = ((isset($order['details']['ST'])) ? $order['details']['ST'] : $order['details']['BT']);
        if (!class_exists('TableVendors'))
            require(JPATH_VM_ADMINISTRATOR . DS . 'table' . DS . 'vendors.php');
        $vendorModel = VmModel::getModel('Vendor');
        $vendorModel->setId(1);
        $vendor = $vendorModel->getVendor();
        $vendorModel->addImages($vendor, 1);
        $this->getPaymentCurrency($method);
        $q = 'SELECT `currency_code_3` FROM `#__virtuemart_currencies` WHERE `virtuemart_currency_id`="' . $method->payment_currency . '" ';
        $db = &JFactory::getDBO();
        $db->setQuery($q);
        $currency_code_3 = $db->loadResult();
        $paymentCurrency = CurrencyDisplay::getInstance($method->payment_currency);
        $totalInPaymentCurrency = round($paymentCurrency->convertCurrencyTo($method->payment_currency, $order['details']['BT']->order_total, false), 2);
        $cd = CurrencyDisplay::getInstance($cart->pricesCurrency);
        $merchant_email = $method->pagseguro_merchant_email;
        if (empty($merchant_email)) {
            vmInfo(JText::_('VMPAYMENT_PAGSEGURO_MERCHANT_EMAIL_NOT_SET'));
            return false;
        }
        
        $pagseguro_token = $method->pagseguro_token;
        if (empty($pagseguro_token)) {
            vmInfo(JText::_('VMPAYMENT_PAGSEGURO_TOKEN_NOT_SET'));
            return false;
        }
        
        $pagseguro_botao = $method->pagseguro_botao;
        // Instantiate a new payment request
        $paymentRequest = new PagSeguroPaymentRequest();
        
        // Sets the currency
        $paymentRequest->setCurrency('BRL');
/*        
        // Add an item for this payment request
        $paymentRequest->addItem('P'.$order['details']['BT']->order_number, 
                                JText::_('VMPAYMENT_PAGSEGURO_ORDER_NUMBER') . ': ' . $order['details']['BT']->order_number, 
                                1, 
                                round($order['details']['BT']->order_total, 2)
                                );
*/
        // Add an items for this payment request
        $Rref = 0;
        foreach ($cart->products as $key => $product) {
            $Rref++;
            if($product->product_weight_uom == "KG" || $product->product_weight_uom == "Kg"){
                $weight_g = round($product->product_weight * 1000);
            }else{
                $weight_g = round($product->product_weight);
            }
            if($product->product_sku == ""){
                $ref_produto = "Ref" . $Rref;
            }else{
                $ref_produto = $product->product_sku;
            }
            $paymentRequest->addItem($ref_produto, 
                                    substr(strip_tags($product->product_name), 0, 100), 
                                    $product->quantity, 
                                    round($cart->pricesUnformatted[$key]['salesPrice'], 2),
                                    $weight_g,
                                    round($cart->pricesUnformatted ['salesPriceShipment'], 2)
                                    );
        }
        
        { # seyi_code
            /*if (!empty($cart->couponCode)) {
                $paymentRequest->setExtraAmount((round($cart->pricesUnformatted['salesPriceCoupon'], 2)*-1)+round($cart->pricesUnformatted ['salesPricePayment'], 2));
            }*/
            if(!empty($order['details']['BT']->coupon_code)) {
                $paymentRequest->setExtraAmount((round($order['details']['BT']->coupon_discount, 2)*-1));
            }
        }
        // Sets a reference code for this payment request, it is useful to identify this payment in future notifications.
        $paymentRequest->setReference($order['details']['BT']->order_number . '|||' . $return_context);
        
        // Sets shipping information for this payment request
        $paymentRequest->setShippingType($method->pagseguro_shipping);
        $cep = preg_replace('#[^0-9]#', '', $address->zip);
        $paymentRequest->setShippingAddress($cep, $address->address_1,  
            '000', 
            ' ', 
            isset($address->address_2) ? $address->address_2 : '', 
            $address->city, 
            isset($address->virtuemart_state_id) ? ShopFunctions::getStateByID($address->virtuemart_state_id, 'state_2_code') : '', 
            ShopFunctions::getCountryByID($address->virtuemart_country_id, 'country_3_code')    //    'BRA'
        );
        
        // Sets your customer information.
        $telefone = ereg_replace('[^0-9]', '', $address->phone_1);
        $paymentRequest->setSender($address->first_name . ' ' . $address->last_name, 
            $order['details']['BT']->email, 
            substr($telefone, 0, (strlen($telefone)-8)), substr($telefone, -8)
        );
        // Seta o Retorno ao site
        $paymentRequest->setRedirectUrl(JROUTE::_(JURI::root() . 'index.php?option=com_virtuemart'));
        
        try {
            // #### Crendencials #####
            $credentials = new PagSeguroAccountCredentials($merchant_email, $pagseguro_token);
            
            // Register this payment request in PagSeguro, to obtain the payment URL for redirect your customer.
            $url = $paymentRequest->register($credentials);
        } catch (PagSeguroServiceException $e) {
            vmInfo(JText::_('VMPAYMENT_PAGSEGURO_ERROR_MSG') . $e->getMessage());
        }
/* para testes o futuro
        "return" => JROUTE::_(JURI::root() . 'index.php?option=com_virtuemart&view=pluginresponse&task=pluginresponsereceived&on=' . $order['details']['BT']->order_number . '&pm=' . $order['details']['BT']->virtuemart_paymentmethod_id),
        "notify_url" => JROUTE::_(JURI::root() . 'index.php?option=com_virtuemart&view=pluginresponse&task=pluginnotification&tmpl=component'),
*/
        // Prepare data that should be stored in the database
        $dbValues['order_number'] = $order['details']['BT']->order_number;
        $dbValues['payment_name'] = $this->renderPluginName($method, $order);
        $dbValues['virtuemart_paymentmethod_id'] = $cart->virtuemart_paymentmethod_id;
        $dbValues['cost_per_transaction'] = $method->cost_per_transaction;
        $dbValues['cost_percent_total'] = $method->cost_percent_total;
        $dbValues['payment_currency'] = $method->payment_currency;
        $dbValues['payment_order_total'] = $totalInPaymentCurrency;
        $dbValues['tax_id'] = $method->tax_id;
        $this->storePSPluginInternalData($dbValues);
        // new window opening
        if($method->new_window){
            $nova1 = ' target="_blank" ';
            $nova2 = '';
        }else{
            $nova1 = '';
            $nova2 = ', "_self"';
        }
        // add spin image
        $html = '<html><head><title>Redirecionando</title></head><body><div style="margin: auto; text-align: center;">';
        $html .= '<p>' . JText::_('VMPAYMENT_PAGSEGURO_PLEASE_WAIT') . '</p>';
        $html .= '<p>' . JText::_('VMPAYMENT_PAGSEGURO_CLICK_ON_BUTTON') . '</p>';
        $html .= '<p><a title="URL do pagamento" href="' . $url . '"' . $nova1 . '>';
        $html .= '<img src="'.$pagseguro_botao.'" alt="' . JText::_('VMPAYMENT_PAGSEGURO_BTN_ALT') . '">';
        $html .= '</a></p>';
        // auto opening
        if($method->auto_open){
            $html .= '<script type="text/javascript">';
            $html .= 'window.open("' . $url . '"' . $nova2 . ');';
            $html .= '</script>';
        }
        $html .= '</body></html>';
        //     2 = don't delete the cart, don't send email and don't redirect
        return $this->processConfirmedOrderPaymentResponse(2, $cart, $order, $html, $dbValues['payment_name'], $new_status);
    }
    function plgVmgetPaymentCurrency($virtuemart_paymentmethod_id, &$paymentCurrencyId) {
        if (!($method = $this->getVmPluginMethod($virtuemart_paymentmethod_id))) {
            return null; // Another method was selected, do nothing
        }
        if (!$this->selectedThisElement($method->payment_element)) {
            return false;
        }
        $this->getPaymentCurrency($method);
        $paymentCurrencyId = $method->payment_currency;
    }
      /**
     * This event is fired when the  method notifies you when an event occurs that affects the order.
     * Typically,  the events  represents for payment authorizations, Fraud Management Filter actions and other actions,
     * such as refunds, disputes, and chargebacks.
     *
     * NOTE for Plugin developers:
     *  If the plugin is NOT actually executed (not the selected payment method), this method must return NULL
     *
     * @param $return_context: it was given and sent in the payment form. The notification should return it back.
     * Used to know which cart should be emptied, in case it is still in the session.
     * @param int $virtuemart_order_id : payment  order id
     * @param char $new_status : new_status for this order id.
     * @return mixed Null when this method was not selected, otherwise the true or false
     *
     * @author Valerie Isaksen
     *
     *
      public function plgVmOnPaymentNotification() {
      return null;
      }
    */
    function plgVmOnPaymentNotification() {
        if (!class_exists('VirtueMartModelOrders'))
            require( JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'orders.php' );
        $pagseguro_data = JRequest::get('post');
        if (!isset($pagseguro_data['notificationType']) && !isset($pagseguro_data['notificationCode'])) {
            return;
        }
        if (!class_exists('PagSeguroLibrary')) {
            require('PagSeguroLibrary/PagSeguroLibrary.php');
        }
        $qps = 'SELECT `virtuemart_paymentmethod_id` FROM `#__virtuemart_paymentmethods` WHERE `payment_element`="pagseguro" ';
        $dbps = &JFactory::getDBO();
        $dbps->setQuery($qps);
        $psmethod_id = $dbps->loadResult();
        
        $psmethod = $this->getVmPluginMethod($psmethod_id);
        if (!$this->selectedThisElement($psmethod->payment_element)) {
            return false;
        }
        // Definindo as credenciais
        $merchant_email = $psmethod->pagseguro_merchant_email;
        $pagseguro_token = $psmethod->pagseguro_token;
        
        //Destroys the variables not used
        unset($qps);
        unset($dbps);
        unset($psmethod);
        unset($psmethod_id);
        $credentials = new PagSeguroAccountCredentials($merchant_email, $pagseguro_token);  
        // Tipo de notificação recebida
        $type = $pagseguro_data['notificationType'];
        // Código da notificação recebida
        $code = $pagseguro_data['notificationCode'];
        // Verificando tipo de notificação recebida
        if ($type === 'transaction') {
            // Obtendo o objeto PagSeguroTransaction a partir do código de notificação
            $transaction = PagSeguroNotificationService::checkTransaction($credentials, $code); // código de notificação
        }else{
            $this->logInfo('Tipo não é transação ', 'ERROR');
            return false;
        }
        //Dados da referência
        $referencia = $transaction->getReference();
        $PSdataRef = explode('|||', $referencia);
        $order_number = $PSdataRef[0];
        $return_context = $PSdataRef[1];
        $virtuemart_order_id = VirtueMartModelOrders::getOrderIdByOrderNumber($order_number);
        //$this->logInfo('plgVmOnPaymentNotification: virtuemart_order_id  found ' . $virtuemart_order_id, 'message');
        if (!$virtuemart_order_id) {
            return;
        }
        $vendorId = 0;
        $payment = $this->getDataByOrderId($virtuemart_order_id);
        $method = $this->getVmPluginMethod($payment->virtuemart_paymentmethod_id);
        if (!$this->selectedThisElement($method->payment_element)) {
            return false;
        }
        $this->_debug = $method->debug;
        if (!$payment) {
            $this->logInfo('getDataByOrderId payment not found: exit ', 'ERROR');
            return null;
        }
        $this->logInfo('pagseguro_data ' . implode('   ', $pagseguro_data), 'message');
        $this->_storePagseguroInternalData($method, $transaction, $virtuemart_order_id);
        $ps_status = $transaction->getStatus();
        $payment_status = $ps_status->getValue();
        $payment_status_str = JText::_('VMPAYMENT_PAGSEGURO_STATUS_'.$ps_status->getTypeFromValue());
/*
        if (empty($payment_status) || ($payment_status > 7)) {
            //return false;
        }
*/
        $order = array();
        $new_status = '';
        if ($payment_status == 1 || $payment_status == 2) {
            $new_status = $method->status_pending;
            $order['order_status'] = $new_status;
            $order['customer_notified'] =1;
            $order['comments'] = JText::sprintf('VMPAYMENT_PAGSEGURO_PAYMENT_STATUS_PENDING', $order_number, $payment_status_str);
        } elseif ($payment_status == 3) {
            $new_status = $method->status_success;
            $order['order_status'] = $new_status;
            $order['customer_notified'] =1;
            $order['comments'] = JText::sprintf('VMPAYMENT_PAGSEGURO_PAYMENT_STATUS_CONFIRMED', $order_number, $payment_status_str);
        } elseif ($payment_status == 4) {
            $new_status = $method->status_completed;
            $order['order_status'] = $new_status;
            $order['customer_notified'] =0;
            $order['comments'] = JText::sprintf('VMPAYMENT_PAGSEGURO_PAYMENT_STATUS_COMPLETED', $order_number, $payment_status_str);
        } elseif ($payment_status == 5) {
            $new_status = $method->status_dispute;
            $order['order_status'] = $new_status;
            $order['customer_notified'] =0;
            $order['comments'] = JText::sprintf('VMPAYMENT_PAGSEGURO_PAYMENT_STATUS_DISPUTE', $order_number, $payment_status_str);
        } elseif ($payment_status == 6) {
            $new_status = $method->status_refunded;
            $order['order_status'] = $new_status;
            $order['customer_notified'] =0;
            $order['comments'] = JText::sprintf('VMPAYMENT_PAGSEGURO_PAYMENT_STATUS_REFUNDED', $order_number, $payment_status_str);
        } elseif ($payment_status == 7) {
            $new_status = $method->status_canceled;
            $order['order_status'] = $new_status;
            $order['customer_notified'] =1;
            $order['comments'] = JText::sprintf('VMPAYMENT_PAGSEGURO_PAYMENT_STATUS_CANCELED', $order_number, $payment_status_str);
        }
        $this->logInfo('plgVmOnPaymentNotification return new_status:' . $new_status, 'message');
        $modelOrder = VmModel::getModel('orders');
        $modelOrder->updateStatusForOneOrder($virtuemart_order_id, $order, true);
        $this->logInfo('Notification, sentOrderConfirmedEmail ' . $order_number . ' ' . $new_status, 'message');
        
        // objeto PagSeguroPaymentMethod
        $paymentMethod = $transaction->getPaymentMethod();
        // objeto PagSeguroPaymentMethodCode
        $code = $paymentMethod->getCode();
        // objeto PagSeguroSender
        $sender = $transaction->getSender();
        $mailsubject = JText::_('VMPAYMENT_PAGSEGURO_NPI_EMAIL_SUBJECT') . $order_number;
        $mailbody = JText::_('VMPAYMENT_PAGSEGURO_NPI_EMAIL_TEXT') . "\n";
        $mailbody .= "-----------------------------------------------------\n";
        $mailbody .= JText::_('VMPAYMENT_PAGSEGURO_NPI_PAYMENT_ID') . " : " . $transaction->getCode() . "\n";
        $mailbody .= JText::_('VMPAYMENT_PAGSEGURO_NPI_PAYMENT_METHOD') . " : " . $code->getValue() . " - " . JText::_('VMPAYMENT_PAGSEGURO_METHOD_'.$code->getTypeFromValue()) . "\n";
        $mailbody .= JText::_('VMPAYMENT_PAGSEGURO_NPI_CUSTOMER_EMAIL') . " : " . $sender->getEmail() . "\n";
        $mailbody .= JText::_('VMPAYMENT_PAGSEGURO_NPI_CUSTOMER_NAME') . " : " . $sender->getName() . "\n";
        $mailbody .= JText::_('VMPAYMENT_PAGSEGURO_NPI_ORDER_NUMBER') . " : " . $order_number . "\n";
        $mailbody .= JText::_('VMPAYMENT_PAGSEGURO_NPI_ORDER_AMOUNT') . " : " . $transaction->getGrossAmount() . "\n";
        $mailbody .= JText::_('VMPAYMENT_PAGSEGURO_NPI_PS_STATUS') . " : " . $payment_status . " - " . $payment_status_str . "\n";
        $mailbody .= JText::_('VMPAYMENT_PAGSEGURO_NPI_ORDER_STATUS') . " : " . $new_status . "\n\n";
        $this->sendEmailToVendorAndAdmins($mailsubject, $mailbody);
        //// remove vmcart
        $this->emptyCart($return_context);
        //die();
    }
    function _storePagseguroInternalData($method, $transaction, $virtuemart_order_id) {
        // objeto PagSeguroStatus
        $ps_status = $transaction->getStatus();
        // objeto PagSeguroSender
        $sender = $transaction->getSender();
        // objeto PagSeguroPaymentMethod
        $PSpaymentMethod = $transaction->getPaymentMethod();
        // objeto PagSeguroPaymentMethodCode
        $PSpayCode = $PSpaymentMethod->getCode();
        $PSdataRef = explode('|||', $transaction->getReference());
        $response_fields['pagseguro_response_invoice'] = $PSdataRef[0];
        $response_fields['pagseguro_response_payment_date'] = $transaction->getLastEventDate();
        $response_fields['pagseguro_response_payment_status'] = $ps_status->getValue().' - '.JText::_('VMPAYMENT_PAGSEGURO_STATUS_'.$ps_status->getTypeFromValue());
        $response_fields['pagseguro_response_payer_email'] = $sender->getEmail();
        $response_fields['pagseguro_response_full_name'] = $sender->getName();
        $response_fields['pagseguro_response_payment_id'] = $transaction->getCode();
        $response_fields['pagseguro_response_gross_amount'] = $transaction->getGrossAmount();
        $response_fields['pagseguro_response_discount_amount'] = $transaction->getDiscountAmount();
        $response_fields['pagseguro_response_fee_amount'] = $transaction->getFeeAmount();
        $response_fields['pagseguro_response_net_amount'] = $transaction->getNetAmount();
        $response_fields['pagseguro_response_payment_method'] = $PSpayCode->getValue().' - '.JText::_('VMPAYMENT_PAGSEGURO_METHOD_'.$PSpayCode->getTypeFromValue());
        $response_fields['pagseguro_response_installment_count'] = $transaction->getInstallmentCount();
        $response_fields['payment_name'] = $this->renderPluginName($method);
        $response_fields['order_number'] = $transaction->getReference();
        $response_fields['virtuemart_order_id'] = $virtuemart_order_id;
        //$preload=true   preload the data here too preserve not updated data
        $this->storePSPluginInternalData($response_fields, 'virtuemart_order_id', true);
    }
    function _getTablepkeyValue($virtuemart_order_id) {
        $db = JFactory::getDBO();
        $q = 'SELECT ' . $this->_tablepkey . ' FROM `' . $this->_tablename . '` '
        . 'WHERE `virtuemart_order_id` = ' . $virtuemart_order_id;
        $db->setQuery($q);
        if (!($pkey = $db->loadResult())) {
            JError::raiseWarning(500, $db->getErrorMsg());
            return '';
        }
        return $pkey;
    }
    /**
     * Display stored payment data for an order
     * @see components/com_virtuemart/helpers/vmPSPlugin::plgVmOnShowOrderBEPayment()
     */
    function plgVmOnShowOrderBEPayment($virtuemart_order_id, $payment_method_id) {
        if (!$this->selectedThisByMethodId($payment_method_id)) {
            return null; // Another method was selected, do nothing
        }
        if (!($paymentTable = $this->_getPagseguroInternalData($virtuemart_order_id) )) {
            // JError::raiseWarning(500, $db->getErrorMsg());
            return '';
        }
        $this->getPaymentCurrency($paymentTable);
        $q = 'SELECT `currency_code_3` FROM `#__virtuemart_currencies` WHERE `virtuemart_currency_id`="' . $paymentTable->payment_currency . '" ';
        $db = &JFactory::getDBO();
        $db->setQuery($q);
        $currency_code_3 = $db->loadResult();
        $html = '<table class="adminlist">' . "\n";
        $html .=$this->getHtmlHeaderBE();
        $html .= $this->getHtmlRowBE('PAGSEGURO_PAYMENT_NAME', $paymentTable->payment_name);
        $code = "pagseguro_response_";
        foreach ($paymentTable as $key => $value) {
            if (substr($key, 0, strlen($code)) == $code) {
                $html .= $this->getHtmlRowBE($key, $value);
            }
        }
        $html .= '</table>' . "\n";
        return $html;
    }
    function _getPagseguroInternalData($virtuemart_order_id, $order_number='') {
        $db = JFactory::getDBO();
        $q = 'SELECT * FROM `' . $this->_tablename . '` WHERE ';
        if ($order_number) {
            $q .= " `order_number` = '" . $order_number . "'";
        } else {
            $q .= ' `virtuemart_order_id` = ' . $virtuemart_order_id;
        }
        $db->setQuery($q);
        if (!($paymentTable = $db->loadObject())) {
            // JError::raiseWarning(500, $db->getErrorMsg());
            return '';
        }
        return $paymentTable;
    }
    function getCosts(VirtueMartCart $cart, $method, $cart_prices) {
        if (preg_match('/%$/', $method->cost_percent_total)) {
            $cost_percent_total = substr($method->cost_percent_total, 0, -1);
        } else {
            $cost_percent_total = $method->cost_percent_total;
        }
        return ($method->cost_per_transaction + ($cart_prices['salesPrice'] * $cost_percent_total * 0.01));
    }
    /**
     * Check if the payment conditions are fulfilled for this payment method
     * @author: Valerie Isaksen
     *
     * @param $cart_prices: cart prices
     * @param $payment
     * @return true: if the conditions are fulfilled, false otherwise
     *
     */
    protected function checkConditions($cart, $method, $cart_prices) {
        $address = (($cart->ST == 0) ? $cart->BT : $cart->ST);
        $amount = $cart_prices['salesPrice'];
        $amount_cond = ($amount >= $method->min_amount AND $amount <= $method->max_amount
        OR
        ($method->min_amount <= $amount AND ($method->max_amount == 0) ));
        $countries = array();
        if (!empty($method->countries)) {
            if (!is_array($method->countries)) {
                $countries[0] = $method->countries;
            } else {
                $countries = $method->countries;
            }
        }
        // probably did not gave his BT:ST address
        if (!is_array($address)) {
            $address = array();
            $address['virtuemart_country_id'] = 0;
        }
        if (!isset($address['virtuemart_country_id']))
        $address['virtuemart_country_id'] = 0;
        if (in_array($address['virtuemart_country_id'], $countries) || count($countries) == 0) {
            if ($amount_cond) {
                return true;
            }
        }
        return false;
    }
    /**
     * We must reimplement this triggers for joomla 1.7
     */
    /**
     * Create the table for this plugin if it does not yet exist.
     * This functions checks if the called plugin is active one.
     * When yes it is calling the standard method to create the tables
     * @author Valérie Isaksen
     *
     */
    function plgVmOnStoreInstallPaymentPluginTable($jplugin_id) {
        return $this->onStoreInstallPluginTable($jplugin_id);
    }
    /**
     * This event is fired after the payment method has been selected. It can be used to store
     * additional payment info in the cart.
     *
     * @author Max Milbers
     * @author Valérie isaksen
     *
     * @param VirtueMartCart $cart: the actual cart
     * @return null if the payment was not selected, true if the data is valid, error message if the data is not vlaid
     *
     */
    public function plgVmOnSelectCheckPayment(VirtueMartCart $cart) {
        return $this->OnSelectCheck($cart);
    }
    /**
     * plgVmDisplayListFEPayment
     * This event is fired to display the pluginmethods in the cart (edit shipment/payment) for exampel
     *
     * @param object $cart Cart object
     * @param integer $selected ID of the method selected
     * @return boolean True on succes, false on failures, null when this plugin was not selected.
     * On errors, JError::raiseWarning (or JError::raiseError) must be used to set a message.
     *
     * @author Valerie Isaksen
     * @author Max Milbers
     */
    public function plgVmDisplayListFEPayment(VirtueMartCart $cart, $selected = 0, &$htmlIn) {
        return $this->displayListFE($cart, $selected, $htmlIn);
    }
    /*
     * plgVmonSelectedCalculatePricePayment
    * Calculate the price (value, tax_id) of the selected method
    * It is called by the calculator
    * This function does NOT to be reimplemented. If not reimplemented, then the default values from this function are taken.
    * @author Valerie Isaksen
    * @cart: VirtueMartCart the current cart
    * @cart_prices: array the new cart prices
    * @return null if the method was not selected, false if the shiiping rate is not valid any more, true otherwise
    *
    *
    */
    public function plgVmonSelectedCalculatePricePayment(VirtueMartCart $cart, array &$cart_prices, &$cart_prices_name) {
        return $this->onSelectedCalculatePrice($cart, $cart_prices, $cart_prices_name);
    }
    /**
     * plgVmOnCheckAutomaticSelectedPayment
     * Checks how many plugins are available. If only one, the user will not have the choice. Enter edit_xxx page
     * The plugin must check first if it is the correct type
     * @author Valerie Isaksen
     * @param VirtueMartCart cart: the cart object
     * @return null if no plugin was found, 0 if more then one plugin was found,  virtuemart_xxx_id if only one plugin is found
     *
     */
    function plgVmOnCheckAutomaticSelectedPayment(VirtueMartCart $cart, array $cart_prices = array()) {
        return $this->onCheckAutomaticSelected($cart, $cart_prices);
    }
    /**
     * This method is fired when showing the order details in the frontend.
     * It displays the method-specific data.
     *
     * @param integer $order_id The order ID
     * @return mixed Null for methods that aren't active, text (HTML) otherwise
     * @author Max Milbers
     * @author Valerie Isaksen
     */
    public function plgVmOnShowOrderFEPayment($virtuemart_order_id, $virtuemart_paymentmethod_id, &$payment_name) {
        $this->onShowOrderFE($virtuemart_order_id, $virtuemart_paymentmethod_id, $payment_name);
    }
    /**
     * This event is fired during the checkout process. It can be used to validate the
     * method data as entered by the user.
     *
     * @return boolean True when the data was valid, false otherwise. If the plugin is not activated, it should return null.
     * @author Max Milbers
     public function plgVmOnCheckoutCheckDataPayment($psType, VirtueMartCart $cart) {
     return null;
     }
     */
    /**
     * This method is fired when showing when priting an Order
     * It displays the the payment method-specific data.
     *
     * @param integer $_virtuemart_order_id The order ID
     * @param integer $method_id  method used for this order
     * @return mixed Null when for payment methods that were not selected, text (HTML) otherwise
     * @author Valerie Isaksen
     */
    function plgVmonShowOrderPrintPayment($order_number, $method_id) {
        return $this->onShowOrderPrint($order_number, $method_id);
    }
    /**
     * Save updated order data to the method specific table
     *
     * @param array $_formData Form data
     * @return mixed, True on success, false on failures (the rest of the save-process will be
     * skipped!), or null when this method is not actived.
     * @author Oscar van Eijk
     public function plgVmOnUpdateOrderPayment(  $_formData) {
     return null;
     }
     */
    /**
     * Save updated orderline data to the method specific table
     *
     * @param array $_formData Form data
     * @return mixed, True on success, false on failures (the rest of the save-process will be
     * skipped!), or null when this method is not actived.
     * @author Oscar van Eijk
     public function plgVmOnUpdateOrderLine(  $_formData) {
     return null;
     }
     */
    /**
     * plgVmOnEditOrderLineBE
     * This method is fired when editing the order line details in the backend.
     * It can be used to add line specific package codes
     *
     * @param integer $_orderId The order ID
     * @param integer $_lineId
     * @return mixed Null for method that aren't active, text (HTML) otherwise
     * @author Oscar van Eijk
     public function plgVmOnEditOrderLineBE(  $_orderId, $_lineId) {
     return null;
     }
     */
    /**
     * This method is fired when showing the order details in the frontend, for every orderline.
     * It can be used to display line specific package codes, e.g. with a link to external tracking and
     * tracing systems
     *
     * @param integer $_orderId The order ID
     * @param integer $_lineId
     * @return mixed Null for method that aren't active, text (HTML) otherwise
     * @author Oscar van Eijk
     public function plgVmOnShowOrderLineFE(  $_orderId, $_lineId) {
     return null;
     }
     */
    function plgVmDeclarePluginParamsPayment($name, $id, &$data) {
        return $this->declarePluginParams('payment', $name, $id, $data);
    }
    function plgVmSetOnTablePluginParamsPayment($name, $id, &$table) {
        return $this->setOnTablePluginParams($name, $id, $table);
    }
}
// No closing tag
?>
Thank you in advanced
Paulo

