Jump to content

[Resolvido] API Itaú PIX - 403 Authentication Failed


Renato Rocha

Postagens Recomendadas

Fala galera, estou tentando consumir a api do Itaú para gerar uma cobrança pix e estou recebendo o erro 403 Authentication Failed. Porém quando tento executar as mesmas instrução via curl no terminal, recebo o retorno do request normalmente.

image.png

O estranho é que estou utilizando uma estrutura similar para obter o token de acesso e lá esta funcionando normalmente.

 

Obs: os endpoints e o token são os de ambiente de produção. Acredito que seja algum problema de comunicação com o certificado, o estranho é que não tenho esse problema ao utilizar o endpoint https://sts.itau.com.br/api/oauth/token para obter o token.

 

Alguém tem alguma ideia do que seria? abraço.

Link to comment
Compartilhe em outros sites

  • Renato Rocha mudou o título para [Resolvido] API Itaú PIX - 403 Authentication Failed
  • 5 weeks later...
  • 1 month later...

Boa tarde a todos, obrigado pelas respostas, no meu caso foi o mesmo do AndreGomes, um "/" no final do endpoint, que para os outros bancos que já homologuei não era problema.

Diante do mesmo retorno e das variadas causas, chego a conclusão de má implementação por parte do Banco. Deveria ser mais específico na rejeição, informando a causa como consta na documentação.

Além das causas mencionadas acima, ao efetuar tentativas frustradas de correção, me era retornado também o mesmo erro genérico 403.

 

Link to comment
Compartilhe em outros sites

Olá andregomes, realmente existem muitas incoerências no manual da API, quebrei a cabeça para conseguir integrar completamente. Mas agora já está integrado a parte de registro e consulta de boletos, caso alguém tenha algum problema, também fico a disposição para auxiliar.

  • Curtir 1
Link to comment
Compartilhe em outros sites

  • 2 weeks later...

