Example #1
1
 public function inicializaPagamento($cart, $urlRetorno)
 {
     require_once "vendor/PagSeguroLibrary/PagSeguroLibrary.php";
     $paymentRequest = new PagSeguroPaymentRequest();
     $paymentRequest->setCurrency("BRL");
     foreach ($cart->getProducts() as $product) {
         $paymentRequest->addItem($product['id_product_attribute'], $product['name'], $product['quantity'], $product['price_wt']);
     }
     $customer = new Customer($cart->id_customer);
     $address = new Address($cart->id_address_delivery);
     $telefone_full = preg_replace("/([^0-9])/", null, $address->phone);
     $telefone_full = str_pad($telefone_full, 11, "0", STR_PAD_LEFT);
     $areacode = substr($telefone_full, 1, 2);
     $phone = substr($telefone_full, 3);
     $state = new State($address->id_state);
     $number = preg_replace("/([^0-9])/", null, $address->address2);
     $paymentRequest->setShippingAddress($address->postcode, $address->address1, $number, null, null, $address->city, $state->iso_code, $address->country);
     $CODIGO_SHIPPING = PagSeguroShippingType::getCodeByType('NOT_SPECIFIED');
     $paymentRequest->setShippingType($CODIGO_SHIPPING);
     $paymentRequest->setShippingCost(number_format($cart->getOrderShippingCost(), 2, ".", ""));
     $paymentRequest->setSender($customer->firstname . " " . $customer->lastname, $customer->email, $areacode, $phone);
     $order_id = (int) Order::getOrderByCartId($cart->id);
     $paymentRequest->setReference($order_id);
     $paymentRequest->setRedirectURL($urlRetorno);
     $credentials = new PagSeguroAccountCredentials(Configuration::get("PAGSEGURO_BUSINESS"), Configuration::get("PAGSEGURO_TOKEN"));
     $url = $paymentRequest->register($credentials);
     return $url;
 }
 public static function createCheckoutRequest(PagSeguroCredentials $credentials, PagSeguroPaymentRequest $paymentRequest)
 {
     LogPagSeguro::info("PagSeguroPaymentService.Register(" . $paymentRequest->toString() . ") - begin");
     $connectionData = new PagSeguroConnectionData($credentials, self::serviceName);
     try {
         $connection = new PagSeguroHttpConnection();
         $connection->post(self::buildCheckoutRequestUrl($connectionData), PagSeguroPaymentParser::getData($paymentRequest), $connectionData->getServiceTimeout(), $connectionData->getCharset());
         $httpStatus = new PagSeguroHttpStatus($connection->getStatus());
         switch ($httpStatus->getType()) {
             case 'OK':
                 $PaymentParserData = PagSeguroPaymentParser::readSuccessXml($connection->getResponse());
                 $paymentUrl = self::buildCheckoutUrl($connectionData, $PaymentParserData->getCode());
                 LogPagSeguro::info("PagSeguroPaymentService.Register(" . $paymentRequest->toString() . ") - end {1}" . $PaymentParserData->getCode());
                 break;
             case 'BAD_REQUEST':
                 $errors = PagSeguroPaymentParser::readErrors($connection->getResponse());
                 $e = new PagSeguroServiceException($httpStatus, $errors);
                 LogPagSeguro::error("PagSeguroPaymentService.Register(" . $paymentRequest->toString() . ") - error " . $e->getOneLineMessage());
                 throw $e;
                 break;
             default:
                 $e = new PagSeguroServiceException($httpStatus);
                 LogPagSeguro::error("PagSeguroPaymentService.Register(" . $paymentRequest->toString() . ") - error " . $e->getOneLineMessage());
                 throw $e;
                 break;
         }
         return isset($paymentUrl) ? $paymentUrl : false;
     } catch (PagSeguroServiceException $e) {
         throw $e;
     } catch (Exception $e) {
         LogPagSeguro::error("Exception: " . $e->getMessage());
         throw $e;
     }
 }
 public function button()
 {
     $paymentRequest = new \PagSeguroPaymentRequest();
     $paymentRequest->setCurrency('BRL');
     $paymentRequest->setReference($this->options['dataPedido']['codigo']);
     foreach ($this->options['dataPedido']['ComponentProdutosDoPedido'] as $product) {
         $paymentRequest->addItem($product['component_produtos_id'], sprintf('%s %s', $product['ComponentProdutos']['titulo'], $product['ComponentProdutos']['chapeu']), $product['quantity'], $product['preco']);
     }
     if ($this->options['dataPedido']['desconto'] > 0) {
         $paymentRequest->setExtraAmount($this->options['dataPedido']['desconto'] * -1);
     }
     if ($this->options['dataPedido']['shipping_price'] > 0) {
         $paymentRequest->addItem('frete', sprintf('Frete por %s', $this->options['dataPedido']['ComponentFormasDeEntrega']['titulo']), 1, $this->options['dataPedido']['shipping_price']);
     }
     // customer information.
     $paymentRequest->setSender($this->options['dataUsuario']['titulo'], $this->options['dataUsuario']['email'], mb_substr($this->options['dataUsuario']['telefone'], 1, 2), preg_replace('/[^\\d]/', '', mb_substr($this->options['dataUsuario']['telefone'], 5)), 'CPF', $this->options['dataUsuario']['cpf']);
     $paymentRequest->setRedirectUrl($this->options['redirectUrl']);
     $paymentRequest->addParameter('notificationURL', $this->options['notificationURL']);
     try {
         // Register this payment request in PagSeguro to obtain the payment URL to redirect your customer.
         $url = $paymentRequest->register(new \PagSeguroAccountCredentials($this->credentials['email'], $this->credentials['token']));
         return sprintf('<a class="btn btn-fill btn-lg btn-aircode btn-aircode-primary" href="%s" target="_blank">Pagar com PagSeguro</a>', $url);
     } catch (\PagSeguroServiceException $e) {
         return $e->getMessage();
     }
 }
 public function pagSeguro()
 {
     /*
             /* Carrega a biblioteca do CodeIgniter responsável pela validação dos formulários */
     $this->load->library('form_validation', 'PagSeguroLibrary');
     $this->load->model('presentes_model');
     /* Define as tags onde a mensagem de erro será exibida na página */
     $this->form_validation->set_error_delimiters('<span>', '</span>');
     /* Define as regras para validação */
     $this->form_validation->set_rules('valor', 'decimal', 'required');
     /* Executa a validação e caso houver erro... */
     if ($this->form_validation->run() === FALSE) {
         /* Chama a função index do controlador */
         $this->load->view('pages/presentes.php');
         /* Senão, caso sucesso na validação... */
     } else {
         /* Recebe os dados do formulário (visão) */
         $data['valor'] = $this->input->post('valor');
         $data['descricao'] = 'Presente Luana e Juninho';
         //inserir data atual também....
         /* Chama a função inserir do modelo */
         $this->presentes_model->pagSeguro($data);
         //redirect('#contact');
     }
     /** INICIO PROCESSO PAGSEGURO */
     require_once APPPATH . 'libraries/PagSeguroLibrary/PagSeguroLibrary.php';
     /** INICIO PROCESSO PAGSEGURO */
     $paymentrequest = new PagSeguroPaymentRequest();
     $data = array('id' => '01', 'description' => 'Presente Luana e Juninho', 'quantity' => 1, 'amount' => $this->input->post('valor'));
     $item = new PagSeguroItem($data);
     /* $paymentRequest deve ser um objeto do tipo PagSeguroPaymentRequest */
     $paymentrequest->addItem($item);
     //Definindo moeda
     $paymentrequest->setCurrency('BRL');
     // 1- PAC(Encomenda Normal)
     // 2-SEDEX
     // 3-NOT_SPECIFIED(Não especificar tipo de frete)
     $paymentrequest->setShipping(3);
     //Url de redirecionamento
     //$paymentrequest->setRedirectURL($redirectURL);// Url de retorno
     $credentials = PagSeguroConfig::getAccountCredentials();
     //credenciais do vendedor
     //$compra_id = App_Lib_Compras::insert($produto);
     //$paymentrequest->setReference($compra_id);//Referencia;
     $url = $paymentrequest->register($credentials);
     header("Location: {$url}");
 }
Example #5
0
 public function paymentRequests($billId)
 {
     if (!isset($_SESSION['user'])) {
         redirect('site/login', 'refresh');
     }
     $billInfo = $this->billing->getBillingInfo($billId);
     $items = [];
     $sender = [];
     if (!empty($billInfo)) {
         $package = $billInfo['package'];
         $client = $billInfo['client'];
         $items[] = ['id' => 1, 'descricao' => $package->description, 'quantidade' => 1, 'valor' => $package->price, 'peso' => NULL, 'frete' => NULL];
         foreach ($billInfo['acquisition']['modifiers'] as $k => $modifier) {
             $items[] = ['id' => 2 + $k, 'descricao' => $modifier->description, 'quantidade' => 1, 'valor' => $modifier->price_modifier, 'peso' => NULL, 'frete' => NULL];
         }
         $sender = array('nome' => $this->userinfo->partialName($client->id), 'email' => $client->main_email, 'ddd' => NULL, 'telefone' => NULL);
     }
     if (!empty($items)) {
         $paymentRequest = new PagSeguroPaymentRequest();
         foreach ($items as $item) {
             $paymentRequest->addItem($item['id'], $item['descricao'], 1, (double) $item['valor']);
         }
         if ($sender != NULL) {
             $paymentRequest->setSender($sender['nome'], $sender['email'], $sender['ddd'], $sender['telefone']);
         }
         $paymentRequest->setCurrency('BRL');
         $paymentRequest->setReference($billId);
         $paymentRequest->setMaxAge(172800);
         $paymentRequest->setRedirectURL(site_url('client/profile'));
         $paymentRequest->setNotificationURL(site_url('PagSeguro/notification'));
         $checkoutUrl = NULL;
         try {
             $credentials = PagSeguroConfig::getAccountCredentials();
             $checkoutUrl = $paymentRequest->register($credentials);
         } catch (PagSeguroServiceException $e) {
             die(var_dump($e));
         }
         if ($checkoutUrl != NULL) {
             redirect($checkoutUrl, 'refresh');
         } else {
             $alert = ['message' => 'Ouve um problema ao emitir cobrança no PagSeguro', 'class' => 'alert-danger', 'icon' => 'glyphicon-remove'];
             $this->session->set_flashdata('alert', $alert);
             //redirect( 'client/acquisitions', 'refresh' );
         }
     }
     return FALSE;
 }
