Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //---Incluir as units DateUtils, IdHTTP, blcksock, IdGlobalProtocols, IdSSLOpenSSL, synautil, synsock, ssl_openssl, ssl_openssl_lib, ACBrDFeSSL, System.JSON,
- //-----------Processo de Conseguir o Code---------------------------------
- Baixe essa units que tem todo o processo de conseguir o code
- https://mega.nz/file/mpxlVCRA#ykFSFxuIiVlrjCaPdzjKIVVjhaDJIaM7Ie27HJMyD8o
- Baixe esse fontes que é um Demo de geração de boleto em homologação e produção
- https://mega.nz/file/So5g0aZA#HhmxioqT58ehaAxNVNQE7akVVPjiEyk-9LW3gtPDbO4
- //-----------Processo de Reflesh do Token-----------------------------------------
- procedure TF_boleto.Reflesh_Token;
- var sCaminhoLogo, BANCO_ABREVIADO, USUARIO:string;
- var sLocalPgto, TIPO_REGISTRO_BOLETO:string;
- var sTotalParcela : Integer;
- var refresh_token, expires_in, access_token :string;
- var Data_access_token : TDateTime;
- var
- SLRemessa: TStringList;
- i, j, HORA_RAFLASH_TOKEN, DIAS_RAFLASH_TOKEN: Integer;
- var
- HTTP: TIdHTTP;
- FParams : String;
- Json, scope, token_type: String;
- JsontoSend, AResponseContent : TStringStream;
- var
- LClient: TRESTClient;
- LRequest: TRESTRequest;
- LValue: string;
- begin
- refresh_token :='';
- Data_access_token :=0;
- HORA_RAFLASH_TOKEN :=0;
- 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]);
- 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]);
- 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]);
- if HORA_RAFLASH_TOKEN >= 1 then
- begin
- URL_SICOOB :='';
- if DM.TIPO_AMBIENTE_BOLETO = 'Homologação' then
- begin
- URL_SICOOB :='https://sandbox.sicoob.com.br/token';
- end
- else
- begin
- URL_SICOOB :='URL EM PRODUÇÃO';
- end;
- DIAS_RAFLASH_TOKEN :=0;
- DIAS_RAFLASH_TOKEN := DaysBetween(Data_access_token, DM.DATA_HORA);
- if DIAS_RAFLASH_TOKEN > 30 then
- begin
- //-------Gera novo token----------------------------------------------
- if not Assigned (F_sicoob) then
- begin
- F_sicoob:=TF_sicoob.Create(Self);
- end;
- F_sicoob.ShowModal;
- exit;
- end
- else
- begin
- //-----Atualiza o token----------------------------------------------
- LClient := TRESTClient.Create(self);
- LRequest := TRESTRequest.Create(self);
- LRequest.Client := LClient;
- LRequest.Method := TRESTRequestMethod.rmPOST;
- try
- LClient.BaseURL := URL_SICOOB;
- LRequest.AddParameter('client_id', DM.CLIENT_ID_SICOOB);
- LRequest.AddParameter('client_secret', DM.CLIENT_SECRET);
- LRequest.AddParameter('grant_type', 'refresh_token');
- LRequest.AddParameter('refresh_token', refresh_token);//---aqui usa o reflahs_token
- LRequest.Execute;
- if (LRequest.Response.StatusCode = 200) then
- begin
- if LRequest.Response.GetSimpleValue('access_token', LValue) then
- begin
- access_token :='';
- refresh_token :='';
- expires_in :='';
- access_token :=getCamposJsonString(LRequest.Response.JSONText, 'access_token');
- refresh_token :=getCamposJsonString(LRequest.Response.JSONText, 'refresh_token');
- expires_in :=getCamposJsonString(LRequest.Response.JSONText, 'expires_in');
- 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]);
- end
- else
- begin
- FreeAndNIL(LRequest);
- FreeAndNIL(LClient);
- if Application.MessageBox('Atenção...token não retornado na requisição','Sistema', MB_OK) = IDOK then
- exit;
- end;
- end
- else
- begin
- FreeAndNIL(LRequest);
- FreeAndNIL(LClient);
- ShowMessage('Atenção...Erro ao obter token: ' + LRequest.Response.JSONText);
- exit;
- end;
- Finally
- FreeAndNIL(LRequest);
- FreeAndNIL(LClient);
- end;
- end;
- end;
- end;
- procedure TF_boleto.EnviarBoletoSicoobApi;
- var sCAMINHGO_EXE, ArquivoJSON : String;
- var newFile, Arq_Liberacao : TextFile;
- var DATA_EXPIRACAO, VALIDA_DATA_EXPIRACAO, DATA_LIMITE, DATA_MULTA : TDateTime;
- var mURL, sResponse, mCode, AAuthBase64 : string;
- var
- HTTP: TIdHTTP;
- FParams, access_token : String;
- Json, scope, token_type, VALOR_JUROS, VALOR_MULTA, VALOR_PARCELA : String;
- JsontoSend, AResponseContent : TStringStream;
- var
- LClient: TRESTClient;
- LRequest: TRESTRequest;
- LValue: string;
- begin
- ERRO_SICOOB :='';
- ERRO_EXPCION_SICOOB :='';
- access_token :='';
- 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]);
- URL_SICOOB :='';
- if DM.TIPO_AMBIENTE_BOLETO = 'Homologação' then
- begin
- URL_SICOOB :='https://sandbox.sicoob.com.br/cobranca-bancaria/v1/boletos';
- end
- else
- begin
- URL_SICOOB :='URL EM PRODUÇÃO';
- end;
- //----Emissão do Boleto Online------------------------------------------------
- DATA_LIMITE :=0;
- DATA_MULTA :=0;
- VALOR_MULTA :='';
- VALOR_JUROS :='';
- VALOR_PARCELA :='';
- DATA_LIMITE :=DM.SQL_contas_receber_boletoDetalhe_Data_Vencimento.AsDateTime + 90;
- DATA_MULTA :=DM.SQL_contas_receber_boletoDetalhe_Data_Vencimento.AsDateTime + 5;
- VALOR_MULTA :=TrocaVirgulaPPonto(FormatFloat('#0.00', VALOR_MOURA_JUROS));
- VALOR_JUROS :=TrocaVirgulaPPonto((FormatFloat('#0.00', DM.SQL_contas_receber_boletoDetalhe_Valor_Falta.AsFloat * DM.SQL_busca_contaMULTA_DIA.AsFloat / 100)));
- VALOR_PARCELA :=TrocaVirgulaPPonto(FormatFloat('#0.00', DM.SQL_contas_receber_boletoDetalhe_Valor_Falta.AsFloat));
- Json :='[' + #13 +
- ' {' + #13 +
- ' "numeroContrato": '+ DM.SQL_busca_contaEmpresa_Convenio.AsString +',' + #13 +
- ' "modalidade": '+ DM.SQL_busca_contaCarteira.AsString +',' + #13 +
- ' "numeroContaCorrente": '+ DM.SQL_busca_contaEmpresa_Conta.AsString + DM.SQL_busca_contaEmpresa_Conta_Digito.AsString +',' + #13 +
- ' "especieDocumento": "DM",' + #13 +
- ' "dataEmissao": "'+ FormatDateTime('YYYY-MM-DD', DM.SQL_contas_receber_boletoDetalhe_Data_Emissao.AsDateTime) + 'T' + FormatDateTime('00:00:00', NOW) + '-03:00",' + #13 +
- ' "nossoNumero": ' + sNOSSO_NUMERO+ ',' + #13 +
- ' "seuNumero": "'+DM.SQL_contas_receber_boletoDetalhe_N_Documento.AsString+ '",' + #13 +
- ' "identificacaoBoletoEmpresa": "'+Copy(DM.SQL_contas_receber_boletoIdCliente.AsString, 1, 10)+ '",' + #13 +
- ' "identificacaoEmissaoBoleto": 2,' + #13 +
- ' "identificacaoDistribuicaoBoleto": 2,' + #13 +
- ' "valor": '+ VALOR_PARCELA +',' + #13 +
- ' "dataVencimento": "'+ FormatDateTime('YYYY-MM-DD', DM.SQL_contas_receber_boletoDetalhe_Data_Vencimento.AsDateTime) + 'T' + FormatDateTime('00:00:00', NOW) + '-03:00",' + #13 +
- ' "dataLimitePagamento": "'+ FormatDateTime('YYYY-MM-DD', DATA_LIMITE) + 'T' + FormatDateTime('00:00:00', NOW) + '-03:00",' + #13 +
- ' "valorAbatimento": 0,' + #13 +
- ' "tipoDesconto": 0,' + #13 +
- ' "dataPrimeiroDesconto": "",' + #13 +
- ' "valorPrimeiroDesconto": 0,' + #13 +
- ' "dataSegundoDesconto": "",' + #13 +
- ' "valorSegundoDesconto": 0,' + #13 +
- ' "dataTerceiroDesconto": "",' + #13 +
- ' "valorTerceiroDesconto": 0,' + #13 +
- ' "tipoMulta": 2,' + #13 +
- ' "dataMulta": "'+ FormatDateTime('YYYY-MM-DD', DATA_MULTA) + 'T' + FormatDateTime('00:00:00', NOW) + '-03:00",' + #13 +
- ' "valorMulta": '+VALOR_MULTA+',' + #13 +
- ' "tipoJurosMora": 2,' + #13 +
- ' "dataJurosMora": "'+ FormatDateTime('YYYY-MM-DD', DATA_MULTA) + 'T' + FormatDateTime('00:00:00', NOW) + '-03:00",' + #13 +
- ' "valorJurosMora": '+VALOR_JUROS+',' + #13 +
- ' "numeroParcela": '+ DM.SQL_contas_receber_boletoDetalhe_N_Parcela.Asstring+',' + #13 +
- ' "aceite": true,' + #13 +
- ' "codigoNegativacao": 3,' + #13 +
- ' "numeroDiasNegativacao": 0,' + #13 +
- ' "codigoProtesto": 3,' + #13 +
- ' "numeroDiasProtesto": 0,' + #13 +
- ' "pagador": {' + #13 +
- ' "numeroCpfCnpj": "'+DM.SQL_contas_receber_boletoCPF_CNPJ_Cliente.AsString+ '",' + #13 +
- ' "nome": "'+DM.SQL_contas_receber_boletoNomeRazaoSocial.AsString+ '",' + #13 +
- ' "endereco": "'+DM.SQL_contas_receber_boletoEndereco.AsString+ '",' + #13 +
- ' "bairro": "'+DM.SQL_contas_receber_boletoBairro.AsString+ '",' + #13 +
- ' "cidade": "'+DM.SQL_contas_receber_boletoCidade.AsString+ '",' + #13 +
- ' "cep": "'+ PegarNumeros(DM.SQL_contas_receber_boletoCep.AsString)+ '",' + #13 +
- ' "uf": "'+DM.SQL_contas_receber_boletoUF.AsString+ '",' + #13 +
- ' "email": [' + #13 +
- ' ""' + #13 +
- ' ]' + #13 +
- ' },' + #13 +
- ' "beneficiarioFinal": {' + #13 +
- ' "numeroCpfCnpj": "'+DM.SQL_contas_receber_boletoCPF_CNPJ_Cliente.AsString+ '",' + #13 +
- ' "nome": "'+DM.SQL_contas_receber_boletoNomeRazaoSocial.AsString+ '"' + #13 +
- ' },' + #13 +
- ' "mensagensInstrucao": {' + #13 +
- ' "tipoInstrucao": 1,' + #13 +
- ' "mensagens": [' + #13 +
- ' "Descrição da Instrução 1",' + #13 +
- ' "Descrição da Instrução 2",' + #13 +
- ' "Descrição da Instrução 3",' + #13 +
- ' "Descrição da Instrução 4",' + #13 +
- ' "Descrição da Instrução 5"' + #13 +
- ' ]' + #13 +
- ' },' + #13 +
- ' "gerarPdf": true' + #13 +
- ' }' + #13 +
- ']';
- {
- ArquivoJSON :='';
- ArquivoJSON := (Json);
- sCAMINHGO_EXE := (ExtractFilePath(ParamStr(0)) +'Boletos\LogsWebservice\');
- System.AssignFile(newFile, sCAMINHGO_EXE + Trim(DM.SQL_contas_receber_boletoDetalhe_N_Documento.AsString +'_sicoob_registro') + '.json');
- System.Rewrite(newFile);
- WriteLn(newFile, ArquivoJSON);
- System.CloseFile(newFile);
- }
- RESTClient2.Authenticator := nil;
- RESTClient2.BaseURL := URL_SICOOB;
- RESTRequest2.Method := TRESTRequestMethod.rmPOST;
- //----Correção no problema de envio de mais um boleto-----------------------
- RESTRequest2.Params.Create(Self);
- RESTRequest2.Params.AddItem;
- RESTRequest2.Params.Items[0].name :='Authorization';
- RESTRequest2.Params.Items[0].Value :='Bearer a84d4964-65cd-3197-968d-a760b0741308';
- RESTRequest2.Params.Items[0].ContentType :=ctNone;
- RESTRequest2.Params.Items[0].Kind :=TRESTRequestParameterKind.pkHTTPHEADER;
- RESTRequest2.Params.Items[0].Options := [poDoNotEncode];
- RESTRequest2.Params.AddItem;
- RESTRequest2.Params.Items[1].name :='Client_id';
- RESTRequest2.Params.Items[1].Value :='9DyjkpZXycHHoe5OfOi57PLVBh4a';
- RESTRequest2.Params.Items[1].ContentType :=ctNone;
- RESTRequest2.Params.Items[1].Kind :=TRESTRequestParameterKind.pkHTTPHEADER;
- RESTRequest2.Params.Items[1].Options := [];
- RESTRequest2.Params.AddItem;
- RESTRequest2.Params.Items[2].name :='Accept-Charset';
- RESTRequest2.Params.Items[2].Value :='utf-8';
- RESTRequest2.Params.Items[2].ContentType :=ctNone;
- RESTRequest2.Params.Items[2].Kind :=TRESTRequestParameterKind.pkHTTPHEADER;
- RESTRequest2.Params.Items[2].Options := [];
- RESTRequest2.Params.AddItem;
- RESTRequest2.Params.Items[3].name :='body';
- RESTRequest2.Params.Items[3].Value :='';
- RESTRequest2.Params.Items[3].ContentType :=ctAPPLICATION_JSON;
- RESTRequest2.Params.Items[3].Kind :=TRESTRequestParameterKind.pkREQUESTBODY;
- RESTRequest2.Params.Items[3].Options := [poDoNotEncode];
- RESTRequest2.AddParameter('Content-type', 'application/json', pkHTTPHEADER);
- RESTRequest2.AddParameter('Authorization', 'Bearer ' + access_token, pkHTTPHEADER, [TRESTRequestParameterOption.poDoNotEncode]);
- RESTRequest2.AddParameter('client_id', DM.CLIENT_ID_SICOOB, pkHTTPHEADER);
- RESTRequest2.AddBody(Json);//----json do boleto-------------------------------
- RESTRequest2.Execute;
- if RESTResponse2.StatusCode = 207 then
- begin
- LINHA_DIGITAVEL :='';
- LINHA_DIGITAVEL :=Copy(RESTResponse2.JSONText, Pos('"linhaDigitavel": "', RESTResponse2.JSONText) + 19, Length(RESTResponse2.JSONText));
- LINHA_DIGITAVEL :=Copy(LINHA_DIGITAVEL, 1, 47);
- XMLTemporario.Append;
- XMLTemporarioNossoNumero.AsString :=LINHA_DIGITAVEL;
- if Length(LINHA_DIGITAVEL) > 60 then
- begin
- XMLTemporarioStatus.AsString :='OK';
- XMLTemporarioObs.AsString :='Boleto Registrado com Sucesso';
- end
- else
- begin
- XMLTemporarioStatus.AsString :='ERRO';
- XMLTemporarioObs.AsString :='Erro ao Registrar Boleto via API';
- ERRO_SICOOB :='SIM';
- end;
- XMLTemporarioNumeroDocumento.AsString :=NR_DOCUMENTO;
- XMLTemporarioParcela.AsInteger :=NR_PARCELA;
- XMLTemporario.Post;
- XMLTemporario.Close;
- XMLTemporario.Open;
- //--------------------------------------------------------------------------
- end
- else
- begin
- ERRO_SICOOB :='SIM';
- end;
- ArquivoJSON :='';
- ArquivoJSON := (RESTResponse2.JSONText);
- sCAMINHGO_EXE := (ExtractFilePath(ParamStr(0)) +'Boletos\LogsWebservice\');
- System.AssignFile(newFile, sCAMINHGO_EXE + Trim(DM.SQL_contas_receber_boletoDetalhe_N_Documento.AsString +'_sicoob_registro') + '.json');
- System.Rewrite(newFile);
- WriteLn(newFile, ArquivoJSON);
- System.CloseFile(newFile);
- end;
Add Comment
Please, Sign In to add comment