|
|
<?php |
|
|
|
|
|
require_once 'Integracao.php'; |
|
|
include "config.php"; |
|
|
|
|
|
/** |
|
|
* CLASSE PARA INTEGRACAO DAS API'S MK SOLUTIONS. |
|
|
* |
|
|
* @documentation: https://documentacao.mksolutions.com.br/display/MK30/Gerenciamento+de+Webservices |
|
|
* @author Jose Henrique Joanoni |
|
|
* @function developer |
|
|
* @company SimplesIP |
|
|
* @version 1.0.3 |
|
|
*/ |
|
|
class MkSolutions extends Integracao { |
|
|
|
|
|
private $token; |
|
|
private $auth; |
|
|
private $password; |
|
|
private $url; |
|
|
private $metodo; |
|
|
private $query; |
|
|
private $curl; |
|
|
private $debug; |
|
|
private $params = array(); |
|
|
private $ssl = false; |
|
|
|
|
|
######################################################################## |
|
|
## FUNCOES DA API ## |
|
|
######################################################################## |
|
|
|
|
|
/** |
|
|
* Metodo utilizado para geracao do token de consultas nas api's. |
|
|
* |
|
|
* @param string $token |
|
|
* @param string $password |
|
|
*/ |
|
|
private function geraToken($token) { |
|
|
if ($this->getArgs(func_get_args())) { |
|
|
$this->params = array( |
|
|
"password" => $this->password, |
|
|
"cd_servico" => 9999 |
|
|
); |
|
|
$this->setMetodo('WSAutenticacao'); |
|
|
$result = $this->setParams($token); |
|
|
|
|
|
if ($result['Token']) { |
|
|
return $this->token = $result['Token']; |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
/** |
|
|
* Metodo para consulta de clientes mediante insercao de CPF ou CNPJ. |
|
|
* |
|
|
* @param string $doc |
|
|
* @return boolean |
|
|
*/ |
|
|
public function identificarDocumento($doc) { |
|
|
$this->debug = debug_backtrace(); |
|
|
if ($this->getArgs(func_get_args())) { |
|
|
$this->geraToken($this->auth); |
|
|
$this->params = array( |
|
|
"doc" => $doc |
|
|
); |
|
|
$this->setMetodo('WSMKConsultaDoc'); |
|
|
return $this->setParams(); |
|
|
} else { |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
/** |
|
|
* Metodo para busca das faturas pendentes do cliente. |
|
|
* |
|
|
* @param int $cd_cliente |
|
|
* @return boolean |
|
|
*/ |
|
|
public function buscaFatura($cd_cliente) { |
|
|
$this->debug = debug_backtrace(); |
|
|
if ($this->getArgs(func_get_args())) { |
|
|
$this->geraToken($this->auth); |
|
|
$this->params = array( |
|
|
"cd_cliente" => $cd_cliente |
|
|
); |
|
|
$this->setMetodo('WSMKFaturasPendentes'); |
|
|
return $this->setParams(); |
|
|
} else { |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
/** |
|
|
* Metodo para busca da segunda via do cliente. |
|
|
* |
|
|
* @param int $cd_fat |
|
|
* @return boolean |
|
|
*/ |
|
|
public function segundaVia($cd_fat) { |
|
|
$this->debug = debug_backtrace(); |
|
|
if ($this->getArgs(func_get_args())) { |
|
|
$this->geraToken($this->auth); |
|
|
$this->params = array( |
|
|
"cd_fatura" => $cd_fat |
|
|
); |
|
|
$this->setMetodo('WSMKSegundaViaCobranca'); |
|
|
return $this->setParams(); |
|
|
} else { |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
/** |
|
|
* Metodo para busca da segunda via do cliente. |
|
|
* |
|
|
* @param int $cd_fat |
|
|
* @return boolean |
|
|
*/ |
|
|
public function faturaViaSMS($cd_fat) { |
|
|
$this->debug = debug_backtrace(); |
|
|
if ($this->getArgs(func_get_args())) { |
|
|
$this->geraToken($this->auth); |
|
|
$this->params = array( |
|
|
"cd_fatura" => $cd_fat |
|
|
); |
|
|
$this->setMetodo('WSMKLDViaSMS'); |
|
|
return $this->setParams(); |
|
|
} else { |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
/** |
|
|
* Metodo para desbloqueio de clientes. |
|
|
* |
|
|
* @param int $cd_con |
|
|
* @return boolean |
|
|
*/ |
|
|
public function desbloqueiaCliente($cd_con) { |
|
|
$this->debug = debug_backtrace(); |
|
|
if ($this->getArgs(func_get_args())) { |
|
|
$this->geraToken($this->auth); |
|
|
$this->params = array( |
|
|
"cd_conexao" => $cd_con |
|
|
); |
|
|
$this->setMetodo('WSMKAutoDesbloqueio'); |
|
|
return $this->setParams(); |
|
|
} else { |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
/** |
|
|
* Metodo para buscar todas as conexoes dos clientes e seus respectivos status |
|
|
* |
|
|
* @param int $cd_cli |
|
|
* @return boolean |
|
|
*/ |
|
|
public function obtemConexao($cd_cli) { |
|
|
$this->debug = debug_backtrace(); |
|
|
if ($this->getArgs(func_get_args())) { |
|
|
$this->geraToken($this->auth); |
|
|
$this->params = array( |
|
|
"cd_cliente" => $cd_cli |
|
|
); |
|
|
$this->setMetodo('WSMKConexoesPorCliente'); |
|
|
return $this->setParams(); |
|
|
} else { |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
/** |
|
|
* Metodo para consulta dos contratos do cliente e seus respectivos status. |
|
|
* |
|
|
* @param int $cd_cli |
|
|
* @return boolean |
|
|
*/ |
|
|
public function obtemContratos($cd_cli) { |
|
|
$this->debug = debug_backtrace(); |
|
|
if ($this->getArgs(func_get_args())) { |
|
|
$this->geraToken($this->auth); |
|
|
$this->params = array( |
|
|
"cd_cliente" => $cd_cli |
|
|
); |
|
|
$this->setMetodo('WSMKContratosPorCliente'); |
|
|
return $this->setParams(); |
|
|
} else { |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
/** |
|
|
* Retorna todas as faturas pendentes dos clientes. |
|
|
* |
|
|
* @param int $cd_cliente |
|
|
* @return boolean |
|
|
*/ |
|
|
public function consultaPendencia($cd_cliente) { |
|
|
$this->debug = debug_backtrace(); |
|
|
if ($this->getArgs(func_get_args())) { |
|
|
$this->geraToken($this->auth); |
|
|
$faturas = $this->buscaFatura($cd_cliente); |
|
|
foreach($faturas['FaturasPendentes'] as $value){ |
|
|
if(strtotime($this->convertDateDefault($value['data_vencimento'])) < strtotime(date('Y-m-d'))){ |
|
|
return true; |
|
|
} |
|
|
} |
|
|
return false; |
|
|
} else { |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
/** |
|
|
* Envia email das faturas solicitadas. |
|
|
* |
|
|
* $faturaMes => Coleta todas as faturas do m<EFBFBD>s para ser enviadas. |
|
|
* |
|
|
* @param string|int $documento |
|
|
* @param boolean $faturasMes |
|
|
* @return boolean |
|
|
*/ |
|
|
public function enviarBoletoFatura($documento, $faturasMes = false) { |
|
|
$this->debug = debug_backtrace(); |
|
|
$pathFileMail = __DIR__ . "/email.html"; |
|
|
|
|
|
if (!$this->mail) { |
|
|
$this->log->error('Antes de enviar o email e necessario configurar o SimpleMail e SMTP!'); |
|
|
return false; |
|
|
} |
|
|
|
|
|
$cliente = $this->identificarDocumento($documento); |
|
|
if (strtoupper($cliente) != 'OK') { |
|
|
$this->log->error('Nao foi possivel encontrar o cliente para identificar o email!'); |
|
|
return false; |
|
|
} |
|
|
|
|
|
$invoice = $this->buscaFatura($cliente['CodigoPessoa']); |
|
|
$invoices = $this->getPaymentInvoice($invoice, CONF_FATURA_DIAS_ANTES, CONF_FATURA_DIAS_APOS); |
|
|
|
|
|
if (!$invoices) { |
|
|
$this->log->info("Nao foi possivel encontrar nenhuma fatura em aberto do solicitante!"); |
|
|
return false; |
|
|
} |
|
|
|
|
|
$invoices = $faturasMes ? $invoices : array($invoices[0]); |
|
|
$locations = []; |
|
|
|
|
|
foreach ($invoices as $inv) { |
|
|
$response = $this->segundaVia($inv); |
|
|
if ($response['status'] == "OK") { |
|
|
$location = __DIR__ . "/boleto_{$response['Fatura']}.pdf"; |
|
|
array_push($locations, $location); |
|
|
$this->log->info("Caminho do arquivo: " . $location); |
|
|
$file = file_get_contents($response['PathDownload']); |
|
|
file_put_contents($location, $file); |
|
|
$this->mail->setAddAttachment(array($location)); |
|
|
$link = "Fatura Num.: {$response['Fatura']} <a href='{$response['PathDownload']}' target='_blank'>Visualizar Boleto</a>"; |
|
|
} |
|
|
} |
|
|
|
|
|
$data = array('$titulo' => "Envio de Fatura", '$nome' => $invoice['Nome'], '$link' => $link); |
|
|
$this->log->info("Faturas inseridas do E-mail!"); |
|
|
|
|
|
if (file_exists($pathFileMail)) { |
|
|
$this->mail->pathBodyMail($pathFileMail, $data); |
|
|
} else { |
|
|
$this->mail->bodyMessage("<h4>Ola, <b>{$cliente['Nome']}</b></h4><p>Conforme solicitado estamos lhe enviando a segunda via de sua fatura.</p><p>{$link}</p>"); |
|
|
} |
|
|
|
|
|
$this->log->info("Encaminhando boleto por E-mail!"); |
|
|
|
|
|
if ($this->mail->mailing($cliente['Email'])) { |
|
|
$this->log->success("O Boleto foi enviado com sucesso!"); |
|
|
foreach($locations as $location){ |
|
|
unlink($location); |
|
|
} |
|
|
return true; |
|
|
} else { |
|
|
$this->log->error("Nao foi possivel enviar o boleto para o email do solicitante!"); |
|
|
$this->log->error("Error SimpleMail: " . $this->mail->getErrorSend()); |
|
|
foreach($locations as $location){ |
|
|
unlink($location); |
|
|
} |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
/** |
|
|
* Coleta os Boletos com o status de vencimento para gerar a segunda via. |
|
|
* |
|
|
* $diasApos => Numero de dias para a busca final sendo default 30 dias. |
|
|
* $diasAntes => Numero de dias para a busca antes do dia atual. |
|
|
* @param array $invoice |
|
|
* @param int $diasAntes |
|
|
* @param int $diasApos |
|
|
* @return array |
|
|
*/ |
|
|
public function getPaymentInvoice($invoice, $diasAntes = 0, $diasApos = 30) { |
|
|
$this->debug = debug_backtrace(); |
|
|
$invoices = array(); |
|
|
$datanow = date('Y-m-d'); |
|
|
|
|
|
$diasIni = $diasAntes ? " -{$diasAntes} days" : null; |
|
|
$diasFim = $diasApos ? " +{$diasApos} days" : null; |
|
|
|
|
|
foreach ($invoice['FaturasPendentes'] as $value) { |
|
|
$invoiceIni = (strtotime($this->convertDateDefault($value['data_vencimento'])) >= strtotime($datanow . $diasIni)); |
|
|
$invoiceFim = (strtotime($this->convertDateDefault($value['data_vencimento'])) <= strtotime($datanow . $diasFim)); |
|
|
if ($invoiceIni && $invoiceFim) { |
|
|
$invoices[] = $value['codfatura']; |
|
|
} |
|
|
} |
|
|
|
|
|
$this->log->debug("Payment Invoices: " . print_r($invoices, true)); |
|
|
|
|
|
return $invoices; |
|
|
} |
|
|
|
|
|
public function consultaParadaTecnica($documento) { |
|
|
$this->debug = debug_backtrace(); |
|
|
if ($this->getArgs(func_get_args())) { |
|
|
$str = sprintf("host='%s' port='%s' dbname='%s' user='%s' password='%s'", CONF_DB_HOST, CONF_DB_PORT, CONF_DB_BASE, CONF_DB_USER, CONF_DB_PASSWD); |
|
|
$connect = pg_connect($str, PGSQL_CONNECT_FORCE_NEW); |
|
|
|
|
|
if (!$connect) { |
|
|
$this->log->info("Erro ao conectar a base de dados: " . pg_last_error(), debug_backtrace()); |
|
|
return false; |
|
|
} |
|
|
|
|
|
$query = "select codpessoa, nome_razaosocial, mk_notificacao_parada.descricao, mk_notificacao_parada.observacoes, dt_hr_parada, cpf |
|
|
from mk_pessoas |
|
|
inner join mk_conexoes on codpessoa=codcliente |
|
|
inner join mk_notificacao_parada_conexoes on cd_conexao=codconexao |
|
|
inner join mk_notificacao_parada on cd_parada=codnotifparada |
|
|
where dt_hr_parada::date between current_date-10 and current_date and |
|
|
retornou='N' |
|
|
and REPLACE(REPLACE(REPLACE(COALESCE(cnpj,cpf),'.',''),'/',''),'-','') = '{$documento}' |
|
|
LIMIT 1"; |
|
|
|
|
|
$result = pg_query($connect, $query); |
|
|
$retorna = pg_fetch_assoc($result); |
|
|
return $retorna; |
|
|
} else { |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
######################################################################## |
|
|
## FUNCOES DEFAULT DA CLASSE ## |
|
|
######################################################################## |
|
|
|
|
|
/** |
|
|
* Coleta as informacoes iniciais para o inicio da integracao com a API. |
|
|
* |
|
|
* @param string $token |
|
|
* @param string $url |
|
|
* @param boolean $log |
|
|
*/ |
|
|
|
|
|
public function __construct($token = CONF_TOKEN_API, $url_api = CONF_URL_API, $password = CONF_PASSWORD_API, $log = CONF_LOGGER_ATIVO) { |
|
|
$this->auth = $token; |
|
|
$this->password = $password; |
|
|
|
|
|
if(end(str_split($url_api)) != '/'){ |
|
|
$url_api .= '/'; |
|
|
} |
|
|
if (strpos($url_api, 'https')) { |
|
|
$this->ssl = true; |
|
|
} |
|
|
$this->integracaoReg(); |
|
|
$this->url = $url_api.'mk/'; |
|
|
$this->setLog($log); |
|
|
$this->log->info("Iniciando integracao", debug_backtrace()); |
|
|
} |
|
|
|
|
|
/** |
|
|
* Parametriza o metodo utilizado para a consulta. |
|
|
* |
|
|
* @param type $metodo |
|
|
*/ |
|
|
private function setMetodo($metodo) { |
|
|
$this->metodo = $metodo; |
|
|
} |
|
|
|
|
|
/** |
|
|
* Escreve a query para ser passada ao curl |
|
|
* |
|
|
* @param string $query |
|
|
*/ |
|
|
private function setQuery($query) { |
|
|
return $this->query .= $query; |
|
|
} |
|
|
|
|
|
/** |
|
|
* retorna a string pronta da query do curl e limpa a variavel. |
|
|
* |
|
|
* @return string $query |
|
|
*/ |
|
|
private function getQuery() { |
|
|
$query = $this->query; |
|
|
unset($this->query); |
|
|
return $query; |
|
|
} |
|
|
|
|
|
/** |
|
|
* Constroi de forma dinamica a string para realizar a execucao do Curl |
|
|
* |
|
|
* @void |
|
|
*/ |
|
|
private function curl() { |
|
|
/* |
|
|
* Final da linha para pegar os dados da variavel |
|
|
*/ |
|
|
$this->curl = curl_init(); |
|
|
curl_setopt($this->curl, CURLOPT_URL, $this->url . $this->metodo . ".rule"); |
|
|
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->params); |
|
|
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1); |
|
|
curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, $this->ssl); |
|
|
curl_setopt($this->curl, CURLOPT_TIMEOUT, 30); |
|
|
$this->log->debug("Curl: {$this->curl}", debug_backtrace()); |
|
|
} |
|
|
|
|
|
/** |
|
|
* Recebe array em forma de indice e valor |
|
|
* |
|
|
* @example array("qtype" => 'test_api', "query" => '123', "oper" => '=') |
|
|
* |
|
|
* @obs sempre chamar a fun<EFBFBD><EFBFBD>o debug_backtrace() para ser dispon<EFBFBD>vel em log |
|
|
* |
|
|
* @param type $token |
|
|
* @debug_track function debug_backtrace() |
|
|
*/ |
|
|
private function setParams($token = null) { |
|
|
$this->params["sys"] = "MK0"; |
|
|
$this->params["token"] = $token ? $token : $this->token; |
|
|
$this->curl(); |
|
|
unset($this->params); |
|
|
return $this->exec(); |
|
|
} |
|
|
|
|
|
/** |
|
|
* Recebe as informa<EFBFBD><EFBFBD>es e realiza a execucao da API |
|
|
* |
|
|
* @void |
|
|
*/ |
|
|
private function exec() { |
|
|
/** |
|
|
* Caso tenha problema de requisi<EFBFBD><EFBFBD>o |
|
|
*/ |
|
|
$content = curl_exec($this->curl); |
|
|
if (curl_errno($this->curl)) { |
|
|
$this->log->error(curl_error($this->curl), debug_backtrace()); |
|
|
curl_close($this->curl); |
|
|
$this->audioError(); |
|
|
return false; |
|
|
} |
|
|
curl_close($this->curl); |
|
|
return $this->response($content); |
|
|
} |
|
|
|
|
|
/** |
|
|
* Prepara dos dados para serem transmitidos para o metodo a serem retornados a |
|
|
* integracao. |
|
|
* |
|
|
* @return array |
|
|
*/ |
|
|
private function response($data) { |
|
|
$this->log->debug("Reponse API: " . print_r(json_decode($data, true), true), $this->debug); |
|
|
if ($data) { |
|
|
return json_decode($data, true); |
|
|
} else { |
|
|
return false; |
|
|
} |
|
|
} |
|
|
|
|
|
} |
|
|
|