Boa noite, estou com esse mesmo erro 403 Authentication Failed no registro do boleto na API de Cobrança v2 

 URL  :='https://api.itau.com.br/cash_management/v2/boletos';
        with HttpClient do
        begin
           IOHandler :=IOHandler;
           Request.Clear;
           Request.CharSet := 'utf-8';
           Request.Accept := '*/*';
           Request.AcceptEncoding := 'gzip, deflate, br';
           Request.ContentType := 'application/json';
           Request.CustomHeaders.Values['Authorization'] :='Bearer '+access_token;
           Request.CustomHeaders.Values['x-itau-apikey'] :=DM.SQL_busca_contaClientID.AsString;
           Request.CustomHeaders.Values['x-itau-flowID'] :=DM.SQL_busca_contaClientID.AsString + 'd7';
           Request.CustomHeaders.Values['x-itau-correlationID'] := DM.SQL_busca_contaClientSecret.AsString;
           Request.UserAgent :='Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; GTB5; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; Maxthon; InfoPath.1; .NET CLR 3.5.30729; .NET CLR 3.0.30618)';
           HandleRedirects := True;
           HTTPOptions := [hoKeepOrigProtocol, hoInProcessAuth];
        end;

        try
          RESULTADO_BOLETO   :='';
          RESULTADO_BOLETO   :=HttpClient.Post(URL, JsontoSend);
         except
          on E: Exception do
          begin
            ERRO_ITTAU       :='SIM';
            RESULTADO_BOLETO :=HttpClient.ResponseText;
            ArquivoJSON      :='';
            ArquivoJSON      := RESULTADO_BOLETO;
            sCAMINHGO_EXE    := (ExtractFilePath(ParamStr(0)) +'Boletos\LogsWebservice\');
            System.AssignFile(newFile, sCAMINHGO_EXE + Trim(sNOSSO_NUMERO_ITAU +'_erro_retorno_itau') + '.json');
            System.Rewrite(newFile);
            WriteLn(newFile, ArquivoJSON);
            System.CloseFile(newFile);
          end
        end;

Link to comment
Compartilhe em outros sites

Em 20/10/2022 at 18:45, ismaelhvaz disse:

Olá andregomes, realmente existem muitas incoerências no manual da API, quebrei a cabeça para conseguir integrar completamente. Mas agora já está integrado a parte de registro e consulta de boletos, caso alguém tenha algum problema, também fico a disposição para auxiliar.

Por favor então me ajuda estou com o mesmo roblema!!!!!

Link to comment
Compartilhe em outros sites

Em 29/10/2022 at 20:46, Jhonlemon Barabosa Ribeiro disse:

Boa noite, estou com esse mesmo erro 403 Authentication Failed no registro do boleto na API de Cobrança v2 

 URL  :='https://api.itau.com.br/cash_management/v2/boletos';
        with HttpClient do
        begin
           IOHandler :=IOHandler;
           Request.Clear;
           Request.CharSet := 'utf-8';
           Request.Accept := '*/*';
           Request.AcceptEncoding := 'gzip, deflate, br';
           Request.ContentType := 'application/json';
           Request.CustomHeaders.Values['Authorization'] :='Bearer '+access_token;
           Request.CustomHeaders.Values['x-itau-apikey'] :=DM.SQL_busca_contaClientID.AsString;
           Request.CustomHeaders.Values['x-itau-flowID'] :=DM.SQL_busca_contaClientID.AsString + 'd7';
           Request.CustomHeaders.Values['x-itau-correlationID'] := DM.SQL_busca_contaClientSecret.AsString;
           Request.UserAgent :='Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; GTB5; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; Maxthon; InfoPath.1; .NET CLR 3.5.30729; .NET CLR 3.0.30618)';
           HandleRedirects := True;
           HTTPOptions := [hoKeepOrigProtocol, hoInProcessAuth];
        end;

        try
          RESULTADO_BOLETO   :='';
          RESULTADO_BOLETO   :=HttpClient.Post(URL, JsontoSend);
         except
          on E: Exception do
          begin
            ERRO_ITTAU       :='SIM';
            RESULTADO_BOLETO :=HttpClient.ResponseText;
            ArquivoJSON      :='';
            ArquivoJSON      := RESULTADO_BOLETO;
            sCAMINHGO_EXE    := (ExtractFilePath(ParamStr(0)) +'Boletos\LogsWebservice\');
            System.AssignFile(newFile, sCAMINHGO_EXE + Trim(sNOSSO_NUMERO_ITAU +'_erro_retorno_itau') + '.json');
            System.Rewrite(newFile);
            WriteLn(newFile, ArquivoJSON);
            System.CloseFile(newFile);
          end
        end;

Bom dia,

 

vc ja fez funcionar no postman? esse trecho ai é qual linguagem?

 

abs!

Link to comment
Compartilhe em outros sites

6 horas atrás, andregomes disse:

Bom dia,

Vc já fez todo processo dos certificados e do token? o código é em PHP?

Linguagem Delphi amigo, eu já fiz o processo de gerar a ativar o certificado digital,estou obtendo o token bearer 100%, mais na hora de emitir o boleto dá erro 403 Authentication Failed. será que essa url não mudou?

 

Link to comment
Compartilhe em outros sites

1 minuto atrás, Jhonlemon Barabosa Ribeiro disse:

Linguagem Delphi amigo, eu já fiz o processo de gerar a ativar o certificado digital,estou obtendo o token bearer 100%, mais na hora de emitir o boleto dá erro 403 Authentication Failed. será que essa url não mudou?

https://api.itau.com.br/cash_management/v2/boletos

Verifique no POSTMAN se vc esta enviando um POST.

 

abaixo segue o codigo que fiz em php e está funcionando, talvez na leitura vc identifique algo q possa estar faltando no seu code.

 

public function enviarBoletoApi2022($boleto) {

        $client = new Client();

        $headers = [
            'x-itau-apikey' => $this->apiitau_cliente_id,
            'x-itau-correlationID' => '3',
            'x-itau-flowID' => '3',
            'Authorization' => 'Bearer ' . $this->token,
            'Content-Type' => 'application/json'
        ];

        $options = ['cert' => [ dirname(__FILE__). "/certificados/cert_{$this->cnpj}.crt"],
                    'ssl_key' => [ dirname(__FILE__). "/certificados/privada_{$this->cnpj}.key"]];

        $id_beneficiario = $boleto['agencia_beneficiario'] . $boleto['conta_beneficiario']. $boleto['digito_verificador_conta_beneficiario'];

        if(strlen($boleto['cpf_cnpj_pagador']) == 11) {
            $tipo_pessoa = "F";
            $numero = 'numero_cadastro_pessoa_fisica": "'.$boleto['cpf_cnpj_pagador'].'"';
        } else {
            $tipo_pessoa = "J";
            $numero = '"numero_cadastro_nacional_pessoa_juridica": "'.$boleto['cpf_cnpj_pagador'].'"';
        }

        $body = '{"data": {
                    "etapa_processo_boleto": "efetivacao",
                    "codigo_canal_operacao": "API",
                    "beneficiario": {
                      "id_beneficiario": "'.$id_beneficiario.'"
                    },
                    "dado_boleto": {
                      "descricao_instrumento_cobranca": "boleto",
                      "tipo_boleto": "a vista",
                      "codigo_carteira": "'.$boleto['tipo_carteira_titulo'].'",
                      "valor_total_titulo": "'.$boleto['valor_cobrado'].'",
                      "codigo_especie": "01",
                      "valor_abatimento": "000",
                      "data_emissao": "'.$boleto['data_emissao'].'",
                      "indicador_pagamento_parcial": true,
                      "quantidade_maximo_parcial": 0,
                      "pagador": {
                        "pessoa": {
                          "nome_pessoa": "'.$boleto['nome_pagador'].'",
                          "tipo_pessoa": {
                            "codigo_tipo_pessoa": "'.$tipo_pessoa.'",
                            '.$numero.'
                          }
                        },
                        "endereco": {
                          "nome_logradouro": "'.$boleto['logradouro_pagador'].'",
                          "nome_bairro": "'.$boleto['bairro_pagador'].'",
                          "nome_cidade": "'.$boleto['cidade_pagador'].'",
                          "sigla_UF": "'.$boleto['uf_pagador'].'",
                          "numero_CEP": "'.$boleto['cep_pagador'].'"
                        }
                      },
                      "dados_individuais_boleto": [
                        {
                          "numero_nosso_numero": "'.$boleto['nosso_numero'].'",
                          "data_vencimento": "'.$boleto['data_vencimento'].'",
                          "valor_titulo": "'.$boleto['valor_cobrado'].'",
                          "texto_uso_beneficiario": "",
                          "texto_seu_numero": "'.$boleto['seu_numero'].'"
                        }
                      ],
                      "multa": {
                        "codigo_tipo_multa": "02",
                        "quantidade_dias_multa": 1,
                        "percentual_multa": "000000100000"
                      },
                      "juros": {
                        "codigo_tipo_juros": 90,
                        "quantidade_dias_juros": 1,
                        "percentual_juros": "000000100000"
                      },
                      "recebimento_divergente": {
                        "codigo_tipo_autorizacao": "01"
                      },
                      "desconto_expresso": false
                    }
                  }
                }';

        try {
            $request = new Request('POST', 'https://api.itau.com.br/cash_management/v2/boletos', $headers, $body);
            $res = $client->sendAsync($request, $options)->wait();
            return json_decode($res->getBody()->getContents(), true);
            //return $res->getBody()->getContents();
        } catch (\GuzzleHttp\Exception\ClientException $e) {


            $response = $e->getResponse();
            $responseBodyAsString = json_decode($response->getBody()->getContents());

            //var_dump($responseBodyAsString->mensagem);
            var_dump($responseBodyAsString);
            exit();
        }


    }

 