Example #6
0
 function buildPagseguroUrl($vars, $secure = true)
 {
     // Instantiate a new payment request
     $paymentRequest = new PagSeguroPaymentRequest();
     // Sets the currency
     $paymentRequest->setCurrency($vars->currency_code);
     if (empty($vars->item_code)) {
         $vars->item_code = '0001';
     }
     if (empty($vars->item_quantity)) {
         $vars->item_quantity = '1';
     }
     //format amount to proper format
     $vars->amount = number_format($vars->amount, 2, ".", ".");
     if ($vars->amount < 100) {
         if ($vars->amount < 10) {
             $vars->amount = '00' . $vars->amount;
         } else {
             $vars->amount = '0' . $vars->amount;
         }
     }
     if ($vars->amount <= 0) {
         $vars->amount = 1;
     }
     // Add an item for this payment request
     $paymentRequest->addItem($vars->item_code, $vars->item_name, $vars->item_quantity, $vars->amount);
     //	$paymentRequest->addItem('0001', 'Notebook prata', 1,002);
     // Add another item for this payment request
     //	$paymentRequest->addItem('0002', 'Notebook rosa',  1,002);
     // Sets a reference code for this payment request, it is useful to identify this payment in future notifications.
     $paymentRequest->setReference($vars->order_id);
     // Sets shipping information for this payment request
     //$CODIGO_SEDEX = PagSeguroShippingType::getCodeByType('SEDEX');
     //$paymentRequest->setShippingType($CODIGO_SEDEX);
     //$paymentRequest->setShippingAddress('',  'Av. Brig. Faria Lima',  '1384', 'apto. 114', 'Jardim Paulistano', 'São Paulo', 'SP', 'BRA');
     // Sets your customer information.
     //$paymentRequest->setSender('João Comprador', '*****@*****.**', '11', '56273440');
     $paymentRequest->setRedirectUrl($vars->return);
     try {
         /*
          * #### Crendencials ##### 
          * Substitute the parameters below with your credentials (e-mail and token)
          * You can also get your credentails from a config file. See an example:
          * $credentials = PagSeguroConfig::getAccountCredentials();
          */
         //$credentials = new PagSeguroAccountCredentials("*****@*****.**", "your_token_here");
         $credentials = new PagSeguroAccountCredentials($vars->sellar_email, $vars->token);
         // Register this payment request in PagSeguro, to obtain the payment URL for redirect your customer.
         $url = $paymentRequest->register($credentials);
     } catch (PagSeguroServiceException $e) {
         die($e->getMessage());
     }
     /*if ($secure) {
     			$url = 'https://' . $url;
     		}*/
     return $url;
 }
Example #7
0
File: ad.php Project: caina/pando
 function payment()
 {
     require_once APPPATH . 'third_party/PagSeguroLibrary/PagSeguroLibrary.php';
     $this->load->model('../libraries/anuncios/model/ad_price_model', 'price');
     $this->load->model('user_model');
     // valida se o anuncio e o preco realmente existem
     if (!$this->price->get($this->input->post('price_id', TRUE))->exists() || !$this->ad_model->get($this->input->post('ad_id', TRUE))->is_mine()) {
         set_message("Operação inválida", 2);
         redirect(site_url("act/anuncios/ad/home_page"));
     }
     $paymentRequest = new PagSeguroPaymentRequest();
     $paymentRequest->AddItem($this->price->object->id, $this->price->object->title, 1, '0.10');
     $paymentRequest->setShippingType(3);
     $user_object = $this->user_model->get();
     // dump($user_object);
     // precisamos dos dados de cidade, bairro, rua e numero
     $paymentRequest->setShippingAddress(str_replace(array("-", "."), "", $user_object->zip_code), @$user_object->street_name, @$user_object->number, '', @$user_object->district, @$user_object->city_name, @$user_object->state_letter, 'BRA');
     $type = !empty($user_object->cpf) ? "CPF" : "CNPJ";
     $type_value = !empty($user_object->cpf) ? $user_object->cpf : $user_object->cnpj;
     $paymentRequest->setSender($user_object->name, $user_object->username, '11', '', $type, $type_value);
     $paymentRequest->setCurrency("BRL");
     $paymentRequest->setReference($this->ad_model->object->id);
     $paymentRequest->setRedirectUrl(site_url("act/anuncios/ad/home_page"));
     $paymentRequest->addParameter('notificationURL', site_url("pagseguro/notification/anuncios/" . $this->ad_model->object->id));
     try {
         $credentials = PagSeguroConfig::getAccountCredentials();
         // getApplicationCredentials()
         $checkoutUrl = $paymentRequest->register($credentials);
     } catch (PagSeguroServiceException $e) {
         set_message("Erro ao gerar link pagamento: " . $e->getMessage(), 2);
         redirect(site_url("act/anuncios/ad/home_page"));
     }
     $this->data["ad"] = $this->ad_model->object;
     $this->data["price"] = $this->price->object;
     $this->load_view("../libraries/anuncios/views/anuncio_view/payment");
 }
 public static function createPreApprovalRequest(PagSeguroCredentials $credentials, PagSeguroPaymentRequest $paymentRequest)
 {
     LogPagSeguro::info("PagSeguroPreApprovalService.createPreApprovalRequest(" . $paymentRequest->toString() . ") - begin");
     $connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME);
     $data = array_merge($connectionData->getCredentials()->getAttributesMap(), PagSeguroPreApprovalParser::getData($paymentRequest));
     // On preApproval, credentials goes with data, not in the url query string
     try {
         $connection = new PagSeguroHttpConnection();
         $connection->post(self::buildCheckoutRequestUrl($connectionData), $data, $connectionData->getServiceTimeout(), $connectionData->getCharset());
         $httpStatus = new PagSeguroHttpStatus($connection->getStatus());
         switch ($httpStatus->getType()) {
             case 'OK':
                 $PaymentParserData = PagSeguroPreApprovalParser::readSuccessXml($connection->getResponse());
                 $paymentReturn = array('code' => $PaymentParserData->getCode(), 'cancelUrl' => self::buildCancelUrl($connectionData, $PaymentParserData->getCode()), 'checkoutUrl' => self::buildCheckoutUrl($connectionData, $PaymentParserData->getCode()));
                 LogPagSeguro::info("PagSeguroPreApprovalService.createPreApprovalRequest(" . $paymentRequest->toString() . ") - end {1}" . $PaymentParserData->getCode());
                 break;
             case 'BAD_REQUEST':
                 $errors = PagSeguroPreApprovalParser::readErrors($connection->getResponse());
                 $e = new PagSeguroServiceException($httpStatus, $errors);
                 LogPagSeguro::error("PagSeguroPreApprovalService.createPreApprovalRequest(" . $paymentRequest->toString() . ") - error " . $e->getOneLineMessage());
                 throw $e;
                 break;
             default:
                 $e = new PagSeguroServiceException($httpStatus);
                 LogPagSeguro::error("PagSeguroPreApprovalService.createPreApprovalRequest(" . $paymentRequest->toString() . ") - error " . $e->getOneLineMessage());
                 throw $e;
                 break;
         }
         return isset($paymentReturn) ? $paymentReturn : false;
     } catch (PagSeguroServiceException $e) {
         throw $e;
     } catch (Exception $e) {
         LogPagSeguro::error("Exception: " . $e->getMessage());
         throw $e;
     }
 }
 private function makeRequisition()
 {
     require_once VENDOR_PATH . 'PagSeguro/PagSeguroLibrary.php';
     $payment = new \PagSeguroPaymentRequest();
     $payment->setCurrency('BRL');
     $payment->addItem('0001', $this->productName, $this->productQuantity, $this->productPrice);
     $payment->setReference($this->pid);
     $payment->setShippingType(3);
     $payment->setsender($this->clientName, $this->clientMail, $this->clientAreaCode, $this->clientPhone);
     $payment->setRedirectUrl($this->redirectUrl);
     $credentials = \PagSeguroConfig::getAccountCredentials();
     if (defined('ALLOW_PAYMENT_REQUEST') and ALLOW_PAYMENT_REQUEST === true) {
         $this->paymentUrl = $payment->register($credentials);
     } else {
         $this->paymentUrl = '/loja/checkout/pid/' . $this->pid . '/continue/ok/';
     }
 }
 public function pay($id)
 {
     \PagSeguroLibrary::init();
     \PagSeguroConfig::setEnvironment('production');
     $this->plan = Plans::find($id);
     $this->client = User::find(Auth::user()->id);
     $this->payment = Payments::create(['plan_name' => $this->plan->name, 'plan_value' => $this->plan->value, 'plan_id' => $this->plan->id, 'user_id' => $this->client->id, 'confirmed' => 0]);
     // Instantiate a new payment request
     $paymentRequest = new \PagSeguroPaymentRequest();
     // Set the currency
     $paymentRequest->setCurrency("BRL");
     /* // Add an item for this payment request
        $paymentRequest->addItem('0001', 'Sempre da Negócio - Plano '.$this->plan->name, 1, $this->plan->value);*/
     $paymentRequest->addItem($this->plan->id, 'Sempre da Negócio - Plano ' . $this->plan->name, 1, $this->plan->value);
     // Set a reference code for this payment request. It is useful to identify this payment
     // in future notifications.
     $paymentRequest->setReference($this->payment->id);
     //Create object PagSeguroShipping
     $shipping = new \PagSeguroShipping();
     //Set Type Shipping
     $type = new \PagSeguroShippingType(3);
     $shipping->setType($type);
     //Set address of client
     $data = array('postalCode' => $this->client->zipcode, 'street' => $this->client->address, 'number' => $this->client->number, 'city' => $this->client->city, 'state' => $this->client->state);
     $address = new \PagSeguroAddress($data);
     $shipping->setAddress($address);
     //Add Shipping to Payment Request
     $paymentRequest->setShipping($shipping);
     // Set your customer information.
     $phone = str_replace(['(', ')', ' ', '-'], ['', '', '', ''], $this->client->phone);
     $paymentRequest->setSender($this->client->name, $this->client->email_responsible, substr($phone, 0, 2), substr($phone, 2));
     try {
         /*
                      * #### Credentials #####
                      * Replace the parameters below with your credentials (e-mail and token)
                      * You can also get your credentials from a config file. See an example:
                      * $credentials = PagSeguroConfig::getAccountCredentials();
                     //  */
         $credentials = new \PagSeguroAccountCredentials($this->email, $this->token);
         // Register this payment request in PagSeguro to obtain the payment URL to redirect your customer.
         $onlyCheckoutCode = true;
         $code = $paymentRequest->register($credentials, $onlyCheckoutCode);
         return view('site.pages.confirma_pagamento', compact('code'));
     } catch (\PagSeguroServiceException $e) {
         die($e->getMessage());
     }
 }
 /**
  * Pagseguro
  *
  * @access public
  * @param int(11) idVenda
  */
 public function pagseguro($idVenda)
 {
     if ($idVenda) {
         $hasError = false;
         $errorList = array();
         // procura sua transação no banco de dados
         $venda = $this->db->get_where('tabela_vendas', array('idVenda' => $idVenda))->row();
         // validações
         if (!is_object($venda)) {
             $hasError = true;
             $errorList[] = array('message' => 'Não foi possível localizar sua compra.');
         }
         if (!$hasError) {
             // Instantiate a new payment request
             $paymentRequest = new PagSeguroPaymentRequest();
             // Sets the currency
             $paymentRequest->setCurrency("BRL");
             // Sets a reference code for this payment request, it is useful to
             // identify this payment in future notifications.
             $paymentRequest->setReference($venda->idVenda);
             // Add an item for this payment request
             $paymentRequest->addItem('0001', 'nome do item', 1, number_format($venda->valorDevido, 2, '.', ''));
             $paymentRequest->setShippingType(3);
             $paymentRequest->setShippingAddress(str_replace('-', '', str_replace('.', '', $venda->CEP)), utf8_decode($venda->endereco), $venda->numero, utf8_decode($venda->complemento), utf8_decode($venda->bairro), utf8_decode($venda->cidade), $venda->sigla ? $venda->sigla : '', 'BRA');
             // Sets your customer information.
             $telefone = $venda->telefone1;
             // 				$paymentRequest->setSenderName(truncate($userObj->nome, 40));
             $paymentRequest->setSenderEmail($venda->email);
             $paymentRequest->setSenderPhone(substr($telefone, 0, 2), substr($telefone, 2, 8));
             // TODO Alterar a URL de RETORNO DE PAGAMENTO SUA URL
             $paymentRequest->setRedirectUrl($this->urlRetornoPagamento);
             $paymentRequest->setMaxAge(86400 * 3);
             try {
                 $credentials = new PagSeguroAccountCredentials($this->config->item('pagseguroAccount'), $this->config->item('pagseguroToken'));
                 $url = $paymentRequest->register($credentials);
                 $parts = parse_url($url);
                 parse_str($parts['query'], $query);
                 if ($this->input->is_ajax_request()) {
                     $data = array('hasError' => FALSE, 'checkoutCode' => $query['code']);
                     $this->output->set_content_type('application/json')->set_output(json_encode($data));
                 } else {
                     redirect($url);
                 }
             } catch (PagSeguroServiceException $e) {
                 $hasError = true;
                 $errorList[] = array('message' => 'Ocorreu um erro ao comunicar com o Pagseguro.' . $e->getCode() . ' - ' . $e->getMessage());
             }
         }
     } else {
         redirect(base_url());
     }
 }
 public static function main()
 {
     // Instantiate a new payment request
     $paymentRequest = new PagSeguroPaymentRequest();
     // Set the currency
     $paymentRequest->setCurrency("BRL");
     $finalPrice = (double) self::$productData->price - self::$productData->discount;
     // Add an item for this payment request
     $paymentRequest->addItem('0001', self::$productData->name, 1, $finalPrice);
     // Set a reference code for this payment request. It is useful to identify this payment
     // in future notifications.
     $paymentRequest->setReference(self::$referenceID);
     // Set shipping information for this payment request
     // 1 = PAC
     // 2 = SEDEX
     $sedexCode = PagSeguroShippingType::getCodeByType('PAC');
     $paymentRequest->setShippingType($sedexCode);
     $paymentRequest->setShippingAddress(self::$orderData->zipcode, self::$orderData->street, self::$orderData->number, self::$orderData->complement, self::$orderData->local, self::$orderData->city, self::$orderData->state, 'BRA');
     //$paymentRequest->setShippingCost(new BigDecimal("23.30"));
     // Adapta nome ao padrão do PagSeguro ("Nome Sobrenome")
     $name = self::$accountData->name;
     $name = preg_replace('/\\d/', '', $name);
     $name = preg_replace('/[\\n\\t\\r]/', ' ', $name);
     $name = preg_replace('/\\s(?=\\s)/', '', $name);
     $name = trim($name);
     $name = explode(' ', $name);
     if (count($name) == 1) {
         $name[] = ' dos Santos';
     }
     $name = implode(' ', $name);
     // Set your customer information.
     $paymentRequest->setSender($name, self::$accountData->email, '11', '56273440', 'CPF', '156.009.442-76');
     $paymentRequest->addParameter('senderCPF', self::$accountData->cpf);
     $paymentRequest->addParameter('senderAreaCode', 11);
     $paymentRequest->addParameter('senderCPF', 36251520884);
     //self::$accountData->cpf);
     $paymentRequest->addParameter('senderPhone', 921231232);
     $paymentRequest->addParameter('senderBornDate', "11/11/2012");
     // Set the url used by PagSeguro to redirect user after checkout process ends
     $paymentRequest->setRedirectUrl($_SERVER['SERVER_NAME'] . Config::read('page.url.order.completed') . '/' . self::$referenceID);
     // Add checkout metadata information
     // $paymentRequest->addMetadata('PASSENGER_CPF', '15600944276', 1);
     // $paymentRequest->addMetadata('GAME_NAME', 'DOTA');
     // $paymentRequest->addMetadata('PASSENGER_PASSPORT', '23456', 1);
     // Another way to set checkout parameters
     $paymentRequest->addParameter('notificationURL', $_SERVER['SERVER_NAME'] . Config::read('page.url.order.notifications'));
     $paymentRequest->addParameter('senderBornDate', '07/05/1981');
     // $paymentRequest->addIndexedParameter('itemId', '0003', 3);
     // $paymentRequest->addIndexedParameter('itemDescription', 'Notebook Preto', 3);
     // $paymentRequest->addIndexedParameter('itemQuantity', '1', 3);
     // $paymentRequest->addIndexedParameter('itemAmount', '200.00', 3);
     // Add discount per payment method
     //$paymentRequest->addPaymentMethodConfig('CREDIT_CARD', 1.00, 'DISCOUNT_PERCENT');
     //$paymentRequest->addPaymentMethodConfig('EFT', 2.90, 'DISCOUNT_PERCENT');
     //$paymentRequest->addPaymentMethodConfig('BOLETO', 10.00, 'DISCOUNT_PERCENT');
     //$paymentRequest->addPaymentMethodConfig('DEPOSIT', 3.45, 'DISCOUNT_PERCENT');
     //$paymentRequest->addPaymentMethodConfig('BALANCE', 0.01, 'DISCOUNT_PERCENT');
     // Add installment without addition per payment method
     $paymentRequest->addPaymentMethodConfig('CREDIT_CARD', 6, 'MAX_INSTALLMENTS_NO_INTEREST');
     // Add installment limit per payment method
     $paymentRequest->addPaymentMethodConfig('CREDIT_CARD', 8, 'MAX_INSTALLMENTS_LIMIT');
     // Add and remove a group and payment methods
     //$paymentRequest->acceptPaymentMethodGroup('CREDIT_CARD', 'DEBITO_ITAU');
     //$paymentRequest->excludePaymentMethodGroup('BOLETO', 'BOLETO');
     try {
         /*
          * #### Credentials #####
          * Replace the parameters below with your credentials
          * You can also get your credentials from a config file. See an example:
          * $credentials = new PagSeguroAccountCredentials("*****@*****.**",
          * "E231B2C9BCC8474DA2E260B6C8CF60D3");
          */
         // seller authentication
         $credentials = PagSeguroConfig::getAccountCredentials();
         // application authentication
         //$credentials = PagSeguroConfig::getApplicationCredentials();
         //$credentials->setAuthorizationCode("E231B2C9BCC8474DA2E260B6C8CF60D3");
         // Register this payment request in PagSeguro to obtain the payment URL to redirect your customer.
         $url = $paymentRequest->register($credentials);
         return $url;
     } catch (PagSeguroServiceException $e) {
         die($e->getMessage());
     }
 }
 /**
  * Process Payment
  *
  * Process payments trough the PagSeguro gateway.
  *
  * @return   void
  * @since    1.0
  */
 function process_payment($purchase_data)
 {
     global $edd_options;
     // check there is a gateway name
     if (!isset($purchase_data['post_data']['edd-gateway'])) {
         return;
     }
     // get credentials
     $credentials = $this->get_credentials();
     // check credentials have been set
     if (is_null($credentials['email']) || is_null($credentials['token'])) {
         edd_set_error(0, __('Please enter your PagSeguro Client Email and Token in settings', 'edd-pagseguro-gateway'));
         edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
     }
     // get payment
     $payment_data = array('price' => $purchase_data['price'], 'date' => $purchase_data['date'], 'user_email' => $purchase_data['user_email'], 'purchase_key' => $purchase_data['purchase_key'], 'currency' => edd_get_option('currency', 'BRL'), 'downloads' => $purchase_data['downloads'], 'user_info' => $purchase_data['user_info'], 'cart_details' => $purchase_data['cart_details'], 'status' => 'pending');
     // insert pending payment
     $payment = edd_insert_payment($payment_data);
     if (!$payment) {
         // problems? send back
         edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
     } else {
         // require PagSeguro files
         $this->load_pagseguro_sdk();
         // verify classes exists
         if (!class_exists('PagSeguroPaymentRequest')) {
             edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
         }
         // create payment request
         $paymentRequest = new PagSeguroPaymentRequest();
         // sets the currency
         $paymentRequest->setCurrency('BRL');
         // cart summary
         $cart_summary = edd_get_purchase_summary($purchase_data, false);
         // format total price
         $total_price = number_format($purchase_data['price'], 2, '.', '');
         // payment request details
         $paymentRequest->addItem('01', sanitize_text_field(substr($cart_summary, 0, 95)), '1', strval($total_price));
         // sets the reference code for this request
         $paymentRequest->setReference($payment);
         // sets customer information
         $paymentRequest->setSender(sanitize_text_field($purchase_data['user_info']['first_name'] . ' ' . $purchase_data['user_info']['last_name']), $purchase_data['user_email']);
         // redirect url
         $paymentRequest->setRedirectUrl(add_query_arg('payment-confirmation', 'pagseguro', edd_get_success_page_uri()));
         // IPN URL
         $paymentRequest->addParameter('notificationURL', get_site_url());
         /* TRY CHECKOUT */
         try {
             // generate credentials
             $credentials = new PagSeguroAccountCredentials($credentials['email'], $credentials['token']);
             // register this payment request in PagSeguro, to obtain the payment URL for redirect your customer
             $checkout_uri = $paymentRequest->register($credentials);
             if (gettype($checkout_uri) != 'string') {
                 throw new exception($checkout_uri);
             }
             // empty cart
             edd_empty_cart();
             // send the user to PagSeguro
             wp_redirect($checkout_uri);
             die;
         } catch (Exception $e) {
             //catch exception
             wp_mail(get_bloginfo('admin_email'), __('PagSeguro Checkout Error', 'edd-pagseguro-gateway'), $e->getMessage());
             edd_set_error('pagseguro_exception', $e->getMessage());
             edd_send_back_to_checkout('?payment-mode=' . $purchase_data['post_data']['edd-gateway']);
         }
     }
 }
	public function iniciaPagamentoPagSeguro() {
        $paymentRequest = new PagSeguroPaymentRequest();

        $paymentRequest->setCurrency("BRL");
        $this->razao = $this->razao . $this->transacaoID;
        //Itens compra | Não posso colocar o dinheiro por partes por conta do cupom
        $paymentRequest->addItem('0001', $this->razao, 1, $this->valor);
        
        $paymentRequest->setReference($this->transacaoID);

        // Dados do usuario
        $paymentRequest->setSender(
            $this->nomeUsuario,
            $this->emailUsuario
        );
        // Url de retorno após pagamento
        $paymentRequest->setRedirectUrl($this->system->getUrlSite());

        // Url de notificação de modificação de status
        $paymentRequest->addParameter('notificationURL', $this->notificationURL);
        
        try {
            $credentials = $this->obterCredenciaisPagSeguro();                           
            $url = $paymentRequest->register($credentials);
            return $url;
        } catch (PagSeguroServiceException $e) {
        	print_r($e);
        	$erros = array();
        	foreach($e->getErrors() as $erro)
        		$erros[] = $erro->getMessage();
        	echo '<script>alert("' . implode('<br/>', $erros) . '")</script>';
            die;
        }   
	}
