Jump to content
Fórum Script Brasil
  • 0

Problemas integrar API PagSeguro peço Ajuda


romihue
 Share

Question

om dia,

Sou novo no scriptbrasil. Eu fiz um curso de PHP , mas uns 10 anos atrás e assim meu PHP está meio antigo :blush:.
Bem Montamos um portal em Joomla 3.4 , hospedado no Amazon webservice com Bitnami.
Estmaos usando uma extension chamado VikEvents. (Vender ingressos)
Preciso integrar PagSeguro API para as vendas, mas com meus conhecimentos não deu certo. Suporte do PaSeguro não pude (ou quis) resolver problema.
Recebi um exemplo do gateway de pagamento do vikevents. Eles usam formulario com hidden inputs. Mas precisamos do API.
O teame Vikevents sugeriu de usar um curl enquanto de um form. Testei mais não deu certo.
Peço ajuda aqui por que meu chefe tá já sem paciencia.

Este é o code do vikevents:

defined('_JEXEC') OR die('Restricted Area');


class VikEventsPayment {
    
    private $order_info;
    private $params;
    
    public static function getAdminParameters() {
        //shows payment in Backend Payments
        $logo_img = JURI::root().'administrator/components/com_vikevents/payments/mypay/logo.gif';
        return array(    
            'logo' => array(
                'label' => ' Logo',
                'type' => 'custom',
                'html' => '<img src="'.$logo_img.'"/>'
            ),
            'merchantid' => array(
                'label' => 'Pagseguro App ID',
                'type' => 'text'
            ),
            'merchantkey' => array(
                'label' => 'PagSeguro App Key',
                'type' => 'text'
            ),
            'testmode' => array(
                'label' => 'Test Mode',
                'type' => 'select',
                'options' => array('Yes', 'No'),
            ),
        );
    }
    
    public function __construct ($order, $params=array()) {
        $this->order_info = $order;
        $this->params = $params;
    }
        
    
    public function showPayment () {
    
        $merchant_id = $this->params['merchantid'];
        
        $action_url = "https://Your_payment_checkout.com/";
        if( $this->params['testmode'] == 'Yes' ) {
            $action_url = "https://sandbox.Your_payment_checkout.com/";
        }

        $form='<form action="'.$action_url.'" method="post">';
        // put here all the required fields of your gateway
        $form.='<input type="hidden" name="your_post_data_merchantid" value="'.$merchant_id.'"/>';
        $form.='<input type="hidden" name="your_post_data_amount" value="'.$this->order_info['total_to_pay'].'"/>';
        $form.='<input type="hidden" name="your_post_data_notifyurl" value="'.$this->order_info['notify_url'].'"/>'; //Payment response will be analyzed by the validatePayment()
        $form.='<input type="hidden" name="your_post_data_description" value="'.$this->order_info['transaction_name'].'"/>';
        // print a button to submit the payment form
        $form.='<input type="submit" name="_submit" value="Pay Now!" />';
        $form.='</form>';
        
        echo $form;

    }
    
    public function validatePayment () {
        $array_result = array();
        $array_result['verified'] = 0;
        $array_result['tot_paid'] = ''; /** This value will be stored in the DB */
        
        /** In case of error the logs will be sent via email to the admin */
        $array_result['log'] = '';
        
        $status = $_POST['status'];
        /** Process your gateway response here */
        if($status == 'success') {
            $array_result['verified'] = 1;
            /** Set a value for $array_result['tot_paid'] */
            $array_result['tot_paid'] = $_POST['amount'];
        } else {
            $array_result['log'] = "Transaction Error!\n".$_POST['error_msg'];
        }
        
        /** Return the array result to VikEvents */
        return $array_result;
    }

    public function afterValidation ($esit = 0) {
    
        $mainframe = JFactory::getApplication();
        //URL to order details page
        $redirect_url = 'index.php?option=com_vikevents&task=orders&oid='.$this->order_info['id'].'&scode='.$this->order_info['scode'];
        
        if($esit < 1) {
            JError::raiseWarning('', 'The payment was not verified, please try again.');
            $mainframe->redirect($redirect_url);
        } else {
            $mainframe->enqueueMessage('Thank you! The payment was verified successfully.');
            $mainframe->redirect($redirect_url);
        }
        
        exit;
        //No page rendering
    }
}

e este meu code para PagSeguro:

header("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");

include_once "PagSeguroLibrary/PagSeguroLibrary.php";

class VikEventsPayment {
    
    private $order_info;
    private $params;
    
    public static function getAdminParameters() {
        //shows payment in Backend Payments
        $logo_img = JURI::root().'administrator/components/com_vikevents/payments/mypay/avista_estatico_130_230.gif';
        return array(    
            'logo' => array(
                'label' => ' Logo',
                'type' => 'custom',
                'html' => '<img src="'.$logo_img.'"/>'
            ),
            'merchantid' => array(
                'label' => 'Pagseguro App ID',
                'type' => 'text'
            ),
            'merchantkey' => array(
                'label' => 'PagSeguro App Key',
                'type' => 'text'
            ),
            'testmode' => array(
                'label' => 'Test Mode',
                'type' => 'select',
                'options' => array('Yes', 'No'),
            ),
        );
    }
    
