JhonlenonRibeiro

Boleto_Sicoob

Dec 23rd, 2021
667
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 14.75 KB | None | 0 0
  1. //---Incluir as units  DateUtils, IdHTTP, blcksock, IdGlobalProtocols, IdSSLOpenSSL, synautil, synsock, ssl_openssl, ssl_openssl_lib, ACBrDFeSSL, System.JSON,
  2.  
  3. //-----------Processo de Conseguir o Code---------------------------------
  4. Baixe essa units que tem todo o processo de conseguir o code
  5. https://mega.nz/file/mpxlVCRA#ykFSFxuIiVlrjCaPdzjKIVVjhaDJIaM7Ie27HJMyD8o
  6.  
  7. Baixe esse fontes que é um Demo de geração de boleto em homologação e produção
  8. https://mega.nz/file/So5g0aZA#HhmxioqT58ehaAxNVNQE7akVVPjiEyk-9LW3gtPDbO4
  9.  
  10. //-----------Processo de Reflesh do Token-----------------------------------------
  11. procedure TF_boleto.Reflesh_Token;
  12.  var  sCaminhoLogo, BANCO_ABREVIADO, USUARIO:string;
  13.  var  sLocalPgto, TIPO_REGISTRO_BOLETO:string;
  14.  var sTotalParcela : Integer;
  15.  var refresh_token, expires_in, access_token  :string;
  16.  var Data_access_token : TDateTime;
  17.  var
  18.  SLRemessa: TStringList;
  19.  i, j,  HORA_RAFLASH_TOKEN, DIAS_RAFLASH_TOKEN: Integer;
  20.  var
  21.  HTTP: TIdHTTP;
  22.  FParams : String;
  23.  Json, scope, token_type: String;
  24.  JsontoSend, AResponseContent : TStringStream;
  25.  var
  26.   LClient: TRESTClient;
  27.   LRequest: TRESTRequest;
  28.   LValue: string;
  29. begin
  30. refresh_token           :='';
  31.     Data_access_token       :=0;
  32.     HORA_RAFLASH_TOKEN      :=0;
  33.     refresh_token           :=DM.conecta.ExecSQLScalar('select IFNULL(refresh_token, "") AS refresh_token from configuracao_boleto where Codigo_Config_Boleto =:BANCO and CodLoja_Boleto =:COD_LOJA', [DM.COD_BANCO, DM.COD_LOJA]);
  34.     Data_access_token       :=DM.conecta.ExecSQLScalar('select Data_access_token AS Data_access_token from configuracao_boleto where Codigo_Config_Boleto =:BANCO and CodLoja_Boleto =:COD_LOJA', [DM.COD_BANCO, DM.COD_LOJA]);
  35.     HORA_RAFLASH_TOKEN      :=DM.conecta.ExecSQLScalar('SELECT IFNULL(TIMESTAMPDIFF (HOUR,Data_refresh_token,NOW()),1) AS QTD_Horas FROM configuracao_boleto where Codigo_Config_Boleto =:BANCO and CodLoja_Boleto =:COD_LOJA', [DM.COD_BANCO, DM.COD_LOJA]);
  36.     if HORA_RAFLASH_TOKEN >= 1 then
  37.     begin
  38.        URL_SICOOB    :='';
  39.        if DM.TIPO_AMBIENTE_BOLETO = 'Homologação' then
  40.        begin
  41.          URL_SICOOB  :='https://sandbox.sicoob.com.br/token';
  42.        end
  43.        else
  44.        begin
  45.          URL_SICOOB  :='URL EM PRODUÇÃO';
  46.        end;
  47.  
  48.        DIAS_RAFLASH_TOKEN :=0;
  49.        DIAS_RAFLASH_TOKEN := DaysBetween(Data_access_token, DM.DATA_HORA);
  50.        if DIAS_RAFLASH_TOKEN > 30 then
  51.        begin
  52.           //-------Gera novo token----------------------------------------------
  53.           if not Assigned (F_sicoob) then
  54.           begin
  55.             F_sicoob:=TF_sicoob.Create(Self);
  56.           end;
  57.           F_sicoob.ShowModal;
  58.           exit;
  59.        end
  60.        else
  61.        begin
  62.            //-----Atualiza o token----------------------------------------------
  63.           LClient := TRESTClient.Create(self);
  64.           LRequest := TRESTRequest.Create(self);
  65.           LRequest.Client := LClient;
  66.           LRequest.Method := TRESTRequestMethod.rmPOST;
  67.           try
  68.              LClient.BaseURL := URL_SICOOB;
  69.              LRequest.AddParameter('client_id', DM.CLIENT_ID_SICOOB);
  70.              LRequest.AddParameter('client_secret', DM.CLIENT_SECRET);
  71.              LRequest.AddParameter('grant_type', 'refresh_token');
  72.              LRequest.AddParameter('refresh_token', refresh_token);//---aqui usa o reflahs_token
  73.              LRequest.Execute;
  74.              if (LRequest.Response.StatusCode = 200) then
  75.              begin
  76.                 if LRequest.Response.GetSimpleValue('access_token', LValue) then
  77.                 begin
  78.                   access_token  :='';
  79.                   refresh_token :='';
  80.                   expires_in    :='';
  81.                   access_token  :=getCamposJsonString(LRequest.Response.JSONText, 'access_token');
  82.                   refresh_token :=getCamposJsonString(LRequest.Response.JSONText, 'refresh_token');
  83.                   expires_in    :=getCamposJsonString(LRequest.Response.JSONText, 'expires_in');
  84.                   DM.conecta.ExecSQL('update configuracao_boleto set access_token =:TOKEN, refresh_token =:REFRESH, expires_in =:EXPIRA, Data_refresh_token =NOW() where Codigo_Config_Boleto =:BANCO and CodLoja_Boleto =:COD_LOJA', [access_token, refresh_token, StrToInt(expires_in), DM.COD_BANCO, DM.COD_LOJA]);
  85.                 end
  86.                 else
  87.                 begin
  88.                   FreeAndNIL(LRequest);
  89.                   FreeAndNIL(LClient);
  90.                   if Application.MessageBox('Atenção...token não retornado na requisição','Sistema', MB_OK) = IDOK then
  91.                   exit;
  92.                 end;
  93.              end
  94.               else
  95.              begin
  96.                FreeAndNIL(LRequest);
  97.                FreeAndNIL(LClient);
  98.                ShowMessage('Atenção...Erro ao obter token: ' + LRequest.Response.JSONText);
  99.                exit;
  100.              end;
  101.           Finally
  102.             FreeAndNIL(LRequest);
  103.             FreeAndNIL(LClient);
  104.           end;
  105.        end;
  106.     end;
  107. end;
  108. procedure TF_boleto.EnviarBoletoSicoobApi;
  109. var sCAMINHGO_EXE, ArquivoJSON : String;
  110. var newFile, Arq_Liberacao : TextFile;
  111. var DATA_EXPIRACAO, VALIDA_DATA_EXPIRACAO, DATA_LIMITE, DATA_MULTA : TDateTime;
  112. var mURL, sResponse, mCode, AAuthBase64 : string;
  113. var
  114.  HTTP: TIdHTTP;
  115.  FParams, access_token : String;
  116.  Json, scope, token_type, VALOR_JUROS, VALOR_MULTA, VALOR_PARCELA  : String;
  117.  JsontoSend, AResponseContent : TStringStream;
  118. var
  119.  LClient: TRESTClient;
  120.  LRequest: TRESTRequest;
  121.  LValue: string;
  122. begin
  123.  ERRO_SICOOB         :='';
  124.   ERRO_EXPCION_SICOOB :='';
  125.   access_token        :='';
  126.   access_token        :=DM.conecta.ExecSQLScalar('select IFNULL(access_token, "") AS access_token from configuracao_boleto where Codigo_Config_Boleto =:BANCO and CodLoja_Boleto =:COD_LOJA', [DM.COD_BANCO, DM.COD_LOJA]);
  127.   URL_SICOOB    :='';
  128.   if DM.TIPO_AMBIENTE_BOLETO = 'Homologação' then
  129.   begin
  130.     URL_SICOOB  :='https://sandbox.sicoob.com.br/cobranca-bancaria/v1/boletos';
  131.   end
  132.   else
  133.   begin
  134.     URL_SICOOB  :='URL EM PRODUÇÃO';
  135.   end;
  136.   //----Emissão do Boleto Online------------------------------------------------
  137.   DATA_LIMITE    :=0;
  138.   DATA_MULTA     :=0;
  139.   VALOR_MULTA    :='';
  140.   VALOR_JUROS    :='';
  141.   VALOR_PARCELA  :='';
  142.   DATA_LIMITE    :=DM.SQL_contas_receber_boletoDetalhe_Data_Vencimento.AsDateTime + 90;
  143.   DATA_MULTA     :=DM.SQL_contas_receber_boletoDetalhe_Data_Vencimento.AsDateTime + 5;
  144.   VALOR_MULTA    :=TrocaVirgulaPPonto(FormatFloat('#0.00', VALOR_MOURA_JUROS));
  145.   VALOR_JUROS    :=TrocaVirgulaPPonto((FormatFloat('#0.00', DM.SQL_contas_receber_boletoDetalhe_Valor_Falta.AsFloat * DM.SQL_busca_contaMULTA_DIA.AsFloat / 100)));
  146.   VALOR_PARCELA  :=TrocaVirgulaPPonto(FormatFloat('#0.00', DM.SQL_contas_receber_boletoDetalhe_Valor_Falta.AsFloat));
  147.   Json :='[' + #13 +
  148.         '  {' + #13 +
  149.         '    "numeroContrato": '+ DM.SQL_busca_contaEmpresa_Convenio.AsString +',' + #13 +
  150.         '    "modalidade": '+ DM.SQL_busca_contaCarteira.AsString +',' + #13 +
  151.         '    "numeroContaCorrente": '+ DM.SQL_busca_contaEmpresa_Conta.AsString + DM.SQL_busca_contaEmpresa_Conta_Digito.AsString +','  + #13 +
  152.         '    "especieDocumento": "DM",' + #13 +
  153.         '    "dataEmissao": "'+ FormatDateTime('YYYY-MM-DD', DM.SQL_contas_receber_boletoDetalhe_Data_Emissao.AsDateTime) + 'T' + FormatDateTime('00:00:00', NOW) + '-03:00",' + #13 +
  154.         '    "nossoNumero": ' + sNOSSO_NUMERO+ ',' + #13 +
  155.         '    "seuNumero": "'+DM.SQL_contas_receber_boletoDetalhe_N_Documento.AsString+ '",' + #13 +
  156.         '    "identificacaoBoletoEmpresa": "'+Copy(DM.SQL_contas_receber_boletoIdCliente.AsString, 1, 10)+ '",' + #13 +
  157.         '    "identificacaoEmissaoBoleto": 2,' + #13 +
  158.         '    "identificacaoDistribuicaoBoleto": 2,' + #13 +
  159.         '    "valor": '+ VALOR_PARCELA +',' + #13 +
  160.         '    "dataVencimento": "'+ FormatDateTime('YYYY-MM-DD', DM.SQL_contas_receber_boletoDetalhe_Data_Vencimento.AsDateTime) + 'T' + FormatDateTime('00:00:00', NOW) + '-03:00",' + #13 +
  161.         '    "dataLimitePagamento": "'+ FormatDateTime('YYYY-MM-DD', DATA_LIMITE) + 'T' + FormatDateTime('00:00:00', NOW) + '-03:00",' + #13 +
  162.         '    "valorAbatimento": 0,' + #13 +
  163.         '    "tipoDesconto": 0,' + #13 +
  164.         '    "dataPrimeiroDesconto": "",' + #13 +
  165.         '    "valorPrimeiroDesconto": 0,' + #13 +
  166.         '    "dataSegundoDesconto": "",' + #13 +
  167.         '    "valorSegundoDesconto": 0,' + #13 +
  168.         '    "dataTerceiroDesconto": "",' + #13 +
  169.         '    "valorTerceiroDesconto": 0,' + #13 +
  170.         '    "tipoMulta": 2,' + #13 +
  171.         '    "dataMulta": "'+ FormatDateTime('YYYY-MM-DD', DATA_MULTA) + 'T' + FormatDateTime('00:00:00', NOW) + '-03:00",' + #13 +
  172.         '    "valorMulta": '+VALOR_MULTA+',' + #13 +
  173.         '    "tipoJurosMora": 2,' + #13 +
  174.         '    "dataJurosMora": "'+ FormatDateTime('YYYY-MM-DD', DATA_MULTA) + 'T' + FormatDateTime('00:00:00', NOW) + '-03:00",' + #13 +
  175.         '    "valorJurosMora": '+VALOR_JUROS+',' + #13 +
  176.         '    "numeroParcela": '+ DM.SQL_contas_receber_boletoDetalhe_N_Parcela.Asstring+',' + #13 +
  177.         '    "aceite": true,' + #13 +
  178.         '    "codigoNegativacao": 3,' + #13 +
  179.         '    "numeroDiasNegativacao": 0,' + #13 +
  180.         '    "codigoProtesto": 3,' + #13 +
  181.         '    "numeroDiasProtesto": 0,' + #13 +
  182.         '    "pagador": {' + #13 +
  183.         '      "numeroCpfCnpj": "'+DM.SQL_contas_receber_boletoCPF_CNPJ_Cliente.AsString+ '",' + #13 +
  184.         '      "nome": "'+DM.SQL_contas_receber_boletoNomeRazaoSocial.AsString+ '",' + #13 +
  185.         '      "endereco": "'+DM.SQL_contas_receber_boletoEndereco.AsString+ '",' + #13 +
  186.         '      "bairro": "'+DM.SQL_contas_receber_boletoBairro.AsString+ '",' + #13 +
  187.         '      "cidade": "'+DM.SQL_contas_receber_boletoCidade.AsString+ '",' + #13 +
  188.         '      "cep": "'+ PegarNumeros(DM.SQL_contas_receber_boletoCep.AsString)+ '",' + #13 +
  189.         '      "uf": "'+DM.SQL_contas_receber_boletoUF.AsString+ '",' + #13 +
  190.         '      "email": [' + #13 +
  191.         '        ""' + #13 +
  192.         '      ]' + #13 +
  193.         '    },' + #13 +
  194.         '    "beneficiarioFinal": {' + #13 +
  195.         '      "numeroCpfCnpj": "'+DM.SQL_contas_receber_boletoCPF_CNPJ_Cliente.AsString+ '",' + #13 +
  196.         '      "nome": "'+DM.SQL_contas_receber_boletoNomeRazaoSocial.AsString+ '"' + #13 +
  197.         '    },' + #13 +
  198.         '    "mensagensInstrucao": {' + #13 +
  199.         '      "tipoInstrucao": 1,' + #13 +
  200.         '      "mensagens": [' + #13 +
  201.         '        "Descrição da Instrução 1",' + #13 +
  202.         '        "Descrição da Instrução 2",' + #13 +
  203.         '        "Descrição da Instrução 3",' + #13 +
  204.         '        "Descrição da Instrução 4",' + #13 +
  205.         '        "Descrição da Instrução 5"' + #13 +
  206.         '      ]' + #13 +
  207.         '    },' + #13 +
  208.         '    "gerarPdf": true' + #13 +
  209.         '  }' + #13 +
  210.         ']';
  211.   {
  212.   ArquivoJSON    :='';
  213.   ArquivoJSON    := (Json);
  214.   sCAMINHGO_EXE  := (ExtractFilePath(ParamStr(0)) +'Boletos\LogsWebservice\');
  215.   System.AssignFile(newFile, sCAMINHGO_EXE + Trim(DM.SQL_contas_receber_boletoDetalhe_N_Documento.AsString +'_sicoob_registro') + '.json');
  216.   System.Rewrite(newFile);
  217.   WriteLn(newFile, ArquivoJSON);
  218.   System.CloseFile(newFile);
  219.   }
  220.   RESTClient2.Authenticator := nil;
  221.   RESTClient2.BaseURL := URL_SICOOB;
  222.   RESTRequest2.Method := TRESTRequestMethod.rmPOST;
  223.   //----Correção no problema de envio de mais um boleto-----------------------
  224.   RESTRequest2.Params.Create(Self);
  225.   RESTRequest2.Params.AddItem;
  226.   RESTRequest2.Params.Items[0].name        :='Authorization';
  227.   RESTRequest2.Params.Items[0].Value       :='Bearer a84d4964-65cd-3197-968d-a760b0741308';
  228.   RESTRequest2.Params.Items[0].ContentType :=ctNone;
  229.   RESTRequest2.Params.Items[0].Kind        :=TRESTRequestParameterKind.pkHTTPHEADER;
  230.   RESTRequest2.Params.Items[0].Options     := [poDoNotEncode];
  231.  
  232.   RESTRequest2.Params.AddItem;
  233.   RESTRequest2.Params.Items[1].name        :='Client_id';
  234.   RESTRequest2.Params.Items[1].Value       :='9DyjkpZXycHHoe5OfOi57PLVBh4a';
  235.   RESTRequest2.Params.Items[1].ContentType :=ctNone;
  236.   RESTRequest2.Params.Items[1].Kind        :=TRESTRequestParameterKind.pkHTTPHEADER;
  237.   RESTRequest2.Params.Items[1].Options     := [];
  238.  
  239.   RESTRequest2.Params.AddItem;
  240.   RESTRequest2.Params.Items[2].name        :='Accept-Charset';
  241.   RESTRequest2.Params.Items[2].Value       :='utf-8';
  242.   RESTRequest2.Params.Items[2].ContentType :=ctNone;
  243.   RESTRequest2.Params.Items[2].Kind        :=TRESTRequestParameterKind.pkHTTPHEADER;
  244.   RESTRequest2.Params.Items[2].Options     := [];
  245.  
  246.   RESTRequest2.Params.AddItem;
  247.   RESTRequest2.Params.Items[3].name        :='body';
  248.   RESTRequest2.Params.Items[3].Value       :='';
  249.   RESTRequest2.Params.Items[3].ContentType :=ctAPPLICATION_JSON;
  250.   RESTRequest2.Params.Items[3].Kind        :=TRESTRequestParameterKind.pkREQUESTBODY;
  251.   RESTRequest2.Params.Items[3].Options     := [poDoNotEncode];
  252.  
  253.   RESTRequest2.AddParameter('Content-type', 'application/json', pkHTTPHEADER);
  254.   RESTRequest2.AddParameter('Authorization', 'Bearer ' + access_token, pkHTTPHEADER, [TRESTRequestParameterOption.poDoNotEncode]);
  255.   RESTRequest2.AddParameter('client_id', DM.CLIENT_ID_SICOOB, pkHTTPHEADER);
  256.   RESTRequest2.AddBody(Json);//----json do boleto-------------------------------
  257.   RESTRequest2.Execute;
  258.   if RESTResponse2.StatusCode = 207 then
  259.   begin
  260.     LINHA_DIGITAVEL                       :='';
  261.     LINHA_DIGITAVEL                       :=Copy(RESTResponse2.JSONText, Pos('"linhaDigitavel": "', RESTResponse2.JSONText) + 19, Length(RESTResponse2.JSONText));
  262.     LINHA_DIGITAVEL                       :=Copy(LINHA_DIGITAVEL, 1, 47);
  263.  
  264.     XMLTemporario.Append;
  265.     XMLTemporarioNossoNumero.AsString     :=LINHA_DIGITAVEL;
  266.     if Length(LINHA_DIGITAVEL) > 60 then
  267.     begin
  268.       XMLTemporarioStatus.AsString        :='OK';
  269.       XMLTemporarioObs.AsString           :='Boleto Registrado com Sucesso';
  270.     end
  271.     else
  272.     begin
  273.       XMLTemporarioStatus.AsString        :='ERRO';
  274.       XMLTemporarioObs.AsString           :='Erro ao Registrar Boleto via API';
  275.       ERRO_SICOOB                         :='SIM';
  276.     end;
  277.     XMLTemporarioNumeroDocumento.AsString :=NR_DOCUMENTO;
  278.     XMLTemporarioParcela.AsInteger        :=NR_PARCELA;
  279.     XMLTemporario.Post;
  280.     XMLTemporario.Close;
  281.     XMLTemporario.Open;
  282.     //--------------------------------------------------------------------------
  283.   end
  284.   else
  285.   begin
  286.      ERRO_SICOOB  :='SIM';
  287.   end;
  288.   ArquivoJSON    :='';
  289.   ArquivoJSON    := (RESTResponse2.JSONText);
  290.   sCAMINHGO_EXE  := (ExtractFilePath(ParamStr(0)) +'Boletos\LogsWebservice\');
  291.   System.AssignFile(newFile, sCAMINHGO_EXE + Trim(DM.SQL_contas_receber_boletoDetalhe_N_Documento.AsString +'_sicoob_registro') + '.json');
  292.   System.Rewrite(newFile);
  293.   WriteLn(newFile, ArquivoJSON);
  294.   System.CloseFile(newFile);
  295. end;
Add Comment
Please, Sign In to add comment