Example #15
0
if (count($_POST)) {
    $donateVal = $params->get('itemAmount1');
    $donateEmail = $session->account->email;
    $donateAcc = $session->account->account_id;
    $donateInf = sprintf('%s ' . strtoupper($donateCoin), number_format(floor(($donateVal >= $initPromo ? $donateVal + $donatePromo * $donateVal / 100 : $donateVal) / $rate)));
    $donateIp = $_SERVER['REMOTE_ADDR'];
    $donateRef = strtoupper(uniqid(true));
    $donateUser = $session->account->userid;
    $donateBy = $params->get('payment_type');
    if ($donateBy != 'PagSeguro') {
        $errorMessage = 'Somente PagSeguro';
    } else {
        if ($donateVal < $donateMin) {
            $errorMessage = sprintf('O valor da doação deve ser maior ou igual a %s R$!', $this->formatCurrency($donateMin));
        } else {
            $transactionRequest = new PagSeguroPaymentRequest();
            $transactionRequest->setCurrency("BRL");
            $transactionRequest->addItem('01', $donateInf, '1', str_replace(",", "", $this->formatCurrency($donateVal)));
            $transactionRequest->setReference($donateRef);
            $transactionRequest->setNotificationURL($this->url('doa', 'notification', array('_host' => true)));
            $transactionRequest->setRedirectURL($this->url('doa', 'return', array('_host' => true)));
            $transactionCredentials = new PagSeguroAccountCredentials(Flux::config('EmailPagSeguro'), Flux::config('TokenPagseguro'));
            $url = $transactionRequest->register($transactionCredentials);
            if ($url) {
                $sql = "INSERT INTO {$session->loginAthenaGroup->loginDatabase}.{$donateTable} ";
                $sql .= "(account_id, userid, email, payment_id, payment_ip, payment_type, payment, payment_date) ";
                $sql .= "VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
                $sth = $session->loginAthenaGroup->connection->getStatement($sql);
                $res = $sth->execute(array($donateAcc, $donateUser, $donateEmail, $donateRef, $donateIp, $donateBy, $donateVal));
                header('Location:' . $url . '');
            } else {
 public static function main()
 {
     // Instantiate a new payment request
     $paymentRequest = new PagSeguroPaymentRequest();
     // Set the currency
     $paymentRequest->setCurrency("BRL");
     // Add an item for this payment request
     $paymentRequest->addItem('0001', 'Notebook prata', 2, 430.0);
     // Add another item for this payment request
     $paymentRequest->addItem('0002', 'Notebook rosa', 2, 560.0);
     // Set a reference code for this payment request, it is useful to identify this payment
     // in future notifications.
     $paymentRequest->setReference("REF123");
     // Set shipping information for this payment request
     $sedexCode = PagSeguroShippingType::getCodeByType('SEDEX');
     $paymentRequest->setShippingType($sedexCode);
     $paymentRequest->setShippingAddress('01452002', 'Av. Brig. Faria Lima', '1384', 'apto. 114', 'Jardim Paulistano', 'São Paulo', 'SP', 'BRA');
     // Set your customer information.
     $paymentRequest->setSender('João Comprador', '*****@*****.**', '11', '56273440', 'CPF', '156.009.442-76');
     // Set the url used by PagSeguro to redirect user after checkout process ends
     $paymentRequest->setRedirectUrl("http://www.lojamodelo.com.br");
     // Add checkout metadata information
     $paymentRequest->addMetadata('PASSENGER_CPF', '15600944276', 1);
     $paymentRequest->addMetadata('GAME_NAME', 'DOTA');
     $paymentRequest->addMetadata('PASSENGER_PASSPORT', '23456', 1);
     // Another way to set checkout parameters
     $paymentRequest->addParameter('notificationURL', 'http://www.lojamodelo.com.br/nas');
     $paymentRequest->addParameter('senderBornDate', '07/05/1981');
     $paymentRequest->addIndexedParameter('itemId', '0003', 3);
     $paymentRequest->addIndexedParameter('itemDescription', 'Notebook Preto', 3);
     $paymentRequest->addIndexedParameter('itemQuantity', '1', 3);
     $paymentRequest->addIndexedParameter('itemAmount', '200.00', 3);
     try {
         /*
          * #### Credentials #####
          * Replace the parameters below with your credentials (e-mail and token)
          * You can also get your credentials from a config file. See an example:
          * $credentials = PagSeguroConfig::getAccountCredentials();
          */
         $credentials = new PagSeguroAccountCredentials("*****@*****.**", "E231B2C9BCC8474DA2E260B6C8CF60D3");
         // Register this payment request in PagSeguro to obtain the checkout code
         $onlyCheckoutCode = true;
         $code = $paymentRequest->register($credentials, $onlyCheckoutCode);
         self::printPaymentUrl($code);
     } catch (PagSeguroServiceException $e) {
         die($e->getMessage());
     }
 }
/**
 * Processa o formulário, 
 */
function process_form()
{
    // var_dump($_POST);
    // die();
    require_once "PagSeguroLibrary/PagSeguroLibrary.php";
    $id = $_POST['item_id'];
    $descricao = $_POST['item_descricao'];
    $qtd = $_POST['item_qtd'];
    $valor = $_POST['item_valor'];
    $valor = str_replace(",", ".", $valor);
    //Instancia uma requisicao de pagamento
    $paymentRequest = new PagSeguroPaymentRequest();
    //Seta a moeda
    $paymentRequest->setCurrency("BRL");
    //Adiciona os itens para gerar a url
    $paymentRequest->addItem($id, $descricao, $qtd, $valor);
    //Seta o ambiente de producao, se é Sandbox, ou production
    $is_sandbox = get_option('ps_config_enable_sandbox');
    if (strlen($is_sandbox) > 0) {
        PagSeguroConfig::setEnvironment('sandbox');
    } else {
        PagSeguroConfig::setEnvironment('production');
    }
    /* Infos seguintes apenas para referencia*/
    // Add another item for this payment request
    //$paymentRequest->addItem('0002', 'Notebook rosa', 2, 1.00);
    // Sets a reference code for this payment request, it is useful to identify this payment in future notifications.
    //$paymentRequest->setReference($dadosComprador["codReference"]);
    // Sets shipping information for this payment request
    // 		$CODIGO_SEDEX = PagSeguroShippingType::getCodeByType('SEDEX');
    // 		$paymentRequest->setShippingType($CODIGO_SEDEX);
    // 		$paymentRequest->setShippingAddress($dadosComprador["cep"], $dadosComprador["logradouro"], $dadosComprador["numero"], $dadosComprador["complemento"], $dadosComprador["bairro"], $dadosComprador["cidade"], $dadosComprador["estado"], 'BRA');
    // Sets your customer information.
    //$paymentRequest->setSender($dadosComprador["nome"] . ' ' . $dadosComprador["sobrenome"], $dadosComprador["email"]);
    //Seta a URL de retorno
    $paymentRequest->setRedirectUrl(get_option('ps_config_return_url'));
    try {
        //Inicializa as credenciais
        $credentials = new PagSeguroAccountCredentials(get_option('ps_config_auth_email'), get_option('ps_config_auth_token'));
        //obtem-se a URL da compra
        $url = $paymentRequest->register($credentials);
        //faz o redirect para a url do pagseguro
        wp_redirect($url);
        exit;
    } catch (PagSeguroServiceException $e) {
        die($e->getMessage());
    }
}
                // foi recebido um valor a pagar maior que o saldo devedor
                $valorValido = false;
            }
        } else {
            // redirecionamos o aluno de volta com uma mensagem de erro
            header('Location: ../visualizar_informacoes_curso.php?' . 'mensagem=Erro com o banco de dados', true, "302");
            die;
        }
    } else {
        // redirecionamos o aluno de volta com uma mensagem de erro
        header('Location: ../visualizar_informacoes_curso.php?' . 'mensagem=Valor enviado inválido', true, "302");
        die;
    }
    // agora enviamos o usuário para a tela de pagamento
    require '../PagSeguroLibrary/PagSeguroLibrary.php';
    $reqPagamento = new PagSeguroPaymentRequest();
    $reqPagamento->addItem('0001', 'Parcela do curso de Homeopatia', 1, number_format($valorRecebido, 2));
    $reqPagamento->setCurrency("BRL");
    $reqPagamento->setSender($aluno->getNome(), $aluno->getEmail(), mb_substr($aluno->getTelefone(), 0, 2), mb_substr($aluno->getTelefone(), 2));
    $reqPagamento->setShippingAddress($aluno->getCep(), $aluno->getRua(), $aluno->getNumero(), $aluno->getComplemento(), $aluno->getBairro(), $aluno->getCidade(), $aluno->getEstado(), $aluno->getPais());
    $reqPagamento->setShippingType(3);
    // a referência desse pagamente será a letra "M" de mensalidade,
    // seguida do número de inscrição desse aluno
    $reqPagamento->setReference("M" . $aluno->getNumeroInscricao());
    $credenciais = PagSeguroConfig::getAccountCredentials();
    $url = $reqPagamento->register($credenciais);
    header('Location: ' . $url, true, "302");
    die;
}
// caso não tenha caído no caso anterior, redirecionamos o usuário
// para o index
 /**
  * Create PagSeguro payment request html with payment url
  * @return string
  */
 private function createPaymentRequest()
 {
     $helper = Mage::helper('pagseguro');
     // Get references that stored in the database
     $reference = $helper->getStoreReference();
     $paymentRequest = new PagSeguroPaymentRequest();
     $paymentRequest->setCurrency(PagSeguroCurrencies::getIsoCodeByName(self::REAL));
     $paymentRequest->setReference($reference . $this->order->getId());
     //Order ID
     $paymentRequest->setShipping($this->getShippingInformation());
     //Shipping
     $paymentRequest->setSender($this->getSenderInformation());
     //Sender
     $paymentRequest->setItems($this->getItensInformation());
     //Itens
     $paymentRequest->setShippingType(SHIPPING_TYPE);
     $paymentRequest->setShippingCost(number_format($this->order->getShippingAmount(), 2, '.', ''));
     $paymentRequest->setNotificationURL($this->getNotificationURL());
     $helper->getDiscount($paymentRequest);
     //Define Redirect Url
     $redirectUrl = $this->getRedirectUrl();
     if (!empty($redirectUrl) and $redirectUrl != null) {
         $paymentRequest->setRedirectURL($redirectUrl);
     } else {
         $paymentRequest->setRedirectURL(Mage::getUrl() . 'checkout/onepage/success/');
     }
     //Define Extra Amount Information
     $paymentRequest->setExtraAmount($this->extraAmount());
     try {
         $paymentUrl = $paymentRequest->register($this->getCredentialsInformation());
     } catch (PagSeguroServiceException $ex) {
         Mage::log($ex->getMessage());
         $this->redirectUrl(Mage::getUrl() . 'checkout/onepage');
     }
     return $paymentUrl;
 }
Example #20
0
 protected function index()
 {
     $this->language->load('payment/pagseguro');
     $this->data['button_confirm'] = $this->language->get('button_confirm_pagseguro');
     $this->data['text_information'] = $this->language->get('text_information');
     $this->data['text_wait'] = $this->language->get('text_wait');
     require_once DIR_SYSTEM . 'library/PagSeguroLibrary/PagSeguroLibrary.php';
     // Altera a codificação padrão da API do PagSeguro (ISO-8859-1)
     PagSeguroConfig::setApplicationCharset('UTF-8');
     $mb_substr = function_exists("mb_substr") ? true : false;
     $this->load->model('checkout/order');
     $order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);
     $paymentRequest = new PagSeguroPaymentRequest();
     /* 
      * Dados do cliente
      */
     // Ajuste no nome do comprador para o máximo de 50 caracteres exigido pela API
     $customer_name = trim($order_info['payment_firstname']) . ' ' . trim($order_info['payment_lastname']);
     if ($mb_substr) {
         $customer_name = mb_substr($customer_name, 0, 50, 'UTF-8');
     } else {
         $customer_name = utf8_encode(substr(utf8_decode($customer_name), 0, 50));
     }
     if ($order_info['currency_code'] != "BRL") {
         $this->log->write("PagSeguro :: Pedido " . $this->session->data['order_id'] . ". O PagSeguro só aceita moeda BRL (Real) e a loja está configurada para a moeda " . $order_info['currency_code']);
     }
     $paymentRequest->setCurrency($order_info['currency_code']);
     $paymentRequest->setSenderName(trim($customer_name));
     $paymentRequest->setSenderEmail(trim($order_info['email']));
     // há limitação de 60 caracteres de acordo com a API
     // OpenCart não separa o DDD do número do telefone. Assim, tentamos separá-los.
     $telefone = preg_replace("/[^0-9]/", '', $order_info['telephone']);
     $telefone = ltrim($telefone, '0');
     if (strlen($telefone) >= 9) {
         $paymentRequest->setSenderPhone(substr($telefone, 0, 2), substr($telefone, 2, strlen($telefone) - 1));
     }
     /* 
      * Frete
      */
     $tipo_frete = $this->config->get('pagseguro_tipo_frete');
     if ($tipo_frete) {
         $paymentRequest->setShippingType($tipo_frete);
     } else {
         $paymentRequest->setShippingType(3);
         // 3: Não especificado
     }
     $this->load->model('localisation/zone');
     if ($this->cart->hasShipping()) {
         $zone = $this->model_localisation_zone->getZone($order_info['shipping_zone_id']);
         // Endereço para entrega
         $paymentRequest->setShippingAddress(array('postalCode' => preg_replace("/[^0-9]/", '', $order_info['shipping_postcode']), 'street' => $order_info['shipping_address_1'], 'number' => '', 'complement' => '', 'district' => $order_info['shipping_address_2'], 'city' => $order_info['shipping_city'], 'state' => isset($zone['code']) ? $zone['code'] : '', 'country' => $order_info['shipping_iso_code_3']));
     } else {
         $zone = $this->model_localisation_zone->getZone($order_info['payment_zone_id']);
         // Endereço para entrega
         $paymentRequest->setShippingAddress(array('postalCode' => preg_replace("/[^0-9]/", '', $order_info['payment_postcode']), 'street' => $order_info['payment_address_1'], 'number' => '', 'complement' => '', 'district' => $order_info['payment_address_2'], 'city' => $order_info['payment_city'], 'state' => isset($zone['code']) ? $zone['code'] : '', 'country' => $order_info['payment_iso_code_3']));
     }
     /*
      * Produtos
      */
     foreach ($this->cart->getProducts() as $product) {
         $options_names = '';
         foreach ($product['option'] as $option) {
             $options_names .= '/' . $option['name'];
         }
         // limite de 100 caracteres para a descrição do produto
         if ($mb_substr) {
             $description = mb_substr($product['model'] . '-' . $product['name'] . $options_names, 0, 100, 'UTF-8');
         } else {
             $description = utf8_encode(substr(utf8_decode($product['model'] . '-' . $product['name'] . $options_names), 0, 100));
         }
         $item = array('id' => $product['product_id'], 'description' => trim($description), 'quantity' => $product['quantity'], 'amount' => $this->currency->format($product['price'], $order_info['currency_code'], false, false));
         // O frete será calculado pelo PagSeguro.
         if ($tipo_frete) {
             $peso = $this->getPesoEmGramas($product['weight_class_id'], $product['weight']) / $product['quantity'];
             $item['weight'] = round($peso);
         }
         $paymentRequest->addItem($item);
     }
     // Referência do pedido no PagSeguro
     if ($this->config->get('pagseguro_posfixo') != "") {
         $paymentRequest->setReference($this->session->data['order_id'] . "_" . $this->config->get('pagseguro_posfixo'));
     } else {
         $paymentRequest->setReference($this->session->data['order_id']);
     }
     // url para redirecionar o comprador ao finalizar o pagamento
     $paymentRequest->setRedirectUrl($this->url->link('checkout/success'));
     // url para receber notificações sobre o status das transações
     $paymentRequest->setNotificationURL($this->url->link('payment/pagseguro/callback'));
     // obtendo frete, descontos e taxas
     $total = $this->currency->format($order_info['total'] - $this->cart->getSubTotal(), $order_info['currency_code'], false, false);
     if ($total > 0) {
         $item = array('id' => '-', 'description' => $this->language->get('text_extra_amount'), 'quantity' => 1, 'amount' => $total);
         $paymentRequest->addItem($item);
     } else {
         if ($total < 0) {
             $paymentRequest->setExtraAmount($total);
         }
     }
     /* 
      * Fazendo a chamada para a API de Pagamentos do PagSeguro. 
      * Se tiver sucesso, retorna o código (url) de requisição para este pagamento.
      */
     $this->data['url'] = '';
     try {
         $credentials = new PagSeguroAccountCredentials($this->config->get('pagseguro_email'), $this->config->get('pagseguro_token'));
         $url = $paymentRequest->register($credentials);
         $this->data['url'] = $url;
     } catch (PagSeguroServiceException $e) {
         $this->log->write('PagSeguro: ' . $e->getOneLineMessage());
     }
     if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/pagseguro.tpl')) {
         $this->template = $this->config->get('config_template') . '/template/payment/pagseguro.tpl';
     } else {
         $this->template = 'default/template/payment/pagseguro.tpl';
     }
     $this->render();
 }
Example #21
0
 /**
  * Use PagSeguroLibrary
  * 
  * @param type $order_id
  * @return type
  */
 public function payment($order)
 {
     global $woocommerce;
     // Instantiate a new payment request
     $paymentRequest = new PagSeguroPaymentRequest();
     // Set cms version
     PagSeguroLibrary::setCMSVersion('woocommerce-v.' . $woocommerce->version);
     // Set plugin version
     PagSeguroLibrary::setModuleVersion('woocommerce-v.' . $this->plugin_version);
     // Set charset
     PagSeguroConfig::setApplicationCharset($this->charset);
     // Sets the currency
     $paymentRequest->setCurrency(PagSeguroCurrencies::getIsoCodeByName("REAL"));
     // Set a reference
     $paymentRequest->setReference($this->invoice_prefix . $order->id);
     //Sets shipping data
     $paymentRequest->setShippingAddress($order->billing_postcode, $order->billing_address_1, '', $order->billing_address_2, '', $order->billing_city, $order->billing_state, $order->billing_country);
     $paymentRequest->setShippingCost($order->order_shipping);
     $paymentRequest->setShippingType(PagSeguroShippingType::getCodeByType('NOT_SPECIFIED'));
     // Sets your customer information.
     $paymentRequest->setSender($order->billing_first_name . ' ' . $order->billing_last_name, $order->billing_email, substr($order->billing_phone, 0, 2), substr($order->billing_phone, 2));
     // Sets the url used by PagSeguro for redirect user after ends checkout process
     if (!empty($this->url_redirect)) {
         $paymentRequest->setRedirectUrl($this->url_redirect);
     } else {
         $paymentRequest->setRedirectUrl($this->get_return_url($order));
     }
     // Sets the url used by PagSeguro for redirect user after ends checkout process
     if (!empty($this->url_notification)) {
         $paymentRequest->setNotificationURL($this->url_notification);
     } else {
         $paymentRequest->setNotificationURL(home_url() . '/index.php?notificationurl=true');
     }
     //Sets Items
     if (sizeof($order->get_items()) > 0) {
         $paymentRequest->setItems($this->setItems($order));
     }
     // Sets the sum of discounts
     $paymentRequest->setExtraAmount(($order->order_discount + $order->cart_discount) * -1 + ($order->order_tax + $order->order_shipping_tax + $order->prices_include_tax));
     try {
         $credentials = new PagSeguroAccountCredentials($this->email, $this->token);
         return $paymentRequest->register($credentials);
     } catch (PagSeguroServiceException $e) {
         $woocommerce->add_error(__('Sorry, unfortunately there was an error during checkout. Please contact the store administrator if the problem persists.', 'wpwcpagseguro'));
         $woocommerce->show_messages();
         wp_die();
     }
 }
