Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App;
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Support\Facades\DB;
- use App\User;
- use App\Logs;
- use App\Config;
- class Pagseguro extends Model
- {
- private $credentials;
- public function __construct(){
- $this->credentials = $this->getCredentials();
- }
- public function getCredentials(){
- $config = new Config();
- /* */
- $dados = json_decode($config->getPagseguro());
- if($dados->metodo == "sandbox"){
- return json_decode(json_encode(array(
- "type" => "sandbox",
- "token" => "77DBB23D06434213A8E9A57C8D30C2C4",
- "usuario" => "pagseguro@clubedetiroliberdade.com.br",
- "session" => "https://ws.sandbox.pagseguro.uol.com.br/v2/sessions",
- "transaction" => "https://ws.sandbox.pagseguro.uol.com.br/v2/transactions",
- "email" => "c22731539627466576438@sandbox.pagseguro.com.br", // para usar o sandbox como cliente
- "notification" => "https://ws.sandbox.pagseguro.uol.com.br/v3/transactions/notifications/",
- )));
- }elseif($dados->metodo == "production"){
- return json_decode(json_encode(array(
- "type" => "production",
- "usuario" => $dados->usuario, // pagseguro@clubedetiroliberdade.com.br
- "token" => $dados->token,// C56284A69898CACAA4EC1F829C122A41
- "session" => "https://ws.pagseguro.uol.com.br/v2/sessions",
- "transaction" => "https://ws.pagseguro.uol.com.br/v2/transactions",
- "notification" => "https://ws.pagseguro.uol.com.br/v3/transactions/notifications/",
- )));
- }
- }
- public function convertCPF($cpf)
- {
- $ex1 = str_replace(".", "", $cpf);
- $ex2 = str_replace("-", "", $ex1);
- return $ex2;
- }
- public function getAreaCode($cel)
- {
- $ex1 = explode("(", $cel); // (81) 99999-9999
- $ex2 = explode(") ", $ex1[1]);
- return $ex2[0];
- }
- public function getOnlyCelNumber($cel)
- {
- $ex1 = explode("(", $cel);
- $ex2 = explode(") ", $ex1[1]);
- return str_replace("-", "", $ex2[1]);
- }
- public function getOnlyCepNumber($cep)
- {
- $ex1 = str_replace(".", "", $cep);
- $ex2 = str_replace("-", "", $ex1);
- return $ex2;
- }
- public function createSession()
- {
- $acesso = $this->getCredentials();
- $credentials = array(
- "token" => $acesso->token,
- "email" => $acesso->usuario
- );
- $data = http_build_query($credentials);
- $curl = curl_init();
- $headers = array('Content-Type: application/x-www-form-urlencoded; charset=ISO-8859-1'
- );
- //$url = 'https://ws.sandbox.pagseguro.uol.com.br/v2/sessions';
- $url = $acesso->session;
- curl_setopt($curl, CURLOPT_URL, $url);
- curl_setopt($curl, CURLOPT_POST, true);
- curl_setopt( $curl,CURLOPT_HTTPHEADER, $headers );
- curl_setopt( $curl,CURLOPT_RETURNTRANSFER, true );
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
- //curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
- curl_setopt($curl, CURLOPT_HEADER, false);
- $xml = curl_exec($curl);
- $err = curl_error($curl);
- curl_close($curl);
- if ($err) {
- return false;
- } else {
- if($xml == "Unauthorized"):
- return false;
- else:
- $xml= simplexml_load_string($xml);
- return $xml->id;
- endif;
- }
- }
- /*
- Formas de pagamento:
- 1 - crédito
- 2 - boleto
- 3 - débito
- Status do pagamento
- 1 - Aguardando pagamento
- 2 - Em análise
- 3 - Paga
- 4 - Disponível
- 5 - Em disputa
- 6 - Devolvida
- 7 - Cancelada
- */
- public function createPaymentBoleto($valor, $valor_inicial, $user, $senderHash)
- {
- $acesso = $this->getCredentials();
- $info = [
- 'filiado' => auth()->user()->id,
- 'valor' => $valor,
- 'valor_inicial' => $valor_inicial,
- 'forma' => 2,
- 'parcelas' => 1,
- 'token' => hash('md5', "Transaction_".date("YmdHis").auth()->user()->private_key),
- 'transaction_type' => 2, // igual a forma, rever isso
- 'created_at' => date("Y-m-d H:i:s"),
- 'updated_at' => date("Y-m-d H:i:s"),
- 'status' => 1
- ];
- DB::beginTransaction();
- if(DB::table('anuidades')->insert($info)){
- if($acesso->type == "sandbox"){
- $email_sender = $acesso->email;
- }else{
- $email_sender = auth()->user()->email;
- }
- $credentials = array(
- // config
- "token" => $acesso->token,
- "email" => $acesso->usuario,
- "paymentMode" => "default",
- "paymentMethod" => "boleto", /* ver aqui */
- "receiverEmail" => $acesso->usuario,
- "currency" => "BRL",
- "extraAmount" => "0.00",
- // Anuidade em si
- "itemId1" => "0001",
- "itemDescription1" => "Anuidade Clube de Tiro Liberdade",
- "itemAmount1" => number_format($valor, 2, '.', ''),
- "itemQuantity1" => 1,
- // sobre o sistema
- "notificationURL" => "https://clubedetiroliberdade.com.br/pagseguro/notification",
- "reference" => $info["token"], // Gerar um token único
- // Dados Filiado
- "senderName" => auth()->user()->name,
- "senderCPF" => $this->convertCPF(auth()->user()->cpf),
- "senderAreaCode" => $this->getAreaCode(auth()->user()->cel),
- "senderPhone" => $this->getOnlyCelNumber(auth()->user()->cel),
- "senderEmail" => $email_sender,
- "senderHash" => $senderHash,
- "shippingAddressStreet" => auth()->user()->logradouro,
- "shippingAddressNumber" => auth()->user()->num,
- "shippingAddressComplement" => auth()->user()->comp,
- "shippingAddressDistrict" => auth()->user()->bairro,
- "shippingAddressPostalCode" => $this->getOnlyCepNumber(auth()->user()->cep),
- "shippingAddressCity" => auth()->user()->cidade,
- "shippingAddressState" => strtoupper(auth()->user()->uf),
- "shippingAddressCountry" => "ATA",
- "shippingType" => 3,
- "shippingCost" => "0.00",
- );
- $transaction = $this->createTransaction($credentials);
- if($transaction):
- $logs = new Logs;
- if($logs->registerLog("Realizou um pagamento")){
- DB::commit();
- return $transaction;
- }else{
- DB::rollBack();
- return redirect()
- ->back()
- ->with('error', 'Falha ao realizar pagamento.');
- }
- else:
- DB::rollBack();
- return redirect()
- ->back()
- ->with('error', 'Falha ao realizar pagamento.');
- endif;
- }else{
- DB::rollBack();
- return redirect()
- ->back()
- ->with('error', 'Falha ao realizar pagamento.');
- }
- }
- public function createPaymentCreditCard($dados)
- {
- $acesso = $this->getCredentials();
- $info = [
- 'filiado' => auth()->user()->id,
- 'valor' => $dados["valor"],
- 'valor_inicial' => $dados["valor_inicial"],
- 'forma' => 1,
- 'parcelas' => $dados["parcelas"],
- 'token' => hash('md5', "Transaction_".date("YmdHis").auth()->user()->private_key),
- 'transaction_type' => 2, // igual a forma, rever isso
- 'created_at' => date("Y-m-d H:i:s"),
- 'updated_at' => date("Y-m-d H:i:s"),
- 'status' => 1
- ];
- DB::beginTransaction();
- if(DB::table('anuidades')->insert($info)){
- if($dados["valor"] > 500){
- $maxp = 5;
- }else{
- $maxp = 3;
- }
- if($acesso->type == "sandbox"){
- $email_sender = $acesso->email;
- }else{
- $email_sender = auth()->user()->email;
- }
- $credentials = array(
- "token" => $acesso->token,
- "email" => $acesso->usuario,
- "paymentMode" => "default",
- "paymentMethod" => "creditCard", /* ver aqui */
- "receiverEmail" => $acesso->usuario,
- "currency" => "BRL",
- "extraAmount" => "0.00",
- // Anuidade em si
- "itemId1" => "0001",
- "itemDescription1" => "Anuidade Clube de Tiro Liberdade",
- "itemAmount1" => number_format($dados["valor"], 2, '.', ''),
- "itemQuantity1" => 1,
- "installmentQuantity" => $dados["parcelas"],
- "installmentValue" => $dados["parcelavalor"],
- "noInterestInstallmentQuantity" => $maxp,
- // sobre o sistema
- "notificationURL" => "https://clubedetiroliberdade.com.br/pagseguro/notification",
- "reference" => $info["token"], // Gerar um token único
- // Dados Filiado
- "senderName" => auth()->user()->name,
- "senderCPF" => $this->convertCPF(auth()->user()->cpf),
- "senderAreaCode" => $this->getAreaCode(auth()->user()->cel),
- "senderPhone" => $this->getOnlyCelNumber(auth()->user()->cel),
- "senderEmail" => $email_sender,
- "senderHash" => $dados["senderHash"],
- "creditCardToken" => $dados["cardToken"],
- "creditCardHolderName" => $dados["titular"],
- "creditCardHolderCPF" => $dados["tcpf"],
- "creditCardHolderBirthDate" => $dados["tnasc"],
- "creditCardHolderAreaCode" => $this->getAreaCode(auth()->user()->cel),
- "creditCardHolderPhone" => $this->getOnlyCelNumber(auth()->user()->cel),
- "billingAddressStreet" => auth()->user()->logradouro,
- "billingAddressNumber" => auth()->user()->num,
- "billingAddressComplement" => auth()->user()->comp,
- "billingAddressDistrict" => auth()->user()->bairro,
- "billingAddressPostalCode" => $this->getOnlyCepNumber(auth()->user()->cep),
- "billingAddressCity" => auth()->user()->cidade,
- "billingAddressState" => strtoupper(auth()->user()->uf),
- "billingAddressCountry" => "ATA",
- "shippingAddressStreet" => auth()->user()->logradouro,
- "shippingAddressNumber" => auth()->user()->num,
- "shippingAddressComplement" => auth()->user()->comp,
- "shippingAddressDistrict" => auth()->user()->bairro,
- "shippingAddressPostalCode" => $this->getOnlyCepNumber(auth()->user()->cep),
- "shippingAddressCity" => auth()->user()->cidade,
- "shippingAddressState" => strtoupper(auth()->user()->uf),
- "shippingAddressCountry" => "ATA",
- "shippingType" => 3,
- "shippingCost" => "0.00",
- );
- $transaction = $this->createTransaction($credentials);
- if($transaction):
- $logs = new Logs;
- if($logs->registerLog("Realizou um pagamento")){
- DB::commit();
- return $transaction;
- }else{
- DB::rollBack();
- return redirect()
- ->back()
- ->with('error', 'Falha ao realizar pagamento.');
- }
- else:
- DB::rollBack();
- return redirect()
- ->back()
- ->with('error', 'Falha ao criar Fatura.');
- endif;
- }else{
- DB::rollBack();
- return false;
- }
- }
- public function createPaymentDebit($dados)
- {
- $acesso = $this->getCredentials();
- $info = [
- 'filiado' => auth()->user()->id,
- 'valor' => $dados["valor"],
- 'valor_inicial' => $dados["valor_inicial"],
- 'forma' => 3,
- 'parcelas' => 1,
- 'token' => hash('md5', "Transaction_".date("YmdHis").auth()->user()->private_key),
- 'transaction_type' => 3, // igual a forma, rever isso
- 'created_at' => date("Y-m-d H:i:s"),
- 'updated_at' => date("Y-m-d H:i:s"),
- 'status' => 1
- ];
- if(DB::table('anuidades')->insert($info)){
- if($acesso->type == "sandbox"){
- $email_sender = $acesso->email;
- }else{
- $email_sender = auth()->user()->email;
- }
- $credentials = array(
- "token" => $acesso->token,
- "email" => $acesso->usuario,
- "paymentMode" => "default",
- "paymentMethod" => "eft", /* ver aqui */
- "bankName" => $dados["bankName"],// só no débito
- "receiverEmail" => $acesso->usuario,
- "currency" => "BRL",
- "extraAmount" => "0.00",
- // Anuidade em si
- "itemId1" => "0001",
- "itemDescription1" => "Anuidade Clube de Tiro Liberdade",
- "itemAmount1" => number_format($dados["valor"], 2, '.', ''),
- "itemQuantity1" => 1,
- "notificationURL" => "https://clubedetiroliberdade.com.br/pagseguro/notification",
- "reference" => $info["token"], // Gerar um token único
- // Dados Filiado
- "senderName" => auth()->user()->name,
- "senderCPF" => $this->convertCPF(auth()->user()->cpf),
- "senderAreaCode" => $this->getAreaCode(auth()->user()->cel),
- "senderPhone" => $this->getOnlyCelNumber(auth()->user()->cel),
- "senderEmail" => $email_sender,
- "shippingAddressStreet" => auth()->user()->logradouro,
- "shippingAddressNumber" => auth()->user()->num,
- "shippingAddressComplement" => auth()->user()->comp,
- "shippingAddressDistrict" => auth()->user()->bairro,
- "shippingAddressPostalCode" => $this->getOnlyCepNumber(auth()->user()->cep),
- "shippingAddressCity" => auth()->user()->cidade,
- "shippingAddressState" => strtoupper(auth()->user()->uf),
- "shippingAddressCountry" => "ATA",
- "shippingType" => 3,
- "shippingCost" => "0.00",
- );
- $transaction = $this->createTransaction($credentials);
- if($transaction):
- $logs = new Logs;
- if($logs->registerLog("Realizou um pagamento")){
- DB::commit();
- return $transaction;
- }else{
- DB::rollBack();
- return redirect()
- ->back()
- ->with('error', 'Falha ao realizar pagamento.');
- }
- else:
- DB::rollBack();
- return redirect()
- ->back()
- ->with('error', 'Falha ao criar Fatura.');
- endif;
- }else{
- DB::rollBack();
- return false;
- }
- }
- public function createAnuidade($array)
- {
- }
- public function createTransaction($dados)
- {
- $acesso = $this->getCredentials();
- $data = http_build_query($dados);
- $curl = curl_init();
- $headers = array('Content-Type: application/x-www-form-urlencoded; charset=ISO-8859-1');
- //$url = 'https://ws.sandbox.pagseguro.uol.com.br/v2/transactions';
- $url = $acesso->transaction;
- curl_setopt($curl, CURLOPT_URL, $url);
- curl_setopt($curl, CURLOPT_POST, true);
- curl_setopt( $curl,CURLOPT_HTTPHEADER, $headers );
- curl_setopt( $curl,CURLOPT_RETURNTRANSFER, true );
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
- //curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
- curl_setopt($curl, CURLOPT_HEADER, false);
- $xml = curl_exec($curl);
- $err = curl_error($curl);
- curl_close($curl);
- if ($err) {
- return false;
- } else {
- if($xml == "Unauthorized"):
- return "Unauthorized";
- else:
- $xml= simplexml_load_string($xml);
- return $xml;
- endif;
- }
- }
- public function processNotification($notificationCode = null)
- {
- header("access-control-allow-origin: https://sandbox.pagseguro.uol.com.br");
- $acesso = $this->getCredentials();
- /*if($acesso->type == "sandbox"){
- header("access-control-allow-origin: https://sandbox.pagseguro.uol.com.br");
- }else{
- header("access-control-allow-origin: https://pagseguro.uol.com.br");
- }*/
- if($notificationCode == null){
- return false; // c0VgKQpcc_s
- }else{
- $credentials = array(
- "notificationType" => "transaction",
- "token" => $acesso->token,
- "email" => $acesso->usuario,
- );
- // token=77DBB23D06434213A8E9A57C8D30C2C4&email=pagseguro%40clubedetiroliberdade.com.br¬ificationType=transaction
- $data = http_build_query($credentials);
- $headers = array('Content-Type: application/x-www-form-urlencoded; charset=ISO-8859-1');
- $url = $acesso->notification.$notificationCode.'?'.$data;
- $curl = curl_init();
- curl_setopt( $curl , CURLOPT_FOLLOWLOCATION , true );
- curl_setopt( $curl , CURLOPT_RETURNTRANSFER , true );
- curl_setopt( $curl , CURLOPT_HTTPHEADER , $headers );
- curl_setopt( $curl , CURLOPT_URL, $url );
- $xml = curl_exec($curl);
- $err = curl_error($curl);
- curl_close($curl);
- if ($err) {
- return $err;
- } else {
- if($xml == "Unauthorized"):
- throw new Exception("Não autorizado", 1);
- else:
- header('Content-Type: application/json');
- return simplexml_load_string($xml);
- endif;
- }
- }
- }
- public function changeStatus($reference, $status)
- {
- $db = DB::table('anuidades')->where('token', $reference);
- if(count($db->get()) > 0){
- if(DB::table('anuidades')
- ->where('token', $reference)
- ->update([
- "updated_at" => date("Y-m-d H:i:s"),
- "status" => intval($status)
- ]) ) {
- return true;
- }else{
- return false;
- }
- }else{
- echo "Não existe";
- }
- }
- public function consultar($reference = null)
- {
- if($reference != null):
- $acesso = $this->getCredentials();
- $credentials = array(
- "email" => $acesso->usuario,
- "token" => $acesso->token,
- "reference" => $reference
- );
- $data = http_build_query($credentials);
- $url = $acesso->transaction."?".$data;
- $headers = array('Content-Type: application/x-www-form-urlencoded; charset=ISO-8859-1');
- $curl = curl_init();
- curl_setopt( $curl , CURLOPT_FOLLOWLOCATION , true );
- curl_setopt( $curl , CURLOPT_RETURNTRANSFER , true );
- curl_setopt( $curl , CURLOPT_HTTPHEADER , $headers );
- curl_setopt( $curl , CURLOPT_URL, $url );
- $xml = curl_exec($curl);
- $err = curl_error($curl);
- curl_close($curl);
- if ($err) {
- return $err;
- } else {
- if($xml == "Unauthorized"):
- throw new Exception("Não autorizado", 1);
- else:
- header('Content-Type: application/json');
- return simplexml_load_string($xml);
- endif;
- }
- endif;
- }
- public function pegaLinkBoleto($reference = null)
- {
- if($reference != null):
- $consultar = $this->consultar($reference);
- if($consultar){
- if($consultar->transactions->transaction->paymentMethod->type == 2){
- $acesso = $this->getCredentials();
- $credentials = array(
- "email" => $acesso->usuario,
- "token" => $acesso->token,
- );
- $data = http_build_query($credentials);
- $url = $acesso->transaction."/".$consultar->transactions->transaction->code."?".$data;
- $headers = array('Content-Type: application/x-www-form-urlencoded; charset=ISO-8859-1');
- $curl = curl_init();
- curl_setopt( $curl , CURLOPT_FOLLOWLOCATION , true );
- curl_setopt( $curl , CURLOPT_RETURNTRANSFER , true );
- curl_setopt( $curl , CURLOPT_HTTPHEADER , $headers );
- curl_setopt( $curl , CURLOPT_URL, $url );
- $xml = curl_exec($curl);
- $err = curl_error($curl);
- curl_close($curl);
- if ($err) {
- return $err;
- } else {
- if($xml == "Unauthorized"):
- throw new Exception("Não autorizado", 1);
- else:
- header('Content-Type: application/json');
- return simplexml_load_string($xml);
- endif;
- }
- return $consultar->transactions->transaction->code[0];
- }
- }
- endif;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement