public static function main() { $amount = 30.0; //Required $cardBrand = "visa"; //Optional $maxInstallmentNoInterest = 2; //Optional 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"); */ $credentials = PagSeguroConfig::getAccountCredentials(); // Application authentication //$credentials = PagSeguroConfig::getApplicationCredentials(); //$credentials->setAuthorizationCode("E231B2C9BCC8474DA2E260B6C8CF60D3"); $installments = PagSeguroInstallmentService::getInstallments($credentials, $amount, $cardBrand, $maxInstallmentNoInterest); self::printInstallment($installments); } catch (Exception $e) { die($e->getMessage()); } catch (PagSeguroServiceException $e) { die($e->getMessage()); } }
public static function main() { $reference = "REF123"; $initialDate = '2015-09-03T00:00'; $finalDate = '2015-09-09T11:13'; $pageNumber = 1; $maxPageResults = 20; // $reference = "REF123"; // // $initialDate = '2014-12-03T00:00'; // $finalDate = '2014-12-08T00:00'; // $pageNumber = 1; // $maxPageResults = 20; try { /* * #### Credentials ##### * Substitute the parameters below with your credentials * You can also get your credentials from a config file. See an example: * $credentials = PagSeguroConfig::getAccountCredentials(); */ // seller authentication $credentials = new PagSeguroAccountCredentials("*****@*****.**", "E231B2C9BCC8474DA2E260B6C8CF60D3"); $credentials = PagSeguroConfig::getAccountCredentials(); // application authentication //$credentials = PagSeguroConfig::getApplicationCredentials(); //$credentials->setAuthorizationCode("E231B2C9BCC8474DA2E260B6C8CF60D3"); $result = PagSeguroTransactionSearchService::searchByReference($credentials, $reference, $initialDate, $finalDate, $pageNumber, $maxPageResults); self::printResult($result, $initialDate, $finalDate); } catch (PagSeguroServiceException $e) { die($e->getMessage()); } }
private static function transactionNotification($notificationCode) { $credentials = PagSeguroConfig::getAccountCredentials(); try { return PagSeguroNotificationService::checkTransaction($credentials, $notificationCode); } catch (PagSeguroServiceException $e) { die($e->getMessage()); } }
private static function preApprovalNotification($preApprovalCode) { $credentials = PagSeguroConfig::getAccountCredentials(); try { $preApproval = PagSeguroNotificationService::checkPreApproval($credentials, $preApprovalCode); // Do something with $preApproval } catch (PagSeguroServiceException $e) { die($e->getMessage()); } }
public static function main() { // Instantiate a new payment request $directPaymentRequest = new PagSeguroDirectPaymentRequest(); // Set the Payment Mode for this payment request $directPaymentRequest->setPaymentMode('DEFAULT'); // Set the Payment Method for this payment request $directPaymentRequest->setPaymentMethod('CREDIT_CARD'); /** * @todo Change the receiver Email */ $directPaymentRequest->setReceiverEmail('*****@*****.**'); // Set the currency $directPaymentRequest->setCurrency("BRL"); // Add an item for this payment request // Add an item for this payment request $directPaymentRequest->addItem('0001', 'Descricao do item a ser vendido', 2, 10.0); // Add an item for this payment request $directPaymentRequest->addItem('0002', 'Descricao do item a ser vendido', 2, 5.0); // Set a reference code for this payment request. It is useful to identify this payment // in future notifications. $directPaymentRequest->setReference("REF123"); // Set your customer information. // If you using SANDBOX you must use an email @sandbox.pagseguro.com.br $directPaymentRequest->setSender('João Comprador', '*****@*****.**'); $directPaymentRequest->addParameter('notificationURL', 'http://www.lojamodelo.com.br'); $token = "5b97542cd1524b67a9e89b3d90c1f262"; $installment = new PagSeguroInstallment(array("quantity" => 1, "value" => "30.00")); $cardCheckout = new PagSeguroCreditCardCheckout(array('token' => $token, 'installment' => $installment)); //Set credit card for payment $directPaymentRequest->setCreditCard($cardCheckout); try { /** * #### Credentials ##### * Replace the parameters below with your credentials * You can also get your credentials like this: * $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. $return = $directPaymentRequest->register($credentials); self::printTransactionReturn($return); } catch (PagSeguroServiceException $e) { die($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}"); }
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 static function searchByInterval() { // Substitute the code below $days = 20; try { /** * @todo * #### 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 = PagSeguroConfig::getAccountCredentials(); $result = PagSeguroPreApprovalSearchService::searchByInterval($credentials, $days); self::printResult($result); } catch (PagSeguroServiceException $e) { die($e->getMessage()); } }
public static function searchByCode() { // Substitute the code below with a valid pre-approval code for your account $preApprovalCode = "0FEBE545C6C657A77402DF878C539E56"; try { /** * @todo * #### 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 = PagSeguroConfig::getAccountCredentials(); $result = PagSeguroPreApprovalSearchService::searchByCode($credentials, $preApprovalCode); self::printResult($result); } catch (PagSeguroServiceException $e) { die($e->getMessage()); } }
public static function searchByNotification() { // Substitute the code below with a valid code notification for your account $notificationCode = "29B0BEC9D653D653435EE42F3FAEF4461091"; try { /** * @todo * #### 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 = PagSeguroConfig::getAccountCredentials(); $result = PagSeguroPreApprovalSearchService::findByNotification($credentials, $notificationCode); self::printResult($result); } catch (PagSeguroServiceException $e) { die($e->getMessage()); } }
public static function main() { $transaction_code = 'FC138A0E-C734-44A8-A9B7-6A79E1E33292'; try { /* * #### Credentials ##### * Replace the parameters below with your credentials * You can also get your credentials from a config file. See an example: * $credentials = PagSeguroConfig::getAccountCredentials(); */ // seller authentication $credentials = new PagSeguroAccountCredentials("*****@*****.**", "E231B2C9BCC8474DA2E260B6C8CF60D3"); $credentials = PagSeguroConfig::getAccountCredentials(); // application authentication //$credentials = PagSeguroConfig::getApplicationCredentials(); //$credentials->setAuthorizationCode("E231B2C9BCC8474DA2E260B6C8CF60D3"); $transaction = PagSeguroTransactionSearchService::searchByCode($credentials, $transaction_code); self::printTransaction($transaction); } catch (PagSeguroServiceException $e) { die($e->getMessage()); } }
public static function searchByDate() { // Substitute the information below $page = 1; $maxPageResults = 1000; $initialDate = "2015-03-10T00:00:00"; $finalDate = "2015-04-06T00:00:00"; try { /** * @todo * #### 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 = PagSeguroConfig::getAccountCredentials(); $result = PagSeguroPreApprovalSearchService::searchByDate($credentials, $page, $maxPageResults, $initialDate, $finalDate); self::printResult($result, $initialDate, $finalDate); } catch (PagSeguroServiceException $e) { die($e->getMessage()); } }
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 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); // Add discount per payment method $paymentRequest->addPaymentMethodConfig('CREDIT_CARD', 1.0, 'DISCOUNT_PERCENT'); $paymentRequest->addPaymentMethodConfig('EFT', 2.9, 'DISCOUNT_PERCENT'); $paymentRequest->addPaymentMethodConfig('BOLETO', 10.0, '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); self::printPaymentUrl($url); } catch (PagSeguroServiceException $e) { die($e->getMessage()); } }
public function index() { $this->load->model('Order'); $this->load->library('PagSeguroLibrary'); $credentials = PagSeguroConfig::getAccountCredentials(); if ($this->input->get('transaction_id')) { $id = $this->input->get('transaction_id'); $transaction = PagSeguroTransactionSearchService::searchByCode($credentials, $id); $taxas_cobradas = $transaction->getFeeAmount(); $vl_liquido_transacao = $transaction->getNetAmount(); $vl_bruto_transacao = $transaction->getGrossAmount(); $nr_parcelas = $transaction->getInstallmentCount(); $nr_pedido_net = $transaction->getReference(); $ultimo_evento = $transaction->getLastEventDate(); $status = $transaction->getStatus()->getValue(); $paymentMethod = $transaction->getPaymentMethod(); $gross_amount = $transaction->getGrossAmount(); $code = $paymentMethod->getCode()->getValue(); $message = ''; $payment = ''; $status_crismetal = ''; switch ($status) { case 1: // crismetal : 1 - pendente $message = "Aguardando pagamento."; $status_crismetal = '1'; break; case 2: // crismetal : 1 - pendente $message = "Em análise."; $status_crismetal = '1'; break; case 3: // crismetal : 2 - aprovado $message = "Pagamento aprovado."; $status_crismetal = '2'; break; case 4: // crismetal : 2 - aprovado $message = "Disponível (Paga)."; $status_crismetal = '2'; break; case 5: // crismetal : 9 - em disputa $message = "Em disputa."; $status_crismetal = '9'; break; case 6: // crismetal : 6 - devolvida $message = "Devolvida."; $status_crismetal = '6'; break; case 7: // crismetal : 7 - cancelada $message = "Cancelada."; $status_crismetal = '7'; break; } switch ($code) { case 101: $payment = "Cartão de crédito Visa."; break; case 102: $payment = "Cartão de crédito MasterCard."; break; case 103: $payment = "Cartão de crédito American Express."; break; case 104: $payment = "Cartão de crédito Diners."; break; case 105: $payment = "Cartão de crédito Hipercard."; break; case 106: $payment = "Cartão de crédito Aura."; break; case 107: $payment = "Cartão de crédito Elo."; break; case 108: $payment = "Cartão de crédito PLENOCard."; break; case 109: $payment = "Cartão de crédito PersonalCard."; break; case 110: $payment = "Cartão de crédito JCB."; break; case 111: $payment = "Cartão de crédito Discover."; break; case 112: $payment = "Cartão de crédito BrasilCard."; break; case 113: $payment = "Cartão de crédito FORTBRASIL."; break; case 114: $payment = "Cartão de crédito CARDBAN."; break; case 115: $payment = "Cartão de crédito VALECARD."; break; case 116: $payment = "Cartão de crédito Cabal."; break; case 117: $payment = "Cartão de crédito Mais!."; break; case 118: $payment = "Cartão de crédito Avista."; break; case 119: $payment = "Cartão de crédito GRANDCARD."; break; case 201: $payment = "Boleto Bradesco."; $vl_bruto_transacao += 1; break; case 202: $payment = "Boleto Santander."; $vl_bruto_transacao += 1; break; case 301: $payment = "Débito online Bradesco."; break; case 302: $payment = "Débito online Itaú."; break; case 303: $payment = "Débito online Unibanco."; break; case 304: $payment = "Débito online Banco do Brasil."; break; case 305: $payment = "Débito online Banco Real."; break; case 306: $payment = "Débito online Banrisul."; break; case 401: $payment = "Saldo PagSeguro."; break; case 501: $payment = "Oi Paggo."; break; case 701: $payment = "Depósito em conta - Banco do Brasil."; break; } // rotina para atualizar tabela pedido_venda no banco $data_db = array('tipo_pagto' => $payment, 'cond_pagto' => $nr_parcelas, 'cd_status' => $status_crismetal, 'desc_status' => $message, 'vl_liquido' => $vl_liquido_transacao, 'vl_pago_juros' => $vl_bruto_transacao, 'vl_taxas_cobradas' => $taxas_cobradas); $this->Order->updateOrder($nr_pedido_net, $data_db); // carrega view com os dados $data = array('id' => $id, 'message' => $message, 'payment' => $payment, 'amount' => $gross_amount); $this->load->view('open_header'); $this->load->view('v_retorno', $data); $this->load->view('i_footer'); $this->cart->destroy(); } else { redirect('default_controller', 'location'); } }
session_start(); // se receber uma mensagem por POST, identifica se é uma notificação do pagseguro, // se for, redireciona para seu devido lugar error_reporting(-1); ini_set('display_errors', 'On'); ini_set("log_errors", 1); ini_set("error_log", "logs/erro.log"); // recebemos uma notificação do PagSeguro // importa a biblioteca do PagSeguro require '../PagSeguroLibrary/PagSeguroLibrary.php'; /* Tipo de notificação recebida */ $tipoNotificacao = $_POST['notificationType']; /* Código da notificação recebida */ $codigoNotificacao = $_POST['notificationCode']; $credenciais = PagSeguroConfig::getAccountCredentials(); if ($tipoNotificacao === 'transaction') { $transacao = PagSeguroNotificationService::checkTransaction($credenciais, $codigoNotificacao); $statusPag = $transacao->getStatus(); //se existe uma transacao valida, redireciona if ($statusPag->getValue() == 3) { $referencia = $transacao->getReference(); $codigoTipo = mb_substr($referencia, 0, 1); // se a referencia possuir um dos códigos do sistema novo, envia ao sistema novo if ($codigoTipo === "M" || $codigoTipo == "A") { //header("Location:./notificacoes_pagseguro.php",true,307); ?> <form action='./notificacao_pagseguro.php' method='post' name='frm'> <?php
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()); } }
public function notification() { $this->load->library('email'); $this->email->mailtype = 'html'; $code = $this->input->post('notificationCode'); $type = $this->input->post('notificationType'); $support_subject = ''; $support_mesage = ''; try { $credentials = PagSeguroConfig::getAccountCredentials(); $response = PagSeguroNotificationService::checkTransaction($credentials, $code); $status = $response->getStatus()->getValue(); $billId = $response->getReference(); $items = $response->getItems(); if ($status == 3 || $status == 4) { $this->db->where(['id' => $billId]); $this->db->update('tb_billing_accounts', ['dt_payment' => date('Y-m-d H:i:s')]); $message = '<h3>Seu pagamento foi aceito</h3>'; $message = '<p>A compra dos seguintes items foi bem sucedida, boa viagem.<;p><ul>'; foreach ($items as $k => $item) { $message .= "<li>" . $item->getDescription() . ' - ' . $item->getAmount() . "</li>"; } $message .= '</ul>'; $clientMail = $response->getSender()->getEmail(); $this->email->from('*****@*****.**', 'Notificações Financeiras - Origami'); $this->email->to($clientMail); $this->email->subject('Confirmação de pagamento - Caravana Origami'); $this->email->message($message); $this->email->send(); } $support_subject = 'Notificação ' . $response->getReference() . ' - ' . $response->getStatus()->getTypeFromValue(); $support_message = '<h3>Notificação de Transação</h3><p>A seguinte transação foi atualizada</p>'; $support_message .= '<ul><li>Referência: ' . $response->getReference() . '</li>'; $support_message .= '<li>Status: ' . $response->getStatus()->getValue() . ' - ' . $response->getStatus()->getTypeFromValue() . '</li>'; $support_message .= '<li>Cliente: ' . $response->getSender()->getName() . ' - ' . $response->getSender()->getEmail() . '</li>'; foreach ($items as $k => $item) { $support_message .= "<li>" . $item->getDescription() . ' - ' . $item->getAmount() . "</li>"; } $support_message .= '</ul>'; } catch (PagSeguroServiceException $e) { $support_subject = "Falha no acompanhamento de uma cobrança"; $support_message = $e->getMessage(); } $this->email->from('*****@*****.**', 'Notificações Financeiras - Origami'); $this->email->to('*****@*****.**'); $this->email->subject($support_subject); $this->email->message($support_message); $this->email->send(); }
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()); } }
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'); }