Example #22
0
 /**
  *  Generates PagSeguro request data
  */
 private function _generatePagSeguroRequestData()
 {
     $payment_request = new PagSeguroPaymentRequest();
     $payment_request->setCurrency(PagSeguroCurrencies::getIsoCodeByName('Real'));
     /* Currency */
     $payment_request->setExtraAmount($this->_getExtraAmountValues());
     /* Extra amount */
     $payment_request->setItems($this->_generateProductsData());
     /* Products */
     $payment_request->setSender($this->_generateSenderData());
     /* Sender */
     $payment_request->setShipping($this->_generateShippingData());
     /* Shipping */
     if (!Tools::isEmpty(Configuration::get('PAGSEGURO_URL_REDIRECT'))) {
         /* Redirect URL */
         $payment_request->setRedirectURL(Configuration::get('PAGSEGURO_URL_REDIRECT'));
     }
     $this->_payment_request = $payment_request;
 }
 /**
  *  Perform PagSeguro request and return url from PagSeguro
  *  @return string
  */
 private function _performPagSeguroRequest(PagSeguroPaymentRequest $pagSeguroPaymentRequest)
 {
     try {
         // setting PagSeguro configurations
         $this->_setPagSeguroConfiguration();
         // setting PagSeguro plugin version
         $this->_setPagSeguroModuleVersion();
         // setting VirtueMart version
         $this->_setPagSeguroCMSVersion();
         // getting credentials
         $credentials = new PagSeguroAccountCredentials($this->payment_params->pagseguro_email, $this->payment_params->pagseguro_token);
         // return performed PagSeguro request values
         return $pagSeguroPaymentRequest->register($credentials);
     } catch (PagSeguroServiceException $e) {
         die($e->getMessage());
     }
 }
     if ($linha = $query->fetch()) {
         $divida = $linha["valorPagar"];
     } else {
         // Houve algum erro de consulta ao banco ou o usuário não possui dividas no banco
         header('Location: ../visualizar_pagamentos_associado.php?mensagem=Erro ao consultar divida, favor, comunicar a administração', true, "302");
         die;
     }
     if ($valor > $divida || $valor == 0) {
         header('Location: ../visualizar_pagamentos_associado.php?mensagem=favor, entre com um valor válido entre 0 e ' . $divida, true, "302");
         die;
     }
 }
 //se correu tudo bem, o valor a ser pago deve estar setado e pronto para ser redirecionado ao pagSeguro
 // agora enviamos o usuário para a tela de pagamento
 require '../PagSeguroLibrary/PagSeguroLibrary.php';
 $reqPagamento = new PagSeguroPaymentRequest();
 if ($inscricao) {
     $reqPagamento->addItem('0002', 'Inscrição de associação ao curso de Homeopatia', 1, number_format($valor, 2, ".", ""));
 } else {
     $reqPagamento->addItem('0003', 'Anuidade de associação ao curso de Homeopatia', 1, number_format($valor, 2, ".", ""));
 }
 $reqPagamento->setCurrency("BRL");
 $reqPagamento->setSender($associado->getNome(), $associado->getEmail(), mb_substr($associado->getTelefone(), 0, 2), mb_substr($associado->getTelefone(), 2));
 $reqPagamento->setShippingAddress($associado->getCep(), $associado->getRua(), $associado->getNumero(), $associado->getComplemento(), $associado->getBairro(), $associado->getCidade(), $associado->getEstado(), $associado->getPais());
 $reqPagamento->setShippingType(3);
 // a referência desse pagamente será a letra "A" de anuidade,
 // seguida do id de Associado deste associado
 $reqPagamento->setReference("A" . $associado->getIdAssoc());
 $credenciais = PagSeguroConfig::getAccountCredentials();
 $url = $reqPagamento->register($credenciais);
 header('Location: ' . $url, true, "302");
 public function iniciaPagamentoPagSeguro()
 {
     $paymentRequest = new PagSeguroPaymentRequest();
     $paymentRequest->setCurrency("BRL");
     $this->razao = $this->razao . $this->transacaoID;
     //Itens compra | Não posso colocar o dinheiro por partes por conta do cupom
     $paymentRequest->addItem('0001', $this->razao, 1, $this->valor);
     $paymentRequest->setReference($this->transacaoID);
     $nomeUsuario = preg_replace('/\\d/', '', $this->nomeUsuario);
     $nomeUsuario = preg_replace('/[\\n\\t\\r]/', ' ', $nomeUsuario);
     $nomeUsuario = preg_replace('/\\s(?=\\s)/', '', $nomeUsuario);
     $nomeUsuario = trim($nomeUsuario);
     $nomeUsuario = explode(' ', $nomeUsuario);
     if (count($nomeUsuario) == 1) {
         $nomeUsuario[] = ' sem Sobrenome';
     }
     $nomeUsuario = implode(' ', $nomeUsuario);
     // Dados do usuario
     $paymentRequest->setSender($nomeUsuario, trim($this->emailUsuario));
     // Url de retorno após pagamento
     $paymentRequest->setRedirectUrl($this->system->getUrlSite());
     // Url de notificação de modificação de status
     $paymentRequest->addParameter('notificationURL', $this->notificationURLPagSeguro);
     $paymentRequest->addParameter('sistemaID', $this->system->session->getItem('session_cod_empresa'));
     try {
         $credentials = $this->obterCredenciaisPagSeguro();
         $url = $paymentRequest->register($credentials);
         return $url;
     } catch (PagSeguroServiceException $e) {
         $erros = array();
         foreach ($e->getErrors() as $erro) {
             $erros[] = $erro->getMessage();
         }
         echo '<script>alert("' . implode('<br/>', $erros) . '")</script>';
         die;
     }
 }
 public static function compraCreditos($idp, $idpct)
 {
     /**
      * Executa uma operação de compra de créditos
      *
      * @param int $idp ID do parceiro
      * @param int $idpct ID do pacote comprado
      * @param int $tipo transação : 2 = cartão (default) | 3 = boleto | 4 = depósito
      * @param string $obj objeto da operação
      */
     // As ações de compra e bônus possuem status = 0 (espera) e não atualiza o saldo de créditos
     // até que a operação de checkout retorne o valor como pago.
     $hoje = new ActiveRecord\DateTime(date('Y-m-d H:i:s'));
     $saldo = creditos_saldo_parceiro::find_by_parceiro_id('first', $idp);
     $parceiro = parceiro::find_by_id($idp);
     if (!$parceiro) {
         return self::ERRO_USUARIO_INVALIDO;
     }
     $ddd = (int) substr($parceiro->fone, 1, 2);
     $fone = (int) str_replace('-', '', substr($parceiro->fone, 4, 10));
     $options['conditions'] = array('parceiro_id = ? AND vencimento >= ? AND flag_ativo = ?', $idp, $hoje, 1);
     $bonusUnico = creditos_bonus_unico::first($options);
     // Pega os dados de créditos, custo e bonus do pacote
     $pacote = creditos_pacote::find_by_id($idpct);
     if (!$pacote || $pacote->flag_ativo == 0) {
         return self::ERRO_PACOTE_INVALIDO;
     }
     $titulo = $pacote->titulo;
     $creditos = $pacote->quant_creditos;
     $custo = $pacote->custo_pacote_reais;
     $referencia = $idp . '-SC-' . self::contaEventos($idp, self::SC, 1);
     // utilizado para rastrear todos as fases da operação
     $bonus_geral = 0;
     $bonus_unico = 0;
     // avalia bonus geral e único
     if ($pacote->creditos_bonus > 0 && strtotime($pacote->data_limite_bonus) >= strtotime($hoje)) {
         $bonus_geral = $pacote->creditos_bonus;
     }
     $buOptions['conditions'] = array('parceiro_id = ? AND vencimento >= ? AND flag_ativo = ?', $idp, $hoje, 1);
     $bu = creditos_bonus_unico::first($buOptions);
     if ($bu) {
         $bonus_unico = $bu->bonus;
     }
     // inicializa classe do pagseguro, inserindo dados de usuário
     $paymentRequest = new PagSeguroPaymentRequest();
     $paymentRequest->addItem($idpct, $titulo, 1, $custo);
     $paymentRequest->setSender($parceiro->responsavel . ' - ' . $parceiro->nome, $parceiro->email, $ddd, $fone);
     $paymentRequest->setCurrency('BRL');
     $paymentRequest->setReference($referencia);
     //$paymentRequest->addParameter('notificationURL', self::NOTIFICATION_URL);
     $sedexCode = PagSeguroShippingType::getCodeByType('NOT_SPECIFIED');
     $paymentRequest->setShippingType($sedexCode);
     $cidade = cidade::find_by_id($parceiro->cidade_id);
     $estado = estado::find_by_id($parceiro->estado_id);
     $postalCode = str_replace('-', '', $parceiro->cep);
     $postalCode = str_replace('.', '', $postalCode);
     $logradouro = explode(', ', $parceiro->logradouro);
     $paymentRequest->setShippingAddress($postalCode, $logradouro[0], $logradouro[1], $parceiro->complemento, $parceiro->bairro, $cidade->cidade, $estado->uf, 'BRA');
     // inicia o processo de transação enviando as credenciais e
     // solicitando o código da operação
     try {
         $credentials = PagSeguroConfig::getAccountCredentials();
         // getApplicationCredentials()
         $checkoutUrl = $paymentRequest->register($credentials);
         // FORMATO:  https://pagseguro.uol.com.br/v2/checkout/payment.html?code=1C9B0FD3AEAE0FF004A39F98B751B1E5
         $codigo = explode('=', $checkoutUrl);
         // grava os dados da operação antes inicar
         $dadosPagSeguro = array();
         $dadosPagSeguro['parceiro_id'] = $idp;
         $dadosPagSeguro['parceiro_nome'] = $parceiro->responsavel . ' - ' . $parceiro->nome;
         $dadosPagSeguro['parceiro_email'] = $parceiro->email;
         $dadosPagSeguro['parceiro_fone'] = $parceiro->fone;
         $dadosPagSeguro['bonus_geral'] = $bonus_geral;
         $dadosPagSeguro['bonus_unico'] = $bonus_unico;
         $dadosPagSeguro['pacote_id'] = $idpct;
         $dadosPagSeguro['pacote_titulo'] = $titulo;
         $dadosPagSeguro['pacote_creditos'] = $creditos;
         $dadosPagSeguro['flag_pacote_creditado'] = 0;
         $dadosPagSeguro['data_cadastro'] = $hoje;
         $dadosPagSeguro['data_atualizacao'] = $hoje;
         $dadosPagSeguro['codigo_link'] = $codigo[1];
         $dadosPagSeguro['referencia'] = $referencia;
         $dadosPagSeguro['tipo_transacao'] = 1;
         // 1 ==  compra | 11 == assinatura
         $dadosPagSeguro['status_transacao'] = 0;
         // inicia como 0
         $dadosPagSeguro['fases'] = 0;
         // registra todos os status retornados pelo pagseguro. Inicia como 0
         $dadosPagSeguro['valor_reais'] = $custo;
         $pagseguro = operacoes_pagseguro::create($dadosPagSeguro);
         $pagseguro->save();
         $observação = 'Solicitação de compra PagSeguro ' . $referencia . '(R$' . number_format($custo, 2, ',', '.') . ')';
         // registra o crédito adquirido como status EM ESPERA
         self::registraEvento($idp, self::SC, $saldo->saldo, $referencia, $crdt, $custo, 1, $observação);
         // descomentar esta linha na versão final
         // return $codigo[1];
         return self::ERRO_OPERACAO_TESTE_CANCELADA;
     } catch (PagSeguroServiceException $e) {
         // implementar retorno de erro personalizado
         die($e->getMessage());
     }
 }
