✏️ 正在编辑: Fgts.php
路径:
/srv/systems_dir/yuppiecred-lidernegocios/library/Core/Banco/Service/Icred/Fgts.php
提示:
您可以编辑任何文件(包括二进制文件),但请注意不当修改可能导致文件损坏。
<?php use Carbon\Carbon; use Modules\SimulacaoAberta\Service\SimulacaoAbertaService; class Core_Banco_Service_Icred_Fgts extends Core_Banco_Service_Autocontratacao_Fgts { private $_indiceUsuario = 0; private $_dadosUsuarios; private $_clientId; private $_clientSecret; private $_usuarioId; private $_usuario; private $_authorization; // private $_url = "https://api-hml.icred.app/core-api/oauth/token"; private $_url = "https://api.icred.app/"; private $_bancoId = null; private $_origemConsulta; private $_chaveConsulta = null; function __construct() { $this->_bancoId = Model_Banco::bancoPorNome('ICRED'); if (empty($this->_bancoId)) { throw new Core_Exception("iCred não está cadastrado."); } $application = service('config')->get()->bancos->icred ?? null; if (!$application) { $msgErro = 'API da iCred não está configurada.'; throw new Core_Exception($msgErro); } $this->_dadosUsuarios = Model_UsuariosApi::getByApi('ICRED', 'autocontratacao'); if (count($this->_dadosUsuarios) == 0) { $msgErro = 'Nenhum usuário cadastrado.'; throw new Yuppie_Exception($msgErro); } $this->_clientId = $application->client_id; $this->_clientSecret = $application->client_secret; $options = [ 'id' => $this->_dadosUsuarios[$this->_indiceUsuario]['id'], 'usuario' => $this->_dadosUsuarios[$this->_indiceUsuario]['usuario'], ]; $this->_origemConsulta = 'iCred'; $this->setOptions($options); } public function setOptions(array $options) { $this->_usuarioId = $options['id']; $this->_usuario = $options['usuario']; return $this; } public function getClientId() { return $this->_clientId; } public function getClientSecret() { return $this->_clientSecret; } public function getUsuario() { return $this->_usuario; } public function getUrl() { return $this->_url; } public function getBancoId() { return $this->_bancoId; } public function getOrigemConsulta() { return $this->_origemConsulta; } /** * @throws Exception */ protected function getTokenApi() { //verifica se já tem token gerado $tokenValido = (new Model_DbTable_BancosTokenApi())->checkTokenValido($this->_bancoId, $this->_usuarioId); if ($tokenValido) { $this->_authorization = $tokenValido['token']; return; } $this->newToken(); } protected function newToken() { $auth = base64_encode($this->getClientId() . ":" . $this->getClientSecret()); $params = [ 'grant_type' => 'client_credentials', 'scope' => 'default fgts' ]; $curl = curl_init(); $url = $this->_url . "authorization-server/oauth2/token"; curl_setopt_array($curl, [ CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_POSTFIELDS => http_build_query($params), CURLOPT_HTTPHEADER => [ "Authorization: Basic $auth", "Content-Type: application/x-www-form-urlencoded" ], ]); $response = curl_exec($curl); curl_close($curl); $token = json_decode($response); if (empty($token->access_token)) { Yuppie_Log::write("Consulta iCred geração de newToken: " . print_r($response, 1), $this); if (!$this->setProximoUsuario(true)) { throw new Core_Exception("iCred: " . $token->error_description); } return $this->newToken(); } $this->_authorization = $token->access_token; $expiraEm = Zend_Date::now()->addSecond($token->expires_in); (new Model_DbTable_BancosTokenApi())->saveToken($this->_bancoId, $this->_usuarioId, $this->_authorization, $expiraEm->get('yyyy-MM-dd HH:mm:ss')); Model_UsuariosApi::gravarDataUtilizacao($this->_usuarioId); Yuppie_Log::write("Novo token gerado. Expira em: " . $expiraEm->get('yyyy-MM-dd HH:mm:ss'), $this); } protected function setProximoUsuario($erroAutenticacao = false) { if ($erroAutenticacao) { Model_UsuariosApi::desativarUsuario($this->_usuarioId); } $this->_indiceUsuario++; if (!empty($this->_dadosUsuarios[$this->_indiceUsuario]['id'])) { Yuppie_Log::write("Passando para próximo usuário cadastrado.", $this); $options = [ 'id' => $this->_dadosUsuarios[$this->_indiceUsuario]['id'], 'usuario' => $this->_dadosUsuarios[$this->_indiceUsuario]['usuario'], ]; $this->setOptions($options); } else { Yuppie_Log::write("Fim dos usuários.", $this); return false; } return true; } protected function getResponse($endPoint, $params, $method = 'GET') { $url = $this->_url . $endPoint; $options = [ CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ "Content-Type: application/json", "Authorization: Bearer {$this->_authorization}" ] ]; if ($method == "GET" && !empty($params)) { $url .= '?' . http_build_query($params); $options[CURLOPT_CUSTOMREQUEST] = "GET"; } elseif ($method == "POST") { $params = json_encode($params); $options[CURLOPT_CUSTOMREQUEST] = "POST"; $options[CURLOPT_POSTFIELDS] = $params; } elseif (empty($params)) { $options[CURLOPT_CUSTOMREQUEST] = "GET"; } $options[CURLOPT_URL] = $url; $curl = curl_init(); curl_setopt_array($curl, $options); $jsonResponse = curl_exec($curl); $info = curl_getinfo($curl); $response = json_decode($jsonResponse); curl_close($curl); Yuppie_Log::write("getResponse Service iCred parâmetros enviados para url {$url}:" . print_r($params, true), $this); Yuppie_Log::write("Retorno do getResponse Service iCred:" . print_r($jsonResponse, true), $this); if ($info['code'] == 403) { $this->newToken(); return $this->getResponse($endPoint, $params, $method); } if (empty($response)) { throw new Core_Exception("Nenhuma informação retornada pela API"); } if (!empty($response->errors)) { if (stristr($response->errors[0]->code, "BALANCE")) { return $response; } $message = current($response->errors)->userMessage; throw new Core_Exception("Icred: " . $message); } return $response; } protected function _getMaxSimulation($cpf, $qtdParcelas) { $tabelas = (new Model_Tabela())->getTabelaAutocontratacao('FGTS', $this->getBancoId()); $endPoint = "fgts/v1/max-simulation"; $params = [ 'personCode' => String_Refatorar::formatarCpf($cpf), 'birthdate' => Zend_Date::now()->subYear(30)->get('yyyy-MM-dd'), //data de aniversário do cliente 'sellerPersonCode' => $this->_usuario ]; if (!empty($qtdParcelas)) { $params['numberOfInstallments'] = $qtdParcelas; } if ($tabelas->count() == 0) { $tabelas = []; $tabelas[0] = new stdClass(); $tabelas[0]->codigo = 20; //ICred FGTS | TOP } foreach ($tabelas as $tabela) { $params['productIds'] = [$tabela->codigo]; $response = $this->getResponse($endPoint, $params, "POST"); if (!empty($response->simulations[0]->message) && (stristr($response->simulations[0]->message, "Valor Simulado inferior ao mínimo permitido"))) { continue; } break; } return $response; } public function consultaFgts($cpf, $clienteId, $qtdParcelas) { if (empty($this->_authorization)) { $this->getTokenApi(); } //localiza cliente na base para ver se já tem uuid $cliente = (new Model_DbTable_CallcenterFgts())->findByCpf($cpf, $this->getOrigemConsulta()); if (!empty($cliente->chave_consulta)) { $this->_chaveConsulta = $cliente->chave_consulta; return $this->getBalanceRequest($cliente->chave_consulta, $cpf, (int)$qtdParcelas); } $response = $this->_getMaxSimulation($cpf, $qtdParcelas); return $this->respostaConsultaFgts($response); } protected function respostaConsultaFgts($response) { if (empty($response) || $response->flow->code != 'success' || !empty($response->errors[0])) { $retorno = new stdClass(); if (!empty($response->errors[0]->userMessage)) { $retorno->message = $response->errors[0]->userMessage; return $retorno; } $retorno->message = $response->flow->message ? "Icred: " . $response->flow->message : "Nenhuma informação retornada"; $ultimaMensagem = current($response->balanceRequests); $uuid = $ultimaMensagem->uuid; $simulations = current($response->simulations); if (!empty($ultimaMensagem->status->name) && empty($simulations)) { $retorno->message = $ultimaMensagem->status->name; $uuid = $ultimaMensagem->uuid; } if ($uuid) { $this->_chaveConsulta = $uuid; } if (!empty($simulations->message)) { $retorno->message = $simulations->message; } return $retorno; } $simulation = new stdClass(); foreach($response->simulations as $value) { if (!$value->hasInsurance) { $simulation = $value->data; break; } } $tabela = (new Model_Tabela())->getTabelaAutocontratacao('FGTS', $this->getBancoId()); $data = new stdClass(); $data->condicoes_credito = []; $data->condicoes_credito[0] = new stdClass(); $data->condicoes_credito[0]->parcelas = []; $data->condicoes_credito[0]->valor_liberado = $simulation->netAmount; $data->condicoes_credito[0]->valor_liquido = $simulation->netAmount; $data->condicoes_credito[0]->valor_financiado = $simulation->loanAmount; $data->condicoes_credito[0]->saldo_total = $simulation->netAmount; $data->condicoes_credito[0]->taxa_referencia_mensal = ($simulation->monthlyInterestRate*100); $data->condicoes_credito[0]->codigo_produto = !empty($tabela->codigo) ? [$tabela->codigo] : 20; // ICred FGTS | TOP $data->condicoes_credito[0]->descricao_produto = $simulation->productName; $data->condicoes_credito[0]->codigo_tabela_financiamento = !empty($tabela->codigo) ? [$tabela->codigo] : 20; // ICred FGTS | TOP $data->condicoes_credito[0]->descricao_tabela_financiamento = $simulation->productName; $data->condicoes_credito[0]->prazo = $simulation->numberOfInstallments; // count($response->installments); $data->condicoes_credito[0]->uuid = $simulation->uuid; foreach ($simulation->installments as $key => $parcelas) { $dt = new Zend_Date(); $data->condicoes_credito[0]->parcelas[] = [ "num_parcela" => ($key + 1), "valor_parcela" => $parcelas->amount, "data_vencimento" => $dt->set($parcelas->dueDate)->toString('dd/MM/yyyy'), ]; } $data->origem_consulta = $this->getOrigemConsulta(); return $data; } public function inclusaoFgts($dados, $condicoesCredito, $propostaId) { if (empty($this->_authorization)) { $this->getTokenApi(); } $params = $this->montarParamsFgtsInclusao($dados, $condicoesCredito); $endPoint = "fgts/v1/proposal"; $response = $this->getResponse($endPoint, $params, "POST"); if (!empty($response->error)) { return $response; } sleep(3); //delay pra dar tempo de gerar a CCB $dadosProposta = $this->getProposta($response->uuid); $retorno = new stdClass(); $retorno->numero_proposta = !empty($dadosProposta->number) ? $dadosProposta->number : null; $retorno->token_proposta = $response->uuid; return [$retorno]; } /** * @param $dados * @param $condicoesCredito * @return array */ public function montarParamsFgtsInclusao($dados, $condicoesCredito): array { $fone = trim(String_Refatorar::soNumeros($dados['fone'])); try { $dataNascimento = new Zend_Date($dados['data_nascimento']); } catch (Zend_Date_Exception $e) { throw new Core_Exception("Data de nascimento ({$dados['data_nascimento']}) é inválida."); } $chavePix = trim($dados['chave_pix']); if ($dados['tipo_pix'] == 'telefone') { $chavePix = '+55' . String_Refatorar::soNumeros($chavePix); } $params = [ "simulationUuid" => $condicoesCredito['uuid'], "disbursementPix" => $chavePix, "person" => [ "code" => trim(String_Refatorar::soNumeros($dados['cpf'])), "motherName" => $dados['nome_mae'], "birthdate" => $dataNascimento->get('yyyy-MM-dd'), "professionId" => -2914, // -2914 = T.I. "nationalityCountryId" => 55, "dropdownMaritalStatusId" => $this->_getCodigoEstadoCivil($dados['estado_civil']), "dropdownMaritalPropertySystemId" => -3807, // -3807 = comunhão de bens "isPep" => false, "documentNumber" => $dados['rg'], "emailAddress" => "naotem@gmail.com", "phone" => [ "countryCode" => "055", "areaCode" => substr($fone,0,2), "number" => substr($fone,2, strlen($fone)) ], "address" => [ "dropdownAddressTypeId" => -25, // -25 = CASA "address" => $dados['endereco'], "city" => $dados['cidade'], "state" => $dados['uf'], "district" => $dados['bairro'], "number" => $dados['numero'], "postalCode" => $dados['cep'], "complement" => $dados['complemento'] ] ] ]; return $params; } public function getProposta($uuid) { if (empty($this->_authorization)) { $this->getTokenApi(); } $endPoint = 'fgts/v1/proposals/' . $uuid; $response = $this->getResponse($endPoint, null, "GET"); if (!empty($response->error->message) && $this->_countRequest <= 3) { $this->newToken(); return $this->getProposta($uuid); } return $response; } protected function _getCodigoEstadoCivil(string $estadoCivil) { $estadosCivis = [ "-42" => "CASADO", "-43" => "SOLTEIRO", "-44" => "VIUVO", "-45" => "SEPARADO", "-46" => "DIVORCIADO", "-47" => "UNIAO ESTAVEL", "-43" => "DESQUITADO", "-43" => "NAO CADASTRADO", "-43" => "NAO DEFINIDO", "-43" => "OUTROS", ]; $estadosCivis = array_flip($estadosCivis); return $estadosCivis[$estadoCivil] ?? "-43"; } /** * @param int $clienteId * @param $retorno * @return bool * @throws Exception */ public function tratarMensagemErro(int $clienteId, $retorno) { if (empty($retorno->message) && empty($retorno->details[0])) { Yuppie_Log::write("Não veio informação de erro e retornou NULL no método tratarMensagemErro."); return null; } if ($retorno->type == "BAD_REQUEST" && !stristr($retorno->message, 'Campos inválidos')) { Yuppie_Log::write("Exception erro no processamento com a Icred"); throw new Core_Exception('Erro no processamento com a Icred'); } if (!empty($retorno->details[0])) { $mensagem = $retorno->details[0] ?? null; } else { $mensagem = $retorno->message; } if (empty($mensagem)) { Yuppie_Log::write("Exception erro não informado."); throw new Core_Exception('Erro não informado.'); } $mensagemRetorno = $this->_erroMessageTreatment($mensagem); if (!empty($mensagemRetorno)) { (new Model_DbTable_CallcenterFgts())->insert([ 'base_id' => $clienteId, 'periodo' => 0, 'data_repasse' => null, 'valor' => 0, 'descricao_erro' => $mensagemRetorno['message'], 'origem_consulta' => "Icred", 'chave_consulta' => $this->_chaveConsulta ]); throw new Core_Exception($mensagemRetorno['message'], $mensagemRetorno['code']); } Yuppie_Log::write("Método tratarMensagemErro não pegou mensagem nenhuma no _erroMessageTreatment()"); } public function enviarLinkFormalizacao($numeroContrato, $cpf, $celular) { $endPoint = "fgts/v1/proposals/{$numeroContrato}/resend-signature-url"; $fone = trim(String_Refatorar::soNumeros($celular)); $params = [ "countryCode"=> "055", "areaCode" => substr($fone,0,2), "number" => substr($fone,2, strlen($fone)) ]; $response = $this->getResponse($endPoint, $params, "POST"); if (!empty($response->errors) && stristr($response->errors->userMessage, "Authorization")) { $this->newToken(); return $this->enviarLinkFormalizacao($numeroContrato, $cpf, $celular); } return $response; } public function getBalanceRequest(string $uuid, string $cpf, ?int $qtdParcelas) { if (empty($this->_authorization)) { $this->getTokenApi(); } $endPoint = "fgts/v1/balance-request/" . $uuid; $response = $this->getResponse($endPoint, [], "GET"); if ($response->status->id == -4094 || $response->status->name == "unauthorized_institution" || (!empty($response->errors[0]->code) && $response->errors[0]->code == "IBA__FGTS_AVAILABLE_BALANCE_NOT_FOUND")) { $responseMaxSimulation = $this->_getMaxSimulation($cpf, $qtdParcelas); if (!empty(current($responseMaxSimulation->balanceRequests)->status->id) && current($responseMaxSimulation->balanceRequests)->status->id == -4119) { $retorno = new stdClass(); $retorno->message = $response->status->complement; return $retorno; } return $this->respostaConsultaFgts($responseMaxSimulation); } $retorno = new stdClass(); $retorno->message = $response->status->complement; return $retorno; } public function enviarLinkWhatsapp($promotora, $cpf, $numeroContrato, $celular) { } /** * Busca os contratos digitados e com token para poder ajustar o número da operação * e atualizar o status */ public function importar() { $contratos = (new Model_Contrato())->listar("DATE(data_cadastro) >= DATE(DATE_SUB(NOW(), INTERVAL 7 DAY)) AND token_proposta IS NOT NULL AND banco_id = {$this->_bancoId}"); foreach ($this->_dadosUsuarios as $usuario) { foreach ($contratos as $contrato) { $dadosProposta = $this->getProposta($contrato->token_proposta); if (empty($dadosProposta)) { continue; } if (!empty($dadosProposta->number) && $dadosProposta->number != $contrato->numero_contrato) { (new Model_DbTable_Contrato())->updateNumeroContrato([ 'numero_contrato' => $dadosProposta->number, 'status_proposta' => $dadosProposta->dropdownProposalStatus->complement ], $contrato->id); } else { (new Model_DbTable_Contrato())->updateStatus([ 'status_proposta' => $this->_getStatusProposta($dadosProposta->dropdownProposalStatus->complement) ], "id = " . $contrato->id); } } $this->setProximoUsuario(); } } protected function _getStatusProposta($descricao) { $status = (new Model_StatusProposta())->getOrCreate($descricao); return $status->id; } public function getErros() { } }
💾 保存文件
← 返回文件管理器