repositório com os arquivos utilizados para integração entre o sistema SimplesIP e diversos sistemas.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

610 lines
19 KiB

<?php
require_once 'Integracao.php';
include "config.php";
/**
* DESCRICAO DO DESENVOLVEDOR
*
* @author Lucas Awade
* @function developer
* @documentation http://api.elitesoft.com.br/menu/
* @ISPIntegrator 5.0
* @version 1.0.0
*/
class ISPIntegrator extends Integracao
{
private $user;
private $password;
private $url;
private $metodo;
private $subMetodo;
private $query;
private $curl;
private $debug;
private $params = array();
########################################################################
## FUNCOES DA API ##
########################################################################
public function identificarDocumento($documento)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->setMetodo("view.execute");
$doc = $this->mask_cpf_cnpj($documento);
if ($doc) {
$this->params['_consulta'] = "011G0NP05B"; //011G0NP05B
$this->params['formato_padrao'] = "X";
$this->params[(strlen($documento) == 11 ? 'cpf' : 'cnpj')] = $doc;
return $this->setParamsXML();
}
$this->log->error("Mask CPF/CNPJ: {$doc} Nao foi encontrado!", $this->debug);
return false;
} else {
return false;
}
}
public function identificarTelefone($telefone)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->setMetodo("view.execute");
$telefone = $this->mask_phone_tel($telefone);
if ($telefone) {
$this->params['_consulta'] = "011G0NP05B";
$this->params['formato_padrao'] = "X";
$this->params[$telefone['type']] = $telefone['telefone'];
return $this->setParamsXML();
}
$this->log->error("Mask Phone/Tel: " . print_r($telefone, true) . " Nao foi encontrado!", $this->debug);
return false;
} else {
return false;
}
}
public function listaDetalhesServico($codcli)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->setMetodo("list");
$this->setSubMetodo("services.details");
$this->params['codcli'] = $codcli;
return $this->setParamsJSON();
} else {
return false;
}
}
public function abrirChamado($codcli, $codsercli,$codtcoCl)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->setMetodo("list");
$this->setSubMetodo("datasource.criarAtendimento");
$this->params['codcli'] = $codcli;
$this->params['codsercli'] = $codsercli;
$this->params['codocop'] = 'ELZ90OV9SZ';
$this->params['codusu'] = '09';
$this->params['descri_oco'] = 'Desbloqueio provis<EFBFBD>rio';
$this->params['codco_cl'] = $codtcoCl;
return $this->setParamsJSON();
} else {
return false;
}
}
public function getCodcoCl($codcli)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->setMetodo("list");
$this->setSubMetodo("contacts.list");
$this->params['_user'] = $this->user;
$this->params['_passwd'] = $this->password;
$this->params['codcli'] = $codcli;
$this->params['codtco_cl'] = 'FINANCEIRO';
return $this->setParamsJSON();
} else {
return false;
}
}
public function fecharChamadoEmail($codoco)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->setMetodo("list");
$this->setSubMetodo("datasource.fecharAtendimento");
$this->params['codoco'] = $codoco;
$this->params['codsto'] = '01CONCLUID';
$this->params['motivo_fechamento'] = '01RESOLVID';
$this->params['codocop_sol'] = 'ELZ90OV9SZ';
$this->params['descri_oco_sol'] = 'Desbloqueio provis<EFBFBD>rio';
$this->params['enviar_email'] = 'N';
return $this->setParamsJSON();
} else {
return false;
}
}
public function faturasCliente($codcli, $from = '01-01-2000', $to = '')
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->setMetodo("faturas.cliente");
$this->params['codcli'] = $codcli;
$this->params['from'] = $from;
$this->params['to'] = date('Y-m-d', strtotime('+20 days', time()));
return $this->setParamsXML();
} else {
return false;
}
}
public function verBoleto($codFat)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->setMetodo("list");
$this->setSubMetodo("datasource.verBoleto");
$this->params['codfat'] = $codFat;
$this->params['link_publico'] = 'S';
return $this->setParamsJSON();
} else {
return false;
}
}
public function linhaDigitavel($codFat)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->setMetodo("list");
$this->setSubMetodo("datasource.linhaDigitavel");
$this->params['codfat'] = $codFat;
return $this->setParamsJSON();
} else {
return false;
}
}
public function listaServico($codcli)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->setMetodo("list");
$this->setSubMetodo("services.details");
$this->params['codcli'] = $codcli;
return $this->setParamsJSON();
} else {
return false;
}
}
public function planInfo2($codcli)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->setMetodo("list");
$this->setSubMetodo("plan.getInfo2");
$this->params['codcli'] = $codcli;
return $this->setParamsJSON();
} else {
return false;
}
}
public function habilitacaoProvisoria($codsercli)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->setMetodo("list");
$this->setSubMetodo("habilitacaoProvisoria.execute");
$this->params['codsercli'] = $codsercli;
return $this->setParamsJSON();
} else {
return false;
}
}
public function verificaIncidente($codcli)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->setMetodo("view.execute");
$this->params['_consulta'] = "02A50HOX3E";
$this->params['formato_padrao'] = "X";
$this->params['codcli'] = $codcli;
return $this->setParamsXML();
} else {
return false;
}
}
public function validaBoleto($atraso)
{
if ($atraso >= 1) {
return false;
} else {
return true;
}
}
public function diasBaixa($documento)
{
$this->debug = debug_backtrace();
// if ($this->getArgs(func_get_args())) {
$doc = $this->mask_cpf_cnpj($documento);
$this->setMetodo("list");
$this->setSubMetodo("view.execute");
$this->params['_consulta'] = "01FATURAS";
if(strlen($doc) > 15){
$this->params['cnpj'] = $doc;
}else{
$this->params['cpf'] = $doc;
}
return $this->setParamsJSON();
// } else {
// return false;
// }
}
/**
* Envia email das faturas solicitadas.
*
* $faturaMes => Coleta todas as faturas do mês para ser enviadas.
*
* @param string|int $documento
* @param boolean $faturasMes
* @return boolean
*/
public function enviarBoletoFatura($cliente)
{
$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;
}
$dados = $cliente->params->param[1]->value->DOMElement->result->row;
$fatura = $this->faturasCliente($dados->codcli);
$invoices = $fatura->params->param[1]->value->DOMElement->result->row;
if (!$invoices) {
$this->log->info("Nao foi possivel encontrar nenhuma fatura em aberto do solicitante!");
return false;
}
$diasBaixa = $this->diasBaixa($dados->cpf_cnpj);
$this->log->info('Teste Unit: '.var_export($diasBaixa,true));
$dias_baixa = $diasBaixa['data']['results'][0]['dias_baixa'];
$this->log->info('Dias baixa: '. $dias_baixa);
$link = null;
$atraso = 0;
foreach ($invoices as $value) {
if ($value->Quant_dias_venc <= $dias_baixa) {
$invoice = $this->verBoleto($value->codfat);
$line = $this->linhaDigitavel($value->codfat)['data']['results']['codigo_barras'];
$linkInvoice = $invoice['data']['results'][0]['linkPublico'];
$link .= "<b>Codigo do boleto:</b>[ $line ] <a href='{$linkInvoice}' target='_blank'>Visualizar Boleto</a> <br/>";
sleep(1);
} else {
$atraso = 1;
}
}
if ($atraso == 1) {
return 2;
} else {
$data = array('$titulo' => "Envio de Fatura", '$data_ven' => $invoices->data_ven, '$nome' => $dados->nome_cli, '$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>{$dados->nome_cli}</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($dados->e_mail)) {
$this->log->success("O Boleto foi enviado com sucesso!");
return 1;
}
$this->log->error("Nao foi possivel enviar o boleto para o email do solicitante!");
$this->log->error("Error SimpleMail: " . $this->mail->getErrorSend());
return 0;
}
}
public function verificaCodest($codcli,$codest)
{
$this->debug = debug_backtrace();
$codestTrue = 0;
$listar = $this->listaDetalhesServico($codcli);
$planos = $listar['data']['results']['planos'];
foreach($planos as $suspenso){
if($suspenso['codest'] == $codest){
$codestTrue++;
}
}
return $codestTrue;
}
/**
* 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 enviarProtocoloEmail($cliente, $uid)
{
$this->debug = debug_backtrace();
$dados = $cliente->params->param[1]->value->DOMElement->result->row;
if (!$dados) {
$this->log->error('Cliente n<EFBFBD>o preenchido!');
return false;
}
if (!$this->mail) {
$this->log->error('Antes de enviar o email e necessario configurar o SimpleMail e SMTP!');
return false;
}
$protocolo = $this->geraProtocoloSimples($uid);
if (!$protocolo) {
$this->log->info("Protocolo nao preenchido!");
return false;
}
$this->log->info("Protocolo inseridas do E-mail!");
$this->mail->bodyMessage("<h4>Ola, <b>{$dados->nome_cli}</b></h4><p>Segue o protocolo da ligacao.</p><p>{$protocolo}</p>");
$this->log->info("Encaminhando protocolo por E-mail!");
if ($this->mail->mailing($dados->e_mail)) {
$this->log->success("O Protocolo foi enviado com sucesso!");
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());
return false;
}
}
function listaServicoHabilitado($codcli, $infoAll = false)
{
$retorno = $this->listaDetalhesServico($codcli);
$groupService = array();
if ($retorno['data']['results'][0]['planos']) {
$descri_est = explode(' ', $retorno['descri_est'])[1];
if ($descri_est == 'Habilitado') {
if (!in_array($retorno['codgser'], $groupService)) {
$groupService[] = $infoAll ? $retorno : $retorno['codgser'];
}
}
} else {
foreach ($retorno['data']['results']['planos'] as $plano) {
$descri_est = explode(' ', $plano['descri_est'])[1];
if ($descri_est == 'Habilitado') {
if (!in_array($plano['codgser'], $groupService)) {
$groupService[] = $infoAll ? $plano : $plano['codgser'];
}
}
}
}
return $groupService;
}
########################################################################
## FUNCOES DEFAULT DA CLASSE ##
########################################################################
/**
* Coleta as informacoes iniciais para o inicio da integracao com a API.
*
* @param string $user
* @param string $password
* @param boolean $url
*/
public function __construct($user, $password, $url)
{
$this->user = $user;
$this->password = $password;
$this->url = "{$url}/";
$this->setLog(CONF_LOGGER_ATIVO);
$this->log->info("Iniciando integracao", debug_backtrace());
}
/**
* Parametriza o metodo utilizado para a consulta.
*
* @param type $metodo
*/
private function setMetodo($metodo)
{
$this->metodo = $metodo;
}
/**
* Parametriza do submetodo utilizado para a consulta.
*
* @param type $submetodo
*/
private function setSubMetodo($submetodo)
{
$this->subMetodo = $submetodo;
}
/**
* Escreve a query para ser passada para o 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 ser passada para a execucao do Curl
*
* @void
*/
private function curl($type)
{
$this->log->debug($this->query);
$this->curl = curl_init();
curl_setopt($this->curl, CURLOPT_URL, $this->url . (strtoupper($type) == 'XML' ? 'server.php' : 'integrator.server.php'));
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->curl, CURLOPT_POST, 1);
curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
// curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, true);
// curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, true);
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->getQuery());
curl_setopt($this->curl, CURLOPT_ENCODING, "deflate,gzip,br");
if (strtoupper($type) == 'XML') {
curl_setopt($this->curl, CURLOPT_HTTPHEADER, array('Content-Type: text/xml; charset=utf-8; ApplicationV: Integrator/6'));
} else {
curl_setopt($this->curl, CURLOPT_HTTPHEADER, array('Cache-Control: no-cache', 'Content-Type: application/json', 'ApplicationV: Integrator/6'));
}
/*
* Final da linha para pegar os dados da variavel
*/
$this->log->debug("Curl: {$this->curl}", debug_backtrace());
}
/**
* Recebe array de 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 $params
* @debug_track function debug_backtrace()
*/
private function setParamsXML()
{
$this->params['_user'] = $this->user;
$this->params['_passwd'] = $this->password;
$this->setQuery("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><methodCall><methodName>{$this->metodo}</methodName><params>");
foreach ($this->params as $key => $value) {
$this->setQuery("<param name=\"$key\"><value><string><![CDATA[$value]]></string></value></param>");
}
$this->setQuery("</params></methodCall>");
unset($this->params);
return $this->exec('XML');
}
private function setParamsJSON()
{
$x = 0;
$this->setQuery("{");
$this->setQuery(sprintf('"request": {"sendRequest": "integrator.server", "method": "%s", "submethod": "%s",', $this->metodo, $this->subMetodo));
$this->setQuery(sprintf('"params": {"_user":"%s","_passwd":"%s",', $this->user, $this->password));
foreach ($this->params as $key => $value) {
$x++;
$this->setQuery(sprintf('"%s":"%s"', $key, $value));
if (count($this->params) != $x) {
$this->setQuery(", ");
}
}
$this->setQuery("}}}");
unset($this->params);
return $this->exec('JSON');
}
/**
* Recebe as informa<EFBFBD><EFBFBD>es e realiza a execucao da API
*
* @void
*/
private function exec($type)
{
$this->curl($type);
$response = 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;
}
$this->log->debug("Curl Info: " . print_r(curl_getinfo($this->curl), true), debug_backtrace());
curl_close($this->curl);
if (strtoupper($type) == 'XML') {
return $this->response(simplexml_load_string($response));
} else {
return $this->response(json_decode($response, true));
}
}
/**
* Prepara dos dados para ser transmitidos para o metodo a ser retornado a
* integracao.
*
* @return array
*/
private function response($data)
{
$this->log->debug("Reponse API: " . print_r($data, true), $this->debug);
if ($data) {
return $data;
} else {
return false;
}
}
}