Example #27
0
 /**
  * Perform PagSeguro Request
  * @param PagSeguroPaymentRequest $paymentRequest
  */
 private function _performPagSeguroRequest(PagSeguroPaymentRequest $paymentRequest)
 {
     $this->_credential = new PagSeguroAccountCredentials($this->config->get('pagseguro_email'), $this->config->get('pagseguro_token'));
     try {
         $this->_urlPagSeguro = $paymentRequest->register($this->_credential);
     } catch (Exception $exc) {
         die($this->language->get('text_info'));
     }
 }
 /**
  * Pagseguro
  *
  * @access public
  * @param int(11) idVenda
  */
 public function pagseguro($idVenda)
 {
     if ($this->session->userdata('logged_in') == true && $this->session->userdata('userData')->idTipoUsuario == 4) {
         $this->data['hasError'] = false;
         $this->data['errorList'] = array();
         $venda = array_shift($this->Vendas_model->getVenda(array('idVenda' => $idVenda)));
         // validações
         if (!is_object($venda)) {
             $this->data['hasError'] = true;
             $this->data['errorList'][] = array('message' => 'Não foi possível localizar sua compra.');
         }
         if (!$this->data['hasError']) {
             $userObj = $this->session->userdata('userData');
             $promocao = $this->Promocoes_model->getPromocaoById($venda->idPromocao);
             // Pega o estado do usuário
             $estadoObj = null;
             if ($userObj->idEstado) {
                 $filter = array('idEstado' => $userObj->idEstado);
                 $estadoObj = array_shift($this->Estados_model->getEstado($filter));
             }
             // Instantiate a new payment request
             $paymentRequest = new PagSeguroPaymentRequest();
             // Sets the currency
             $paymentRequest->setCurrency("BRL");
             // Sets a reference code for this payment request, it is useful to
             // identify this payment in future notifications.
             $paymentRequest->setReference($venda->idVenda);
             // Add an item for this payment request
             $paymentRequest->addItem('0001', substr($promocao->nome, 0, 80), 1, number_format($venda->valorDevido, 2, '.', ''));
             $paymentRequest->setShippingType(3);
             $paymentRequest->setShippingAddress(str_replace('-', '', str_replace('.', '', $userObj->CEP)), $userObj->endereco, $userObj->numero, $userObj->complemento, $userObj->bairro, $userObj->cidade, $estadoObj->sigla ? $estadoObj->sigla : '', 'BRA');
             // Sets your customer information.
             $paymentRequest->setSenderName(substr($userObj->nome, 0, 40));
             $paymentRequest->setSenderEmail($userObj->email);
             $paymentRequest->setSenderPhone($userObj->telefone1);
             $paymentRequest->setRedirectUrl(base_url('ofertas/retornoPagamento'));
             $paymentRequest->setMaxAge(86400 * 3);
             try {
                 $credentials = new PagSeguroAccountCredentials($this->config->item('pagseguroAccount'), $this->config->item('pagseguroToken'));
                 $url = $paymentRequest->register($credentials);
                 $dados = array('meioPagamento' => 2, 'statusPagamento' => 1, 'dataAtualizacao' => date('Y-m-d H:i:s'));
                 $this->Vendas_model->update($dados, $venda->idVenda);
                 redirect($url);
             } catch (PagSeguroServiceException $e) {
                 $this->data['hasError'] = true;
                 $this->data['errorList'][] = array('message' => 'Ocorreu um erro ao comunicar com o Pagseguro.' . $e->getCode() . ' - ' . $e->getMessage());
             }
             var_dump($this->data['errorList']);
         }
     } else {
         redirect(base_url('login'));
     }
 }
 public function requestPayment($items, $client, $reference = null, $shipping = null, $redirect = '/', $currency = 'BRL')
 {
     $requestPayment = new PagSeguroPaymentRequest();
     $requestPayment->setCurrency($currency);
     $itemId = 1;
     foreach ($items as $item) {
         $item['id'] = $this->formatNumber($itemId++);
         $requestPayment->addItem($item);
     }
     $requestPayment->setReference($reference);
     $requestPayment->setSenderName($client['client_name']);
     $requestPayment->setSenderEmail($client['client_email']);
     $requestPayment->setSenderPhone($client['client_ddd'], $client['client_phone']);
     $requestPayment->setShippingType($shipping['frete']);
     $requestPayment->setShippingCost(0);
     $requestPayment->setShippingAddress($shipping['cep'], $shipping['rua'], $shipping['numero'], $shipping['complemento'], $shipping['bairro'], $shipping['cidade'], $shipping['estado'], $shipping['pais']);
     $requestPayment->setRedirectURL($redirect);
     $requestPayment->setMaxAge(86400 * 3);
     try {
         return $requestPayment->register($this->getCredentials());
     } catch (PagSeguroServiceException $e) {
         foreach ($e->getErrors() as $key => $error) {
             echo $error->getCode();
             echo $error->getMessage();
         }
     }
 }
 public function index()
 {
     /////////////////////////////////////////////////////////////////////////////////////////////////////////////
     // REGISTRA NO BANCO ////////////////////////////////////////////////////////////////////////////////////////
     /////////////////////////////////////////////////////////////////////////////////////////////////////////////
     $this->load->model('Product');
     $this->load->model('Kit');
     $this->load->model('Order');
     $this->load->helper('date');
     $total_kits = $this->cart->contents();
     if ($this->Order->getLastId() != NULL) {
         $nr_pedido = str_pad($this->Order->getLastId() + 1, 6, '0', STR_PAD_LEFT);
         // adding leading zeros
     } else {
         $nr_pedido = str_pad(1, 6, '0', STR_PAD_LEFT);
     }
     $datestring = "%Y-%m-%d";
     $time = time();
     $date = mdate($datestring, $time);
     $kit_string = '';
     foreach ($this->cart->contents() as $kit) {
         if ($kit_string == '') {
             $kit_string .= 'Kit ' . $kit['id'];
         } else {
             $kit_string .= ' / Kit ' . $kit['id'];
         }
     }
     $data_pedido = array('nr_pedido_net' => $nr_pedido, 'cd_cliente' => $this->session->userdata('codigo'), 'cd_cond_pagto' => '', 'observacao' => $kit_string, 'cd_status' => '1', 'dt_emissao' => $date, 'vl_pago_juros' => 0.0, 'importado' => 'N');
     $this->Order->addOrder($data_pedido);
     // ROTINA PARA INSERÇAO DOS PRODUTOS NA TABELA pedido_venda_item
     $items = array();
     // array que conterá os items individuais de cada kit e populara a tabela pedido_venda_items
     foreach ($this->cart->contents() as $kit) {
         $kit_qty = $kit['qty'];
         $kit_products = $this->Product->getKit($kit['id']);
         for ($i = 0; $i < count($kit_products); $i++) {
             $codigo_produto = $kit_products[$i]['codigo'];
             $qtd_produto = $kit_products[$i]['qtde'] * $kit_qty;
             $vl_unitario_produto = $kit_products[$i]['valor'];
             $items[$codigo_produto]['nr_pedido_net'] = $nr_pedido;
             $items[$codigo_produto]['cd_produto'] = $codigo_produto;
             if (isset($items[$codigo_produto]['qtd'])) {
                 $items[$codigo_produto]['qtd'] += $qtd_produto;
             } else {
                 $items[$codigo_produto]['qtd'] = $qtd_produto;
             }
             $items[$codigo_produto]['vl_unitario'] = $vl_unitario_produto;
         }
     }
     foreach ($items as $item) {
         $this->Order->addOrderItem($item);
         // var_dump($item);
     }
     /////////////////////////////////////////////////////////////////////////////////////////////////////////////
     // PAGSEGURO ////////////////////////////////////////////////////////////////////////////////////////////////
     /////////////////////////////////////////////////////////////////////////////////////////////////////////////
     $this->load->library('PagSeguroLibrary');
     $data = $this->input->post('formulario');
     $total = $data['total'];
     $nome = $data['nome'];
     $sobrenome = $data['sobrenome'];
     $ddd = $data['ddd'];
     $telefone = $data['telefone'];
     $email = $data['email'];
     $endereco = $data['endereco'];
     $numero = $data['numero'];
     $complemento = $data['complemento'];
     $bairro = $data['bairro'];
     $cidade = $data['cidade'];
     $estado = $data['estado'];
     $cep = $data['cep'];
     //criar um objeto do tipo PagSeguroPaymentRequest:
     $paymentRequest = new PagSeguroPaymentRequest();
     //Agora você deve adicionar os produtos ao objeto criado:
     $i = 0;
     foreach ($this->cart->contents() as $item) {
         $paymentRequest->addItem($nr_pedido, $item['name'], $item['qty'], number_format($item['price'], 2, '.', ','));
         $i++;
     }
     // $paymentRequest->addItem('000001', 'teste', 1, 2.00);
     //Você também pode adicionar produtos e outros parâmetros indexados utilizando o método addIndexedParameter:
     //$paymentRequest->addIndexedParameter('itemId', '0003', 3);
     /*Você também pode informar os dados fornecidos pelo comprador em sua loja, assim, o comprador
     		não precisará informar esses dados novamente no site do PagSeguro:*/
     $paymentRequest->setSender($nome . ' ' . $sobrenome, $email, $ddd, $telefone);
     // Informando o código de referência no objeto PagSeguroPaymentRequest
     $paymentRequest->setReference($nr_pedido);
     //Informe o endereço de envio fornecido pelo comprador, assim, o comprador não precisará informa-lo novamente no site do PagSeguro:
     $paymentRequest->setShippingAddress($cep, $endereco, $numero, $complemento, $bairro, $cidade, $estado, 'BRA');
     //É necessário que você informe a moeda em que o comprador irá realizar o pagamento
     $paymentRequest->setCurrency("BRL");
     //É necessário informar também o tipo de frete da compra, veja mais detalhes na classe PagSeguroShipping
     $paymentRequest->setShippingType(3);
     //Você pode adicionar outros parâmetros ao objeto utilizando o método addParameter
     //$paymentRequest->addParameter('notificationURL', 'http://www.meusite.com.br/notificacao');
     $paymentRequest->setRedirectUrl("http://www.crismetal.com.br/loja_virtual/retorno");
     // Informando as credenciais
     $credentials = PagSeguroConfig::getAccountCredentials();
     // fazendo a requisição a API do PagSeguro pra obter a URL de pagamento
     $url = $paymentRequest->register($credentials);
     redirect($url, 'location');
 }