Link to comment
Compartilhe em outros sites

2 minutos atrás, Jhonlemon Barabosa Ribeiro disse:

Linguagem Delphi amigo, eu já fiz o processo de gerar a ativar o certificado digital,estou obtendo o token bearer 100%, mais na hora de emitir o boleto dá erro 403 Authentication Failed. será que essa url não mudou?

https://api.itau.com.br/cash_management/v2/boletos

Olá Jhonlemon, a url para registro de boleto é essa mesma, para consulta de boleto é https://secure.api.cloud.itau.com.br/boletoscash/v2/boletos

Verifica se o access token que você esta enviando no Authorization, é mesmo que esta sendo enviado no x-itau-apikey (no x-itau-apikey é sem o 'Bearer')

Link to comment
Compartilhe em outros sites

Em 29/10/2022 at 20:46, Jhonlemon Barabosa Ribeiro disse:

Boa noite, estou com esse mesmo erro 403 Authentication Failed no registro do boleto na API de Cobrança v2 

 URL  :='https://api.itau.com.br/cash_management/v2/boletos';
        with HttpClient do
        begin
           IOHandler :=IOHandler;
           Request.Clear;
           Request.CharSet := 'utf-8';
           Request.Accept := '*/*';
           Request.AcceptEncoding := 'gzip, deflate, br';
           Request.ContentType := 'application/json';
           Request.CustomHeaders.Values['Authorization'] :='Bearer '+access_token;
           Request.CustomHeaders.Values['x-itau-apikey'] :=DM.SQL_busca_contaClientID.AsString;
           Request.CustomHeaders.Values['x-itau-flowID'] :=DM.SQL_busca_contaClientID.AsString + 'd7';
           Request.CustomHeaders.Values['x-itau-correlationID'] := DM.SQL_busca_contaClientSecret.AsString;
           Request.UserAgent :='Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; GTB5; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; Maxthon; InfoPath.1; .NET CLR 3.5.30729; .NET CLR 3.0.30618)';
           HandleRedirects := True;
           HTTPOptions := [hoKeepOrigProtocol, hoInProcessAuth];
        end;

        try
          RESULTADO_BOLETO   :='';
          RESULTADO_BOLETO   :=HttpClient.Post(URL, JsontoSend);
         except
          on E: Exception do
          begin
            ERRO_ITTAU       :='SIM';
            RESULTADO_BOLETO :=HttpClient.ResponseText;
            ArquivoJSON      :='';
            ArquivoJSON      := RESULTADO_BOLETO;
            sCAMINHGO_EXE    := (ExtractFilePath(ParamStr(0)) +'Boletos\LogsWebservice\');
            System.AssignFile(newFile, sCAMINHGO_EXE + Trim(sNOSSO_NUMERO_ITAU +'_erro_retorno_itau') + '.json');
            System.Rewrite(newFile);
            WriteLn(newFile, ArquivoJSON);
            System.CloseFile(newFile);
          end
        end;

Eu não vi aqui vc carregando os certificados novamente, eles precisam ir no cabeçalho da requisição.

Link to comment
Compartilhe em outros sites

procedure TF_boleto.EnviarBoletoItau;
var mURL, sResponse, mCode : string;
HTTP, HttpClient: TIdHTTP;
FParams, access_token, refresh_token : String;
Json, scope, token_type, expires_in, RESULTADO_BOLETO : String;
JsontoSend, AResponseContent : TStringStream;
var IOHandler : TIdSSLIOHandlerSocketOpenSSL;
var JsonResponse: TJSONObject;
    Stream: TStringStream;
    nResp : Integer;
    RequestBody : TStringList;
var RIO :THTTPRIO;
var Resp, Req, Resp_Cobranca, Req_Cobranca: TStringStream;
var Result, s, recieveID, DATA_EMISSAO, DATA_VENCIMENTO, ArquivoJSON, ACESSO_TOKEN, RESULTADO_TOKEN, valorTexto : String;
var TICKET_XML, XML_COBRANCA : TStringList;
var Node : IXMLNode;
NodeSec : IXMLNode;
var newFile, Arq_Liberacao : TextFile;
var TICKET, RET_CODE, TIPO_PESSOA, TIPO_AMBIENTE, NSU, sCAMINHGO_EXE, FURLToken, URL, NUMERO_CADASTRO_PESSOA, JSON_TOKEN, JSON_BOLETO : String;
var DIAS_MULTA, DATA_HORA_TOKEN : Integer;
var
  AuthNetHTTP: TIdHttp;
  AuthNetSSL: TIdSSLIOHandlerSocketOpenSSL;
  XMLRequest: TStringStream;
  XMLResponse, TIPO_VALIDACAO, ID_BENEFICIARIO, VALOR_BOLETO, TIPO_CLIENTE, VALOR_JUROS, VALOR_MULTAS, TextoOriginal  : String;
  var JsonStreamRetorno, JsonStreamEnvio: TStringStream;
  SSL : TIdSSLIOHandlerSocketOpenSSL;
begin
  //-----Todo conhecimento que o homem possui é dada por DEUS-------------------
  if Length(DM.SQL_contas_receber_boletoCPF_CNPJ_Cliente.AsString) = 14 then
  begin
    TIPO_CLIENTE             := 'J';
    NUMERO_CADASTRO_PESSOA   := 'numero_cadastro_nacional_pessoa_juridica';
  end
  else
  begin
    TIPO_CLIENTE := 'F';
    NUMERO_CADASTRO_PESSOA   := 'numero_cadastro_pessoa_fisica';
  end;
  DATA_EMISSAO     :=PegarNumeros(DateToStr(DM.SQL_contas_receber_boletoDetalhe_Data_Emissao.AsDateTime));
  DATA_VENCIMENTO  :=PegarNumeros(DateToStr(DM.SQL_contas_receber_boletoDetalhe_Data_Vencimento.AsDateTime));
  TIPO_VALIDACAO   :='';
  if DM.TIPO_AMBIENTE_BOLETO = 'Homologação' then
  begin
    TIPO_VALIDACAO :='validacao';
  end
  else
  begin
    TIPO_VALIDACAO :='efetivacao';
  end;
  DATA_EMISSAO     :=Copy(DATA_EMISSAO, 5, 4)+ '-'+  Copy(DATA_EMISSAO, 3, 2)+ '-'+Copy(DATA_EMISSAO, 1, 2);
  DATA_VENCIMENTO  :=Copy(DATA_VENCIMENTO , 5, 4)+ '-'+  Copy(DATA_VENCIMENTO , 3, 2)+ '-'+Copy(DATA_VENCIMENTO , 1, 2);
  ID_BENEFICIARIO          :='';
  ID_BENEFICIARIO          :=DM.SQL_busca_contaEmpresa_Agencia.AsString + FormatFloat('0000000', DM.SQL_busca_contaEmpresa_conta.AsInteger) + DM.SQL_busca_contaEmpresa_Conta_Digito.AsString;
  VALOR_BOLETO             :='';
  VALOR_BOLETO             :=PegarNumeros(FormatFloat('#000000000000000.00', DM.SQL_contas_receber_boletoDetalhe_Valor_Falta.AsFloat));
  VALOR_MULTAS             :=PegarNumeros(FormatFloat('#000000000000000.00', roundabnt(DM.SQL_busca_contaMULTA_DIA.AsFloat,-2)));
  VALOR_JUROS              :=PegarNumeros(FormatFloat('#000000000000000.00', roundabnt(VALOR_MOURA_JUROS,-2)));

  JSON_BOLETO :='{' + #13 +
                '    "data": {' + #13 +
                '        "etapa_processo_boleto": "'+TIPO_VALIDACAO+'",' + #13 +
                '        "codigo_canal_operacao": "API",' + #13 +
                '        "beneficiario": {' + #13 +
                '            "id_beneficiario": "'+ID_BENEFICIARIO+'"' + #13 +
                '        },' + #13 +
                '        "dado_boleto": {' + #13 +
                '            "descricao_instrumento_cobranca": "boleto",' + #13 +
                '            "tipo_boleto": "a vista",' + #13 +
                '            "codigo_carteira": "'+DM.SQL_busca_contaCarteira.AsString +'",' + #13 +
                '            "valor_total_titulo": "'+VALOR_BOLETO+'",' + #13 +
                '            "codigo_especie": "01",' + #13 +
                '            "valor_abatimento": "000",' + #13 +
                '            "data_emissao": "'+DATA_EMISSAO+'",' + #13 +
                '            "indicador_pagamento_parcial": false,' + #13 +
                '            "quantidade_maximo_parcial": 0,' + #13 +
                '            "pagador": {' + #13 +
                '                "pessoa": {' + #13 +
                '                    "nome_pessoa": "'+TrocaEComercialPorE(TiraAcentos(Copy(DM.SQL_contas_receber_boletoNomeRazaoSocial.AsString, 1, 50)))+'",' + #13 +
                '                    "tipo_pessoa": {' + #13 +
                '                        "codigo_tipo_pessoa": "'+TIPO_CLIENTE+'",' + #13 +
                '                        "'+NUMERO_CADASTRO_PESSOA+'": "'+DM.SQL_contas_receber_boletoCPF_CNPJ_Cliente.AsString+'"' + #13 +
                '                    }' + #13 +
                '                },' + #13 +
                '                "endereco": {' + #13 +
                '                    "nome_logradouro": "'+TrocaEComercialPorE(TiraAcentos(Copy(DM.SQL_contas_receber_boletoEndereco.AsString, 1, 40)))+ ', '+Copy(DM.SQL_contas_receber_boletoNumero.AsString, 1, 5)+'",' + #13 +
                '                    "nome_bairro": "'+TrocaEComercialPorE(TiraAcentos(Copy(DM.SQL_contas_receber_boletoBairro.AsString, 1, 40)))+'",' + #13 +
                '                    "nome_cidade": "'+TrocaEComercialPorE(TiraAcentos(Copy(DM.SQL_contas_receber_boletoCidade.AsString, 1, 40)))+'",' + #13 +
                '                    "sigla_UF": "'+DM.SQL_contas_receber_boletoUF.AsString+'",' + #13 +
                '                    "numero_CEP": "'+DM.SQL_contas_receber_boletoCEP.AsString+'"' + #13 +
                '                }' + #13 +
                '            },' + #13 +
                '            "dados_individuais_boleto": [{' + #13 +
                '                "numero_nosso_numero": "'+sNOSSO_NUMERO_ITAU+'",' + #13 +
                '                "data_vencimento": "'+DATA_VENCIMENTO+'",' + #13 +
                '                "valor_titulo": "'+VALOR_BOLETO+'",' + #13 +
                '                "texto_uso_beneficiario": "'+DM.SQL_contas_receber_boletoDetalhe_N_Parcela.AsString+'",' + #13 +
                '                "texto_seu_numero": "'+DM.SQL_contas_receber_boletoDetalhe_N_Documento.AsString+'"' + #13 +
                '            }],' + #13 +
                '            "multa": {' + #13 +
                '                "codigo_tipo_multa": "02",' + #13 +
                '                "quantidade_dias_multa": 1,' + #13 +
                '                "percentual_multa": "'+VALOR_MULTAS+'"' + #13 +
                '            },' + #13 +
                '            "juros": {' + #13 +
                '                "codigo_tipo_juros": 93,' + #13 +
                '                "quantidade_dias_juros": 1,' + #13 +
                '                "valor_juros": "'+VALOR_JUROS+'"' + #13 +
                '            },' + #13 +
                '            "recebimento_divergente": {' + #13 +
                '                "codigo_tipo_autorizacao": "03"' + #13 +
                '            },' + #13 +
               // '            "instrucao_cobranca": [' + #13 +
               // '                {' + #13 +
               // '                    "codigo_instrucao_cobranca": "4",' + #13 +
               // '                    "quantidade_dias_apos_vencimento":60,' + #13 +
               // '                    "dia_util":false' + #13 +
               // '                }        ' + #13 +
               // '            ],  ' + #13 +
                '            "protesto": {' + #13 +
                '                "protesto": 4,' + #13 +
                '                "quantidade_dias_protesto": 1' + #13 +
                '            },' + #13 +
                '            "negativacao": { ' + #13 +
                '                 "negativacao": 5, ' + #13 +
                '                 "quantidade_dias_negativacao": 1 ' + #13 +
                '             }, ' + #13 +
                '        ' + #13 +
                '            "desconto_expresso": false' + #13 +
                '        }' + #13 +
                '    }' + #13 +
                '}';

   ArquivoJSON          := '';
   ArquivoJSON          := JSON_BOLETO;
   sCAMINHGO_EXE        := (ExtractFilePath(ParamStr(0)) +'Boletos\LogsWebservice\');
   System.AssignFile(newFile, sCAMINHGO_EXE + Trim('Registro _Itau_'+sNOSSO_NUMERO_ITAU) + '.json');
   System.Rewrite(newFile);
   WriteLn(newFile, ArquivoJSON);
   System.CloseFile(newFile);

   RESULTADO_TOKEN  :='';
   access_token     :='';
   JSON_TOKEN       := 'grant_type=client_credentials&client_id='+ DM.SQL_busca_contaClientID.AsString+'&client_secret='+DM.SQL_busca_contaClientSecret.AsString;
   try
     HttpClient := TIdHTTP.Create( nil );
     SSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
     HttpClient.IOHandler := SSL;
     JsonStreamEnvio   := TStringStream.Create(utf8Encode(JSON_TOKEN));
     DATA_HORA_TOKEN      :=DM.conecta.ExecSQLScalar('SELECT IFNULL(TIMESTAMPDIFF (MINUTE,Data_access_token,NOW()),8) AS QTD_Horas FROM configuracao_boleto where Codigo_Config_Boleto =:BANCO and CodLoja_Boleto =:COD_LOJA', [DM.COD_BANCO, DM.COD_LOJA]);
     if DATA_HORA_TOKEN >= 4 then
     begin
       with SSL.SSLOptions do
       begin
         CertFile     := ExtractFilePath(ParamStr(0)) +'Boletos\Certificado\Itau\ARQUIVO_CERTIFICADO.crt';
         KeyFile      := ExtractFilePath(ParamStr(0)) +'Boletos\Certificado\Itau\ARQUIVO_CHAVE_PRIVADA.key';
         Mode         := sslmUnassigned;
         Method       := sslvSSLv23;
         SSLVersions  := [sslvSSLv23];
       end;

       URL  :='URL_no_site';
       with HttpClient do
       begin
          Request.CharSet := 'utf-8';
          Request.Accept := '*/*';
          Request.AcceptEncoding := 'gzip, deflate, br';
          Request.CustomHeaders.Values['Content-Type'] := 'application/x-www-form-urlencoded';
          Request.UserAgent := 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; GTB5; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; Maxthon; InfoPath.1; .NET CLR 3.5.30729; .NET CLR 3.0.30618)';
          HandleRedirects := True;
          HTTPOptions := [hoKeepOrigProtocol, hoInProcessAuth];
       end;

       try
         RESULTADO_TOKEN := HttpClient.Post(URL,JsonStreamEnvio);
          Except
       on E: Exception do
         begin
           ERRO_ITTAU      :='SIM';
           RESULTADO_TOKEN :=HttpClient.ResponseText;
           ArquivoJSON     :='';
           ArquivoJSON     := RESULTADO_TOKEN;
           sCAMINHGO_EXE   := (ExtractFilePath(ParamStr(0)) +'Boletos\LogsWebservice\');
           System.AssignFile(newFile, sCAMINHGO_EXE + Trim(sNOSSO_NUMERO_ITAU +'_erro_retorno_itau') + '.json');
           System.Rewrite(newFile);
           WriteLn(newFile, ArquivoJSON);
           System.CloseFile(newFile);
         end;
       end;

       if HttpClient.ResponseCode = 200 then
       begin
         access_token  :='';
         expires_in    :='';
         access_token  :=getCamposJsonString(RESULTADO_TOKEN, 'access_token');
         expires_in    :=getCamposJsonString(RESULTADO_TOKEN, 'expires_in');
         scope         :=getCamposJsonString(RESULTADO_TOKEN, 'scope');
         DM.conecta.ExecSQL('update configuracao_boleto set access_token =:TOKEN, Scope =:SCOPE, expires_in =:EXPIRA, Data_access_token =NOW() where Codigo_Config_Boleto =:BANCO and CodLoja_Boleto =:COD_LOJA', [access_token, scope, StrToInt(expires_in), DM.COD_BANCO, DM.COD_LOJA]);
       end
        else
       begin
         ERRO_ITTAU     :='SIM';
         ArquivoJSON    :='';
         ArquivoJSON    := RESULTADO_TOKEN;
         sCAMINHGO_EXE  := (ExtractFilePath(ParamStr(0)) +'Boletos\LogsWebservice\');
         System.AssignFile(newFile, sCAMINHGO_EXE + Trim(sNOSSO_NUMERO_ITAU +'_erro_retorno_itau') + '.json');
         System.Rewrite(newFile);
         WriteLn(newFile, ArquivoJSON);
         System.CloseFile(newFile);
       end;
     end
     else
     begin
       access_token  :='';
       access_token  :=DM.conecta.ExecSQLScalar('select IFNULL(access_token, "") AS token from configuracao_boleto where Codigo_Config_Boleto =:BANCO and CodLoja_Boleto =:COD_LOJA', [DM.COD_BANCO, DM.COD_LOJA]);
     end;
    finally
     FreeAndNil(HttpClient);
     FreeAndNil(SSL);
     FreeAndNil(JsonStreamEnvio);
   end;

   if access_token <> '' then
   begin
      try
        HttpClient := TIdHTTP.Create( nil );
        SSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
        HttpClient.IOHandler := SSL;
        AResponseContent := TStringStream.Create('');
        JsonToSend := TStringStream.Create(JSON_BOLETO, TEncoding.UTF8);
        with SSL.SSLOptions do
        begin
          CertFile     := ExtractFilePath(ParamStr(0)) +'Boletos\Certificado\Itau\ARQUIVO_CERTIFICADO.crt';
          KeyFile      := ExtractFilePath(ParamStr(0)) +'Boletos\Certificado\Itau\ARQUIVO_CHAVE_PRIVADA.key';
          Mode         :=sslmUnassigned;
          Method       :=sslvSSLv23;
          SSLVersions  :=[sslvSSLv23];
        end;

        URL  :='URL_no_site';
        with HttpClient do
        begin
          IOHandler :=IOHandler;
          Request.Clear;
          Request.CharSet := 'utf-8';
          Request.Accept := '*/*';
          Request.AcceptEncoding := 'gzip, deflate, br';
          Request.ContentType := 'application/json';
          Request.CustomHeaders.Values['Authorization'] :='Bearer '+access_token;
          Request.CustomHeaders.Values['x-itau-apikey'] :=DM.SQL_busca_contaClientID.AsString;
          Request.CustomHeaders.Values['x-itau-flowID'] :=DM.SQL_busca_contaClientID.AsString + 'd7';
          Request.CustomHeaders.Values['x-itau-correlationID'] := DM.SQL_busca_contaClientSecret.AsString;
          Request.UserAgent :='Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; GTB5; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; Maxthon; InfoPath.1; .NET CLR 3.5.30729; .NET CLR 3.0.30618)';
          HandleRedirects := True;
          HTTPOptions := [hoKeepOrigProtocol, hoInProcessAuth];
        end;

        try
          RESULTADO_BOLETO   :='';
          RESULTADO_BOLETO   :=HttpClient.Post(URL, JsontoSend);
         except
          on E: Exception do
          begin
            ERRO_ITTAU       := 'SIM';
            RESULTADO_BOLETO := HttpClient.ResponseText;
            ArquivoJSON      := '';
            ArquivoJSON      := RESULTADO_BOLETO;
            sCAMINHGO_EXE    := (ExtractFilePath(ParamStr(0)) +'Boletos\LogsWebservice\');
            System.AssignFile(newFile, sCAMINHGO_EXE + Trim(sNOSSO_NUMERO_ITAU +'_erro_retorno_itau') + '.json');
            System.Rewrite(newFile);
            WriteLn(newFile, ArquivoJSON);
            System.CloseFile(newFile);
          end
        end;

        if HttpClient.ResponseCode = 200 then
        begin
           ArquivoJSON      :='';
           ArquivoJSON      := RESULTADO_BOLETO;
           sCAMINHGO_EXE    := (ExtractFilePath(ParamStr(0)) +'Boletos\LogsWebservice\');
           System.AssignFile(newFile, sCAMINHGO_EXE + Trim(sNOSSO_NUMERO_ITAU +'_retorno_itau') + '.json');
           System.Rewrite(newFile);
           WriteLn(newFile, ArquivoJSON);
           System.CloseFile(newFile);

           TextoOriginal    :='';
           valorTexto       :='';
           TextoOriginal    := RESULTADO_BOLETO;
           valorTexto       := Copy(TextoOriginal , Pos('numero_linha_digitavel', TextoOriginal) + 26, Length(TextoOriginal));
           LINHA_DIGITAVEL  :='';
           LINHA_DIGITAVEL  := Copy(valorTexto,1, 47);

           TextoOriginal    :='';
           valorTexto       :='';
           TextoOriginal    := RESULTADO_BOLETO;
           valorTexto       := Copy(TextoOriginal , Pos('codigo_barras', TextoOriginal) + 17, Length(TextoOriginal));
           COD_BARRA_BOLETO := '';
           COD_BARRA_BOLETO := Copy(valorTexto,1, 44);

           XMLTemporario.Append;
           XMLTemporarioNossoNumero.AsString     :=LINHA_DIGITAVEL;
            if Length(OnlyNumber(LINHA_DIGITAVEL)) = 47 then
           begin
             XMLTemporarioStatus.AsString        :='OK';
             XMLTemporarioObs.AsString           :='Boleto Registrado com Sucesso';
           end
           else
           begin
             ERRO_ITTAU                          :='SIM';
             XMLTemporarioStatus.AsString        :='ERRO';
             XMLTemporarioObs.AsString           :='Erro ao Registrar Boleto via API';
           end;
           XMLTemporarioNumeroDocumento.AsString :=NR_DOCUMENTO;
           XMLTemporarioParcela.AsInteger        :=NR_PARCELA;
           XMLTemporario.Post;
           XMLTemporario.Close;
           XMLTemporario.Open;
        end
        else
        begin
          ERRO_ITTAU       :='SIM';
          ArquivoJSON      :='';
          ArquivoJSON      := HttpClient.ResponseText;
          sCAMINHGO_EXE    := (ExtractFilePath(ParamStr(0)) +'Boletos\LogsWebservice\');
          System.AssignFile(newFile, sCAMINHGO_EXE + Trim(sNOSSO_NUMERO_ITAU +'_erro_retorno_itau') + '.json');
          System.Rewrite(newFile);
          WriteLn(newFile, ArquivoJSON);
          System.CloseFile(newFile);
        end;
      finally
       FreeAndNil(HttpClient);
       FreeAndNil(SSL);
       FreeAndNil(JsonStreamEnvio);
      end;
   end
   else
   begin
     ERRO_ITTAU  :='SIM';
   end;

 

Aqui estou passando o certificado digital, para obter o token bearer precisa do certificado digital também e está funcionando. Mais na hora de emitir o boleto dá erro.

curl --location --request POST 'https://api.itau.com.br/cash_management/v2/boletos' \
--header 'x-itau-apikey: 0dbdedc3-3561-453f-b468-3d65d8850e18' \
--header 'x-itau-correlationID: A92EFCB3-E4D7-4DF7-BA68-C6817F184CF2' \
--header 'x-itau-flowID: 5BF9140C-57E9-11ED-9B6A-0242AC120002' \
--header 'Authorization: Bearer eyJraWQiOiIxNDZlNTY1Yy02ZjQ4LTRhN2EtOTU3NS1kYjg2MjE5YTc5N2MucHJkLmdlbi4xNTk3NjAwMTI1ODQ4Lmp3dCIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiIwZGJkZWRjMy0zNTYxLTQ1M2YtYjQ2OC0zZDY1ZDg4NTBlMTgiLCJpc3MiOiJodHRwczovL29wZW5pZC5pdGF1LmNvbS5ici9hcGkvb2F1dGgvdG9rZW4iLCJpYXQiOjE2NjcwODg3ODksImV4cCI6MTY2NzA4OTA4OSwiQWNjZXNzX1Rva2VuIjoiMmFhM2ZlOTUuNjZmMTU1MWUtYjQ2Ny00YWUxLTk4NGQtZTJjNTE5YmNhMzVlIiwidXNyIjoibnVsbCIsImZsb3ciOiJDQyIsInNvdXJjZSI6IkVYVCIsInNpdGUiOiJjdG1tMSIsImVudiI6IlAiLCJtYmkiOiJ0cnVlIiwiYXV0IjoiTUFSIiwidmVyIjoidjEuMCIsInNjb3BlIjoiZXNjb3BvX2RlZmF1bHQgYXBwaWQtODE5YjE4ZjUtM2FjYS00ZWI1LTg5MTUtYWNkNGU2NGFkYTAwIiwidXNlcl9pZCI6IjBkYmRlZGMzLTM1NjEtNDUzZi1iNDY4LTNkNjVkODg1MGUxOCIsInNzbF9jbGllbnRfY2VydCI6Ik5qVTZRalE2UWtFNk1rVTZPVGs2TWtJNlFUTTZOamc2UVVFNk1qUTZSVE02UkRBNk9UVTZPVFU2TVRBNk5EazZOalk2T1RBNk56YzZNRGs9In0.VLDYarYJQ0M7FwQZcIRwTFXV4yKxL_MwvEM2tniqh6mPMeE6zIK0bbRVPgb8e2Vnzlms-Bife-gZRMwrEsexn8PUXtpE76CwHUWOK4Brw2p-zWSwR6ABwSg3QDNrxkmdONnaKH2TT873tCGKWENLlxgtxAjz83RdOIGj4-Suj39OkyQKnch7s6-TY68ISVXwwk2zR7KPe7TzwRi55npKVDyAdGh9MyvbwEhmxmZ-eg_jrCg0GIdKAE8H-Y_1ntHoeke7l_21YpwqGDx3hFgIzFgmvQrhjPRPe37Rkj36Uc_ACOT1J88q9nDhr2XMqqP6KAovnFQ6Y4YzoV0DA0yVlw' \
--header 'Content-Type: application/json' \
--data-raw '{
    "data": {
        "etapa_processo_boleto": "efetivacao",
        "codigo_canal_operacao": "API",
        "beneficiario": {
            "id_beneficiario": "076400754345"
        },
        "dado_boleto": {
            "descricao_instrumento_cobranca": "boleto",
            "tipo_boleto": "a vista",
            "codigo_carteira": "109",
            "valor_total_titulo": "00000000000004100",
            "codigo_especie": "01",
            "valor_abatimento": "000",
            "data_emissao": "2022-10-28",
            "indicador_pagamento_parcial": false,
            "quantidade_maximo_parcial": 0,
            "pagador": {
                "pessoa": {
                    "nome_pessoa": "JHONLEMON BARBOSA RIBEIRO",
                    "tipo_pessoa": {
                        "codigo_tipo_pessoa": "F",
                        "numero_cadastro_pessoa_fisica": "28465238221"
                    }
                },
                "endereco": {
                    "nome_logradouro": "RUA 8, 84",
                    "nome_bairro": "LOTEAMENTO ARAGUAINA SUL",
                    "nome_cidade": "ARAGUAINA",
                    "sigla_UF": "TO",
                    "numero_CEP": "77827150"
                }
            },
            "dados_individuais_boleto": [{
                "numero_nosso_numero": "000000138",
                "data_vencimento": "2022-10-30",
                "valor_titulo": "00000000000004100",
                "texto_uso_beneficiario": "2",
                "texto_seu_numero": "LMC1000035"
            }],
            "multa": {
                "codigo_tipo_multa": "02",
                "quantidade_dias_multa": 1,
                "percentual_multa": "00000000000000200"
            },
            "juros": {
                "codigo_tipo_juros": 93,
                "quantidade_dias_juros": 1,
                "valor_juros": "00000000000000007"
            },
            "recebimento_divergente": {
                "codigo_tipo_autorizacao": "03"
            },
            "instrucao_cobranca": [
                {
                    "codigo_instrucao_cobranca": "4",
                    "quantidade_dias_apos_vencimento":60,
                    "dia_util":false
                }        
            ],  
            "protesto": {
                "protesto": 4,
                "quantidade_dias_protesto": 1
            },
            "negativacao": {
                 "negativacao": 5,
                 "quantidade_dias_negativacao": 1
             },
       
            "desconto_expresso": false
        }
    }
}
--cert CERTIFICADO_ITAU_ATUAL.crt \
--key CERTIFICADO_ITAU_ATUAL.key

Link to comment
Compartilhe em outros sites

Galera por fsavor estou quebrando a cabeça a dias com a integração do boleto itau porém não encontrei nem o endpoint que utliza para gerar o boleto, nem nada. Alguém pode me ajudar a pelo menos encontrar a documentação certa, pois ja li que é a mesma do pix mas não achei nada de endpoint ja li tmabém que é aquela Cash Manager mas só fala de ver detalhes do poagamento por boleto..

Link to comment
Compartilhe em outros sites

  • 2 weeks later...

Crie uma conta ou entre para comentar 😀

Você precisa ser um membro para deixar um comentário.

Crie a sua conta

Participe da nossa comunidade, crie sua conta.
É bem rápido!

Criar minha conta agora

Entrar

Você já tem uma conta?
Faça o login agora.

Entrar agora


×
×
  • Create New...