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; }
private function _generatePagSeguroRequestData($order, $notify_url, $return_url) { $paymentRequest = new PagSeguroPaymentRequest(); $paymentRequest->setCurrency(PagSeguroCurrencies::getIsoCodeByName('REAL')); // currency $paymentRequest->setReference($order->order_id); // reference $paymentRequest->setRedirectURL($return_url); // redirect url $paymentRequest->setNotificationURL($notify_url); // notification url $paymentRequest->setItems($this->_generateProductsData($order)); // products $paymentRequest->setExtraAmount($this->_getExtraAmountValues($order)); // extra values $paymentRequest->setSender($this->_generateSenderData($order)); // sender $paymentRequest->setShipping($this->_generateShippingData($order)); // shipping return $paymentRequest; }
/** * Generate PagSeguro Payment Request * @return \PagSeguroPaymentRequest */ private function _generatePagSeguroPaymentRequestObject() { $paymentRequest = new PagSeguroPaymentRequest(); $paymentRequest->setCurrency(PagSeguroCurrencies::getIsoCodeByName("REAL")); $paymentRequest->setExtraAmount($this->_generateExtraAmount()); $paymentRequest->setRedirectURL($this->_getPagSeguroRedirectUrl()); $paymentRequest->setNotificationURL($this->_getPagSeguroNotificationURL()); $paymentRequest->setItems($this->_generatePagSeguroProductsData()); $paymentRequest->setSender($this->_generatepagSeguroSenderDataObject()); $paymentRequest->setShipping($this->_generatePagSeguroShippingDataObject()); return $paymentRequest; }
/** * 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; }
/** * 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(); } }
/** * Generates PagSeguro request data * @param VirtueMartCart $cart * @param array $order * @param TablePaymentmethods $method * @return PagSeguroPaymentRequest */ private function _generatePagSeguroRequestData(VirtueMartCart $cart, array $order, TablePaymentmethods $method) { $paymentRequest = new PagSeguroPaymentRequest(); $paymentRequest->setCurrency(PagSeguroCurrencies::getIsoCodeByName('REAL')); // currency $paymentRequest->setReference($order['details']['BT']->virtuemart_order_id); // reference $paymentRequest->setRedirectURL($this->_getRedirectUrl($method->pagseguro_url_redirect)); // redirect url $paymentRequest->setNotificationURL($this->_getNotificationUrl($method->pagseguro_url_notification)); // notification url $paymentRequest->setItems($this->_generateProductsData($cart)); // products $paymentRequest->setExtraAmount($this->_getExtraAmountValues($cart)); // extra values $sender = isset($order['details']['ST']) && count($order['details']['ST'] > 0) ? $order['details']['ST'] : $order['details']['BT']; $paymentRequest->setSender($this->_generateSenderData($sender)); // sender $paymentRequest->setShipping($this->_generateShippingData($sender, $cart->pricesUnformatted['salesPriceShipment'])); // shipping return $paymentRequest; }
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(); }
$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 { $errorMessage = 'Ocorreu um erro, reporte imediatamente a administração!'; } } }