    public function __construct ($order, $params=array()) {
        $this->order_info = $order;
        $this->params = $params;
    }
        
    
    public function showPayment () {
    
        $paymentRequest = new PagSeguroPaymentRequest();
        $merchant_id = $this->params['merchantid'];
        
        $action_url = "https://ws.pagseguro.uol.com.br/v2/checkout";
        if( $this->params['testmode'] == 'Yes' ) {
            $action_url = "https://sandbox.pagseguro.uol.com.br/";
        }
        
                $data['email'] = '[email protected]';
                $data['token'] = '01234567890123456789';
                $data['currency'] = 'BRL';
                $data['itemId1'] = ''.$this->order_info['transaction_name'].'';
                $data['itemDescription1'] = ''.$this->order_info['event_name'].'';
                $data['itemAmount1'] = ''.$this->order_info['total_to_pay'].'';
                $data['itemQuantity1'] = ''.$this->order_info['order']['persons'].'';
                $data['reference'] = ''.$this->order_info['id'].'';
                $data['senderName'] = ''.$this->order_info['membdata'].'';
                
                $data['redirectURL'] = 'http://www.meuportal.com.br';
                
                $data = http_build_query($data);
                
                $curl = curl_init($url);
                
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($curl, CURLOPT_POST, true);
                curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                $xml= curl_exec($curl);
                
                if($xml == 'Unauthorized'){
                //Insira seu código de prevenção a erros
                
                header('Location: erro.php?tipo=autenticacao');
                exit;//Mantenha essa linha
                }
                curl_close($curl);
                
                $xml= simplexml_load_string($xml);
                if(count($xml -> error) > 0){
                //Insira seu código de tratamento de erro, talvez seja útil enviar os códigos de erros.
                
                header('Location: erro.php?tipo=dadosInvalidos');
                exit;
                }
                header('Location: https://pagseguro.uol.com.br/v2/checkout/payment.html?code=' . $xml -> code);

        $form='<form action="'.$action_url.'" method="post">';
        // put here all the required fields of your gateway
        $form.='<input type="hidden" name="receiverEmail" value="[email protected]"/>';
        $form.='<input type="hidden" name="currency" value="BRL"/>';
        $form.='<input type="hidden" name="itemId1" value="'.$this->order_info['transaction_name'].'"/>';
        $form.='<input type="hidden" name="itemQuantity1" value="'.$this->order_info['order']['persons'].'"/>';
        $form.='<input type="hidden" name="itemDescription1" value="'.$this->order_info['event_name'].'"/>';
        $form.='<input type="hidden" name="itemAmount1" value="'.number_format($this->order_info['total_to_pay'], 2)."\"/>\n'/>'";
        $form.='<input type="hidden" name="itemAmount1" value="'.number_format($this->order_info['total_tax'], 2)."\"/>\n'/>'";    
        $form.='<input type="hidden" name="transaction_id" value="'.$this->order_info['notify_url'].'"/>'; //Payment response will be analyzed by the validatePayment()
        
        $form.='<input name="reference" value="'.$this->order_info['id'].'" type="hidden">';
        
        $form.='<input type="hidden" name="senderName" value="'.$this->order_info['membdata'].'"/>';
        // print a button to submit the payment form
        $form.='<input alt="Pague com PagSeguro" name="submit" type="image"
src="https://p.simg.uol.com.br/out/pagseguro/i/botoes/pagamentos/120x53-pagar.gif"/>';
        $form.='</form>';
        
        
        //output form
        
        echo $this->order_info['payment_info']['note'];
        echo $form;
        
        return true;

    }
    
    public function validatePayment () {
        $array_result = array();
        $array_result['verified'] = 0;
        $array_result['tot_paid'] = ''; /** This value will be stored in the DB */
        
        /** In case of error the logs will be sent via email to the admin */
        $array_result['log'] = '';
        
        $status = $_POST['status'];
        /** Process your gateway response here */
        if($status == 'success') {
            $array_result['verified'] = 1;
            /** Set a value for $array_result['tot_paid'] */
            $array_result['tot_paid'] = $_POST['amount'];
        } else {
            $array_result['log'] = "Transaction Error!\n".$_POST['error_msg'];
        }
        
        /** Return the array result to VikEvents */
        return $array_result;
    }

    public function afterValidation ($esit = 0) {
    
        $mainframe = JFactory::getApplication();
        //URL to order details page
        $redirect_url = 'index.php?option=com_vikevents&task=orders&oid='.$this->order_info['id'].'&scode='.$this->order_info['scode'];
        
        if($esit < 1) {
            JError::raiseWarning('', 'The payment was not verified, please try again.');
            $mainframe->redirect($redirect_url);
        } else {
            $mainframe->enqueueMessage('Thank you! The payment was verified successfully.');
            $mainframe->redirect($redirect_url);
        }
        
        exit;
        //No page rendering
    }
}

Com isso recebo o erro do pagseguro: Invalid email (troquei aqui, claro ,meu email-endereço, o original está certo e cadastrado no PagSeguro). Seu eu retiro o form, ele manda mais nada.

Algem pode ajudar favor?

Agradeço romihue

Link to comment
Share on other sites

0 answers to this question

Recommended Posts

There have been no answers to this question yet

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

  • Forum Statistics

    • Total Topics
      149.8k
    • Total Posts
      646.6k
×
×
  • Create New...