Advertisement
Guest User

Untitled

a guest
May 25th, 2017
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 12.26 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Módulo Gerencinet Cartão para WHMCS
  4.  * @author      Mauricio Gofas | gofas.net
  5.  * @see         https://gofas.net/?p=8423
  6.  * @copyright   2017 https://gofas.net
  7.  * @license     https://www.gnu.org/licenses/gpl-3.0.pt-br.html
  8.  * @support     https://gofas.net/?p=8343
  9.  * @version     1.0.1
  10.  */
  11.  
  12. // Reporta todos os erros e avisos do php
  13. error_reporting(E_ERROR | E_WARNING | E_PARSE);
  14.  
  15. // Require libraries needed for gateway module functions.
  16. require_once __DIR__ . '/../../../init.php';
  17. require_once __DIR__ . '/../../../includes/gatewayfunctions.php';
  18. require_once __DIR__ . '/../../../includes/invoicefunctions.php';
  19.  
  20. // Require GN PHP SDK
  21. require __DIR__ . '/sdk/vendor/autoload.php';
  22. use Illuminate\Database\Capsule\Manager as Capsule;
  23. use Gerencianet\Exception\GerencianetException;
  24. use Gerencianet\Gerencianet;
  25.  
  26. // Puxa parâmetros de configuração do gateway
  27. $params = getGatewayVariables('gofasgerencianetcartao');
  28.     // Debug
  29.     //echo '<pre>';print_r($params);echo '</pre>';
  30.    
  31. // Morre se o módulo está inativo.
  32. if (!$params['type']) {
  33.     die("Module Not Activated");
  34. }
  35.  
  36. // Recebe o GN token
  37. $token = $_POST['notification'];
  38. //$token    = '497fd2cf-7e52-48f0-bbfd-dc2cfb55cfb0'; // assinatura
  39. //$token        = '38c25708-8834-447f-9779-a3e251d20817'; // pagamento uma vez
  40.  
  41. if ($token) {
  42.  
  43.     if( $params['sandboxmode'] ){
  44.         $sandbox = true;
  45.         $client_id = $params['clientidsandbox'];
  46.         $client_secret = $params['clientsecretsandbox'];
  47.  
  48.     }
  49.     elseif( !$params['testmode'] ){
  50.         $sandbox = false;
  51.         $client_id = $params['clientid'];
  52.         $client_secret = $params['clientsecret'];
  53.     }
  54.     if($params['admin']) {
  55.         $whmcsAdmin         = $params['admin'];
  56.     }
  57.     elseif(!$params['admin']){
  58.         $whmcsAdmin         = 1;
  59.     }
  60.    
  61.     $fee        = '0.00'; //$params['fee'];
  62.  
  63.     // Verifica do que se trata a notificação
  64.     $options = [
  65.         'client_id' => $client_id,
  66.         'client_secret' => $client_secret,
  67.         'sandbox' => $sandbox,
  68.         'debug' => true,
  69.     ];
  70.  
  71.     $params = [
  72.         'token' => $token
  73.     ];
  74.  
  75.     $systemUrl          = $params['systemurl'];
  76.    
  77.     try {
  78.         $api = new Gerencianet($options);
  79.         $notification = $api->getNotification($params, []);
  80.  
  81.         // Prepara dados retornados
  82.         $notificationDataEnd    = end($notification['data']); // @ em caso de bug
  83.         $notificationData       = $notificationDataEnd;
  84.         $notification_type      = $notificationData['type']; // Tipo de notificação, charge ou subscription_charge
  85.         //$invoiceId            = $notificationData['custom_id']; // ID da Fatura
  86.         $charge_id              = (string)$notificationData['identifiers']['charge_id']; // ID da transação
  87.         //$subscription_id      = (string)$notificationData['identifiers']['subscription_id']; // ID da assinatura
  88.         $origPaymentAmount      = (string)$notificationData['value']; // Valor da transação
  89.         $paymentAmount          = $notificationData['value'] / 100; // Valor da transação
  90.         $prevChargeStatus       = (string)$notificationData['status']['previous']; // Status anterior
  91.         $chargeStatus           = (string)$notificationData['status']['current']; // Status atual
  92.        
  93.         echo '<br/>Notificacao:<br/><pre>';
  94.         print_r($notificationData);
  95.         echo '<br>$notificationData type: ', $notification_type, '<br>$paymentAmount: ', $origPaymentAmount, '<br></pre>'; // Debug
  96.        
  97.         // dados do serviço/produto
  98.         if ( $notification_type === 'charge' ) {
  99.            
  100.             $invoiceId                  = $notificationData['custom_id']; // ID do serviço
  101.            
  102.             // Dados da fatura
  103.             $getinvoiceid['invoiceid']  = $invoiceId;
  104.             $invoice_data               = localAPI('getinvoice', $getinvoiceid, $whmcsAdmin);
  105.             $userID                     = $invoice_data['userid']; 
  106.             $invoiceAmount              = $invoice_data['total'];
  107.             $SendedInvoiceAmount        = (string)$invoice_data['total'] * 100;
  108.             $invoiceStatus              = (string)$invoice_data['status'];
  109.             echo '<br/>Dados da Fatura:<br/><pre>'; print_r($invoice_data); echo '</pre>'; // Debug
  110.            
  111.             // Dados do serviço/produto
  112.             $clientservice_values["serviceid"]  = $rel_id;
  113.             $clientservice                  = localAPI( "getclientsproducts", $clientservice_values, $whmcsAdmin );
  114.             echo '<br/>Dados do serviço/produto:<br/><pre>'; print_r($clientservice); echo '<br>$SendedInvoiceAmount: ', $SendedInvoiceAmount, '</pre>'; // Debug
  115.            
  116.         }  
  117.        
  118.         // dados do serviço/produto
  119.         if ( $notification_type === 'subscription_charge' ) {
  120.            
  121.             $rel_id                     = $notificationData['custom_id']; // ID do serviço
  122.             $subscription_id        = (string)$notificationData['identifiers']['subscription_id']; // ID da assinatura
  123.            
  124.             // Dados do serviço/produto
  125.             $clientservice_values["serviceid"]  = $rel_id;
  126.             $clientservice                  = localAPI( "getclientsproducts", $clientservice_values, $whmcsAdmin );
  127.             $userID                     = $clientservice['products']['product']['0']['clientid'];
  128.            
  129.             if ( $userID ) {
  130.                 $subscriptionId                 = (string)$clientservice['products']['product']['0']['subscriptionid']; // ID de assinatura registrado no WHMCS
  131.             }
  132.             echo '<br/>Dados do serviço/produto:<br/><pre>'; print_r($clientservice); echo '</pre>'; // Debug
  133.         }  
  134.        
  135.  
  136.     } catch (GerencianetException $e) {
  137.         die( print_r($e->errorDescription) );
  138.  
  139.     } catch (Exception $e) {
  140.         die( print_r($e->getMessage()) );
  141.     }
  142.    
  143.     // Transação de pagamento uma vez
  144.     if( $notification_type === 'charge' and $chargeStatus === 'paid' and $invoiceStatus === 'Unpaid' and $origPaymentAmount == $SendedInvoiceAmount ) {
  145.    
  146.         $addtransvalues['userid']           = $userID;
  147.         $addtransvalues['invoiceid']        = $invoiceId;
  148.         $addtransvalues['description']      = 'Transação paga via cartão de crédito / Gerencianet';
  149.         $addtransvalues['amountin']         = $invoiceAmount;
  150.         $addtransvalues['fees']             = $fee;
  151.         $addtransvalues['paymentmethod']    = 'gofasgerencianetcartao';
  152.         $addtransvalues['transid']          = $charge_id.'B';
  153.         $addtransvalues['date']             = date('d/m/Y');
  154.         $addtransresult                     = localAPI( 'addtransaction' , $addtransvalues, $whmcsAdmin );
  155.        
  156.         //echo json_encode($addtransresult);
  157.         echo '<br/>Resultado:<br/><pre>'; print_r($addtransresult); echo '</pre>'; // Debug
  158.  
  159.     }
  160.    
  161.     elseif( $notification_type === 'charge' and $chargeStatus === 'unpaid' and $invoiceStatus === 'Unpaid' and $origPaymentAmount === $SendedInvoiceAmount ) {
  162.        
  163.         // Atualiza a transação "Aguardando pagamento"
  164.         foreach (Capsule::table('tblaccounts')
  165.         ->where( 'userid', $userID )
  166.         ->where( 'gateway', 'gofasgerencianetcartao' )
  167.         ->where( 'invoiceid', $invoiceId )
  168.         ->where( 'transid', $charge_id )
  169.         ->where( 'total', $paymentAmount )
  170.         ->get() as $tranInfo) {
  171.  
  172.             $tran_id = $tranInfo->id . PHP_EOL;
  173.             $updatetransaction_values["transactionid"] = $tran_id;
  174.             $updatetransaction_values["transid"] = $charge_id.'C';
  175.             $updatetransaction_values["description"] = "Pagamento não aprovado pela operadora do cartão / Gerencianet";
  176.  
  177.             $updatetransaction = localAPI("updatetransaction",$updatetransaction_values,$whmcsAdmin);
  178.            
  179.         }
  180.        
  181.         // Verifica dados do cliente
  182.         $clientsdetails_['clientid'] = $userID;
  183.         $clientsdetails_['stats'] = false;
  184.         $clientsdetails_['responsetype'] = "json";
  185.  
  186.         $clientsdetails = localAPI( 'getclientsdetails', $clientsdetails_, $whmcsAdmin);
  187.                
  188.         $invoice_user_fname = $clientsdetails['firstname'];
  189.        
  190.         // Envia email para o cliente $userID
  191.         $send_email_['customtype'] = 'invoice';
  192.         $send_email_['customsubject'] = 'Falha no pagamento da fatura #'.$invoiceId;
  193.         $send_email_['custommessage'] = '<p>Olá, '.$invoice_user_fname.'!<br/>Não foi possível completar sua tentativa recente de pagamento da fatura #'.$invoiceId.' via cartão de crédito.<br/>Acesse a fatura <a href="'.$systemUrl.'/viewinvoice.php?id='.$invoiceId.'">neste link</a> e tente realizar o pagamento novamente, talvez com outro cartão de crédito ou uma forma de pagamento diferente.</p>';
  194.         $send_email_['id'] = $invoiceId;
  195.         $send_email = localAPI( 'sendemail', $send_email_, $whmcsAdmin );
  196.        
  197.         // Dispara email para o admin ?
  198.     }
  199.    
  200.     // Transação assinatura
  201.     elseif( $notification_type === 'subscription_charge' and $chargeStatus === 'paid'
  202.     /* and $invoiceStatus !== 'Unpaid' and $subscriptionId === $subscription_id */ ) {
  203.        
  204.         // Verifica Faturas do usuário
  205.         $invoices = array();
  206.         foreach (Capsule::table('tblinvoices')
  207.         ->where( 'userid', $userID )
  208.         ->where( 'paymentmethod', 'gofasgerencianetcartao' )
  209.         ->where( 'status', 'Unpaid' )
  210.         ->where( 'total', $paymentAmount )
  211.         ->get() as $ProductInfo) {
  212.  
  213.             $invoices[] = [ 'id' => $ProductInfo->id . PHP_EOL ];
  214.            
  215.         }
  216.        
  217.         $invoiceId = $invoices['0']['id'];
  218.        
  219.         echo '<br/>Faturas do usuário:<br/><pre>'; print_r($invoices); echo '<br/> Fatura pagável: ', $invoices['0']['id'], '</pre>'; // Debug
  220.  
  221.         // Adiciona pagamento  
  222.         if ($invoiceId) {  
  223.             $addtransvalues['userid']           = $userID;
  224.             $addtransvalues['invoiceid']        = $invoiceId;
  225.             $addtransvalues['description']      = 'Pagamento de assinatura via cartão de crédito / Gerencianet';
  226.             $addtransvalues['amountin']         = $paymentAmount;
  227.             $addtransvalues['fees']             = $fee;
  228.             $addtransvalues['paymentmethod']    = 'gofasgerencianetcartao';
  229.             if ( !$subscriptionId || $subscriptionId !== $subscription_id) {
  230.                 $addtransvalues['transid']          = $charge_id.'B';
  231.             }
  232.             elseif ( $subscriptionId === $subscription_id ) {
  233.                 $addtransvalues['transid']          = $charge_id;
  234.             }
  235.             $addtransvalues['date']             = date('d/m/Y');
  236.             $addtransresult                     = localAPI( 'addtransaction' , $addtransvalues, $whmcsAdmin );
  237.        
  238.             // Adiciona ID da assinatura ao serviço
  239.             if ( !$subscriptionId || $subscriptionId !== $subscription_id ) {
  240.                 $updateclientproduct_["serviceid"] = $rel_id;
  241.                 $updateclientproduct_["subscriptionid"] = $subscription_id;
  242.                 $updateclientproduct = localAPI("updateclientproduct",$updateclientproduct_,$whmcsAdmin);
  243.             }
  244.        
  245.             //echo json_encode($addtransresult);
  246.             echo '<br/>Resultado:<br/><pre>'; print_r($addtransresult); echo '</pre>'; // Debug
  247.         }
  248.     }
  249.    
  250.    
  251.     elseif( $notification_type === 'subscription_charge' and $chargeStatus === 'unpaid'
  252.     /* and $invoiceStatus !== 'Unpaid' and $subscriptionId === $subscription_id */ ) { 
  253.        
  254.         // Verifica Faturas do usuário
  255.         $invoices = array();
  256.         foreach (Capsule::table('tblinvoices')
  257.         ->where( 'userid', $userID )
  258.         ->where( 'paymentmethod', 'gofasgerencianetcartao' )
  259.         ->where( 'status', 'Unpaid' )
  260.         ->where( 'total', $paymentAmount )
  261.         ->get() as $ProductInfo) {
  262.  
  263.             $invoices[] = [ 'id' => $ProductInfo->id . PHP_EOL ];
  264.            
  265.         }
  266.        
  267.         $invoiceId = $invoices['0']['id'];
  268.        
  269.         echo '<br/>Faturas do usuário:<br/><pre>'; print_r($invoices); echo '<br/> Fatura pagável: ', $invoices['0']['id'], '</pre>'; // Debug
  270.        
  271.         // Atualiza a transação "Aguardando pagamento"
  272.         foreach (Capsule::table('tblaccounts')
  273.         ->where( 'userid', $userID )
  274.         ->where( 'gateway', 'gofasgerencianetcartao' )
  275.         ->where( 'invoiceid', $invoiceId )
  276.         ->where( 'transid', $charge_id )
  277.         ->get() as $tranInfo) {
  278.  
  279.             $tran_id = $tranInfo->id . PHP_EOL;
  280.             //print_r($tranInfo);
  281.            
  282.         }
  283.        
  284.         $updatetransaction_values["transactionid"] = $tran_id;
  285.         $updatetransaction_values["transid"] = $charge_id.'C';
  286.         $updatetransaction_values["description"] = "Pagamento recusado pela operadora do cartão / Gerencianet";
  287.  
  288.         $updatetransaction = localAPI("updatetransaction",$updatetransaction_values,$whmcsAdmin);
  289.        
  290.         print_r($updatetransaction);
  291.         echo '<br/> tran_id: '.$tran_id;
  292.         // Verifica dados do cliente
  293.         $clientsdetails_['clientid'] = $userID;
  294.         $clientsdetails_['stats'] = false;
  295.         $clientsdetails_['responsetype'] = "json";
  296.  
  297.         $clientsdetails = localAPI( 'getclientsdetails', $clientsdetails_, $whmcsAdmin);
  298.                
  299.         $invoice_user_fname = $clientsdetails['firstname'];
  300.        
  301.         // Envia email para o cliente $userID
  302.         $send_email_['customtype'] = 'invoice';
  303.         $send_email_['customsubject'] = 'Falha no pagamento da fatura #'.$invoiceId;
  304.         $send_email_['custommessage'] = '<p>Olá, '.$invoice_user_fname.'!<br/>Não foi possível completar sua tentativa recente de pagamento da fatura #'.$invoiceId.' via cartão de crédito.<br/>Acesse a fatura <a href="'.$systemUrl.'/viewinvoice.php?id='.$invoiceId.'">neste link</a> e tente realizar o pagamento novamente, talvez com outro cartão de crédito ou uma forma de pagamento diferente.</p>';
  305.         $send_email_['id'] = $invoiceId;
  306.         $send_email = localAPI( 'sendemail', $send_email_, $whmcsAdmin );
  307.        
  308.         // Dispara email para o admin
  309.     }
  310.      else {
  311.         die('Notificação ignorada.');
  312.     }
  313.  
  314. }
  315. elseif( !$token ) {
  316.     die('Nennhum token válido recebido.');
  317. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement