Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Módulo Gerencinet Cartão para WHMCS
- * @author Mauricio Gofas | gofas.net
- * @see https://gofas.net/?p=8423
- * @copyright 2017 https://gofas.net
- * @license https://www.gnu.org/licenses/gpl-3.0.pt-br.html
- * @support https://gofas.net/?p=8343
- * @version 1.0.1
- */
- // Reporta todos os erros e avisos do php
- error_reporting(E_ERROR | E_WARNING | E_PARSE);
- // Require libraries needed for gateway module functions.
- require_once __DIR__ . '/../../../init.php';
- require_once __DIR__ . '/../../../includes/gatewayfunctions.php';
- require_once __DIR__ . '/../../../includes/invoicefunctions.php';
- // Require GN PHP SDK
- require __DIR__ . '/sdk/vendor/autoload.php';
- use Illuminate\Database\Capsule\Manager as Capsule;
- use Gerencianet\Exception\GerencianetException;
- use Gerencianet\Gerencianet;
- // Puxa parâmetros de configuração do gateway
- $params = getGatewayVariables('gofasgerencianetcartao');
- // Debug
- //echo '<pre>';print_r($params);echo '</pre>';
- // Morre se o módulo está inativo.
- if (!$params['type']) {
- die("Module Not Activated");
- }
- // Recebe o GN token
- $token = $_POST['notification'];
- //$token = '497fd2cf-7e52-48f0-bbfd-dc2cfb55cfb0'; // assinatura
- //$token = '38c25708-8834-447f-9779-a3e251d20817'; // pagamento uma vez
- if ($token) {
- if( $params['sandboxmode'] ){
- $sandbox = true;
- $client_id = $params['clientidsandbox'];
- $client_secret = $params['clientsecretsandbox'];
- }
- elseif( !$params['testmode'] ){
- $sandbox = false;
- $client_id = $params['clientid'];
- $client_secret = $params['clientsecret'];
- }
- if($params['admin']) {
- $whmcsAdmin = $params['admin'];
- }
- elseif(!$params['admin']){
- $whmcsAdmin = 1;
- }
- $fee = '0.00'; //$params['fee'];
- // Verifica do que se trata a notificação
- $options = [
- 'client_id' => $client_id,
- 'client_secret' => $client_secret,
- 'sandbox' => $sandbox,
- 'debug' => true,
- ];
- $params = [
- 'token' => $token
- ];
- $systemUrl = $params['systemurl'];
- try {
- $api = new Gerencianet($options);
- $notification = $api->getNotification($params, []);
- // Prepara dados retornados
- $notificationDataEnd = end($notification['data']); // @ em caso de bug
- $notificationData = $notificationDataEnd;
- $notification_type = $notificationData['type']; // Tipo de notificação, charge ou subscription_charge
- //$invoiceId = $notificationData['custom_id']; // ID da Fatura
- $charge_id = (string)$notificationData['identifiers']['charge_id']; // ID da transação
- //$subscription_id = (string)$notificationData['identifiers']['subscription_id']; // ID da assinatura
- $origPaymentAmount = (string)$notificationData['value']; // Valor da transação
- $paymentAmount = $notificationData['value'] / 100; // Valor da transação
- $prevChargeStatus = (string)$notificationData['status']['previous']; // Status anterior
- $chargeStatus = (string)$notificationData['status']['current']; // Status atual
- echo '<br/>Notificacao:<br/><pre>';
- print_r($notificationData);
- echo '<br>$notificationData type: ', $notification_type, '<br>$paymentAmount: ', $origPaymentAmount, '<br></pre>'; // Debug
- // dados do serviço/produto
- if ( $notification_type === 'charge' ) {
- $invoiceId = $notificationData['custom_id']; // ID do serviço
- // Dados da fatura
- $getinvoiceid['invoiceid'] = $invoiceId;
- $invoice_data = localAPI('getinvoice', $getinvoiceid, $whmcsAdmin);
- $userID = $invoice_data['userid'];
- $invoiceAmount = $invoice_data['total'];
- $SendedInvoiceAmount = (string)$invoice_data['total'] * 100;
- $invoiceStatus = (string)$invoice_data['status'];
- echo '<br/>Dados da Fatura:<br/><pre>'; print_r($invoice_data); echo '</pre>'; // Debug
- // Dados do serviço/produto
- $clientservice_values["serviceid"] = $rel_id;
- $clientservice = localAPI( "getclientsproducts", $clientservice_values, $whmcsAdmin );
- echo '<br/>Dados do serviço/produto:<br/><pre>'; print_r($clientservice); echo '<br>$SendedInvoiceAmount: ', $SendedInvoiceAmount, '</pre>'; // Debug
- }
- // dados do serviço/produto
- if ( $notification_type === 'subscription_charge' ) {
- $rel_id = $notificationData['custom_id']; // ID do serviço
- $subscription_id = (string)$notificationData['identifiers']['subscription_id']; // ID da assinatura
- // Dados do serviço/produto
- $clientservice_values["serviceid"] = $rel_id;
- $clientservice = localAPI( "getclientsproducts", $clientservice_values, $whmcsAdmin );
- $userID = $clientservice['products']['product']['0']['clientid'];
- if ( $userID ) {
- $subscriptionId = (string)$clientservice['products']['product']['0']['subscriptionid']; // ID de assinatura registrado no WHMCS
- }
- echo '<br/>Dados do serviço/produto:<br/><pre>'; print_r($clientservice); echo '</pre>'; // Debug
- }
- } catch (GerencianetException $e) {
- die( print_r($e->errorDescription) );
- } catch (Exception $e) {
- die( print_r($e->getMessage()) );
- }
- // Transação de pagamento uma vez
- if( $notification_type === 'charge' and $chargeStatus === 'paid' and $invoiceStatus === 'Unpaid' and $origPaymentAmount == $SendedInvoiceAmount ) {
- $addtransvalues['userid'] = $userID;
- $addtransvalues['invoiceid'] = $invoiceId;
- $addtransvalues['description'] = 'Transação paga via cartão de crédito / Gerencianet';
- $addtransvalues['amountin'] = $invoiceAmount;
- $addtransvalues['fees'] = $fee;
- $addtransvalues['paymentmethod'] = 'gofasgerencianetcartao';
- $addtransvalues['transid'] = $charge_id.'B';
- $addtransvalues['date'] = date('d/m/Y');
- $addtransresult = localAPI( 'addtransaction' , $addtransvalues, $whmcsAdmin );
- //echo json_encode($addtransresult);
- echo '<br/>Resultado:<br/><pre>'; print_r($addtransresult); echo '</pre>'; // Debug
- }
- elseif( $notification_type === 'charge' and $chargeStatus === 'unpaid' and $invoiceStatus === 'Unpaid' and $origPaymentAmount === $SendedInvoiceAmount ) {
- // Atualiza a transação "Aguardando pagamento"
- foreach (Capsule::table('tblaccounts')
- ->where( 'userid', $userID )
- ->where( 'gateway', 'gofasgerencianetcartao' )
- ->where( 'invoiceid', $invoiceId )
- ->where( 'transid', $charge_id )
- ->where( 'total', $paymentAmount )
- ->get() as $tranInfo) {
- $tran_id = $tranInfo->id . PHP_EOL;
- $updatetransaction_values["transactionid"] = $tran_id;
- $updatetransaction_values["transid"] = $charge_id.'C';
- $updatetransaction_values["description"] = "Pagamento não aprovado pela operadora do cartão / Gerencianet";
- $updatetransaction = localAPI("updatetransaction",$updatetransaction_values,$whmcsAdmin);
- }
- // Verifica dados do cliente
- $clientsdetails_['clientid'] = $userID;
- $clientsdetails_['stats'] = false;
- $clientsdetails_['responsetype'] = "json";
- $clientsdetails = localAPI( 'getclientsdetails', $clientsdetails_, $whmcsAdmin);
- $invoice_user_fname = $clientsdetails['firstname'];
- // Envia email para o cliente $userID
- $send_email_['customtype'] = 'invoice';
- $send_email_['customsubject'] = 'Falha no pagamento da fatura #'.$invoiceId;
- $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>';
- $send_email_['id'] = $invoiceId;
- $send_email = localAPI( 'sendemail', $send_email_, $whmcsAdmin );
- // Dispara email para o admin ?
- }
- // Transação assinatura
- elseif( $notification_type === 'subscription_charge' and $chargeStatus === 'paid'
- /* and $invoiceStatus !== 'Unpaid' and $subscriptionId === $subscription_id */ ) {
- // Verifica Faturas do usuário
- $invoices = array();
- foreach (Capsule::table('tblinvoices')
- ->where( 'userid', $userID )
- ->where( 'paymentmethod', 'gofasgerencianetcartao' )
- ->where( 'status', 'Unpaid' )
- ->where( 'total', $paymentAmount )
- ->get() as $ProductInfo) {
- $invoices[] = [ 'id' => $ProductInfo->id . PHP_EOL ];
- }
- $invoiceId = $invoices['0']['id'];
- echo '<br/>Faturas do usuário:<br/><pre>'; print_r($invoices); echo '<br/> Fatura pagável: ', $invoices['0']['id'], '</pre>'; // Debug
- // Adiciona pagamento
- if ($invoiceId) {
- $addtransvalues['userid'] = $userID;
- $addtransvalues['invoiceid'] = $invoiceId;
- $addtransvalues['description'] = 'Pagamento de assinatura via cartão de crédito / Gerencianet';
- $addtransvalues['amountin'] = $paymentAmount;
- $addtransvalues['fees'] = $fee;
- $addtransvalues['paymentmethod'] = 'gofasgerencianetcartao';
- if ( !$subscriptionId || $subscriptionId !== $subscription_id) {
- $addtransvalues['transid'] = $charge_id.'B';
- }
- elseif ( $subscriptionId === $subscription_id ) {
- $addtransvalues['transid'] = $charge_id;
- }
- $addtransvalues['date'] = date('d/m/Y');
- $addtransresult = localAPI( 'addtransaction' , $addtransvalues, $whmcsAdmin );
- // Adiciona ID da assinatura ao serviço
- if ( !$subscriptionId || $subscriptionId !== $subscription_id ) {
- $updateclientproduct_["serviceid"] = $rel_id;
- $updateclientproduct_["subscriptionid"] = $subscription_id;
- $updateclientproduct = localAPI("updateclientproduct",$updateclientproduct_,$whmcsAdmin);
- }
- //echo json_encode($addtransresult);
- echo '<br/>Resultado:<br/><pre>'; print_r($addtransresult); echo '</pre>'; // Debug
- }
- }
- elseif( $notification_type === 'subscription_charge' and $chargeStatus === 'unpaid'
- /* and $invoiceStatus !== 'Unpaid' and $subscriptionId === $subscription_id */ ) {
- // Verifica Faturas do usuário
- $invoices = array();
- foreach (Capsule::table('tblinvoices')
- ->where( 'userid', $userID )
- ->where( 'paymentmethod', 'gofasgerencianetcartao' )
- ->where( 'status', 'Unpaid' )
- ->where( 'total', $paymentAmount )
- ->get() as $ProductInfo) {
- $invoices[] = [ 'id' => $ProductInfo->id . PHP_EOL ];
- }
- $invoiceId = $invoices['0']['id'];
- echo '<br/>Faturas do usuário:<br/><pre>'; print_r($invoices); echo '<br/> Fatura pagável: ', $invoices['0']['id'], '</pre>'; // Debug
- // Atualiza a transação "Aguardando pagamento"
- foreach (Capsule::table('tblaccounts')
- ->where( 'userid', $userID )
- ->where( 'gateway', 'gofasgerencianetcartao' )
- ->where( 'invoiceid', $invoiceId )
- ->where( 'transid', $charge_id )
- ->get() as $tranInfo) {
- $tran_id = $tranInfo->id . PHP_EOL;
- //print_r($tranInfo);
- }
- $updatetransaction_values["transactionid"] = $tran_id;
- $updatetransaction_values["transid"] = $charge_id.'C';
- $updatetransaction_values["description"] = "Pagamento recusado pela operadora do cartão / Gerencianet";
- $updatetransaction = localAPI("updatetransaction",$updatetransaction_values,$whmcsAdmin);
- print_r($updatetransaction);
- echo '<br/> tran_id: '.$tran_id;
- // Verifica dados do cliente
- $clientsdetails_['clientid'] = $userID;
- $clientsdetails_['stats'] = false;
- $clientsdetails_['responsetype'] = "json";
- $clientsdetails = localAPI( 'getclientsdetails', $clientsdetails_, $whmcsAdmin);
- $invoice_user_fname = $clientsdetails['firstname'];
- // Envia email para o cliente $userID
- $send_email_['customtype'] = 'invoice';
- $send_email_['customsubject'] = 'Falha no pagamento da fatura #'.$invoiceId;
- $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>';
- $send_email_['id'] = $invoiceId;
- $send_email = localAPI( 'sendemail', $send_email_, $whmcsAdmin );
- // Dispara email para o admin
- }
- else {
- die('Notificação ignorada.');
- }
- }
- elseif( !$token ) {
- die('Nennhum token válido recebido.');
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement