unit ACBrConsultaCPF;
interface
uses
SysUtils, Classes, ACBrSocket;
type
EACBrConsultaCPFException = class ( Exception );
{ TACBrConsultaCPF }
TACBrConsultaCPF = class(TACBrHTTP)
private
FNome: String;
FSituacao: String;
FCPF: String;
FDigitoVerificador: String;
FEmissao: String;
FCodCtrlControle: String;
FTokenCaptcha: String;
function VerificarErros(Str: String): String;
function LerCampo(Texto: TStringList; NomeCampo: String): String;
public
procedure Captcha(Stream: TStream);
function Consulta(const ACPF, DataNasc, ACaptcha: String;
ARemoverEspacosDuplos: Boolean = False): Boolean;
published
property CPF: String Read FCPF Write FCPF;
property Nome: String Read FNome;
property Situacao: String Read FSituacao;
property DigitoVerificador: String Read FDigitoVerificador;
property Emissao: String Read FEmissao;
property CodCtrlControle: String Read FCodCtrlControle;
end;
implementation
uses
ACBrUtil, ACBrValidador, synacode, synautil, strutils;
function StrEntreStr(Str, StrInicial, StrFinal: String; ComecarDe: Integer = 1): String;
var
Ini, Fim: Integer;
begin
Ini:= PosEx(StrInicial, Str, ComecarDe) + Length(StrInicial);
if Ini > 0 then
begin
Fim:= PosEx(StrFinal, Str, Ini);
if Fim > 0 then
Result:= Copy(Str, Ini, Fim - Ini)
else
Result:= '';
end
else
Result:= '';
end;
procedure TACBrConsultaCPF.Captcha(Stream: TStream);
var
Img64, ImgBin, DataClientID: AnsiString;
P: Integer;
begin
try
//DataClientID := '41ff278aba054a4cb14ab7a03d2f4c4d';
//HTTPPost('http://captcha2.servicoscorporativos.serpro.gov.br/captcha/1.0.0/imagem', DataClientID);
// HTTPGet('http://www.receita.fazenda.gov.br/Aplicacoes/ATCTA/CPF/captcha/gerarCaptcha.asp');
HTTPGet('https://www.receita.fazenda.gov.br/Aplicacoes/SSL/ATCTA/CPF/captcha/gerarCaptcha.asp');
if HTTPSend.ResultCode = 200 then
begin
(*
Img64 := RespHTTP.Text;
P := pos('@',Img64);
if P > 0 then
begin
FTokenCaptcha := copy(Img64,1,P-1);
Img64 := copy(Img64,P+1,Length(Img64)-Length(FTokenCaptcha)+2);
end
else
raise Exception.Create('');
ImgBin := DecodeBase64(Img64);
Stream.Write(Pointer(ImgBin)^,Length(ImgBin));
*)
HTTPSend.Document.Position := 0;
Stream.CopyFrom(HttpSend.Document, HttpSend.Document.Size);
Stream.Position := 0;
end;
Except
on E: Exception do begin
raise EACBrConsultaCPFException.Create('Erro na hora de fazer o download da imagem do captcha.'+#13#10+E.Message);
end;
end;
end;
function TACBrConsultaCPF.VerificarErros(Str: String): String;
var
Res: String;
begin
Res := '';
if Res = '' then
if Pos( ACBrStr('Os caracteres da imagem não foram preenchidos corretamente'), Str) > 0 then
Res := 'Os caracteres da imagem não foram preenchidos corretamente.';
if Res = '' then
if Pos(ACBrStr('O número do CPF não é válido. Verifique se o mesmo foi digitado corretamente.'), Str) > 0 then
Res := 'O número do CPF não é válido. Verifique se o mesmo foi digitado corretamente.';
if Res = '' then
if Pos(ACBrStr('Não existe no Cadastro de Pessoas Jurídicas o número de CPF informado. '+
'Verifique se o mesmo foi digitado corretamente.'), Str) > 0 then
Res := 'Não existe no Cadastro de Pessoas Jurídicas o número de CPF informado. '+
'Verifique se o mesmo foi digitado corretamente.';
if Res = '' then
if Pos(ACBrStr('a. No momento não podemos atender a sua solicitação. Por favor tente mais tarde.'), Str) > 0 then
Res := 'Erro no site da receita federal. Tente mais tarde.';
Result := ACBrStr(Res);
end;
function TACBrConsultaCPF.LerCampo(Texto : TStringList ; NomeCampo : String
) : String ;
var
i : integer;
linha : String;
begin
NomeCampo := ACBrStr(NomeCampo);
Result := '';
for i := 0 to Texto.Count-1 do
begin
linha := Texto;
if Pos(NomeCampo, linha) > 0 then
begin
Result := Trim(StringReplace(linha, NomeCampo, ' ',[rfReplaceAll]));
break;
end;
end
end;
function TACBrConsultaCPF.Consulta(const ACPF, DataNasc, ACaptcha: String;
ARemoverEspacosDuplos: Boolean): Boolean;
var
Post: TStringStream;
Erro: String;
Resposta : TStringList;
begin
Erro := ACBrValidadorValidarCPF( ACPF ) ;
if Erro <> '' then
raise EACBrConsultaCPFException.Create(Erro);
//txtCPF=11122334410&txtToken_captcha_serpro_gov_br=299218104152138191166941752496584741018616278361624164&txtTexto_captcha_serpro_gov_br=ZCI8B9&Enviar=Consultar
Post:= TStringStream.Create('');
try
//acredito que irão mudar esse tempTxtCPF, tempTxtNascimento, temptxtToken e temptxtTexto_captcha_serpro_gov_br para como era anteriormente
Post.WriteString('tempTxtCPF='+ACPF+'&');
Post.WriteString('tempTxtNascimento='+datanasc+'&');
Post.WriteString('temptxtToken_captcha_serpro_gov_br='+FTokenCaptcha+'&');
Post.WriteString('txtTexto_captcha_serpro_gov_br='+Trim(ACaptcha)+'&');
Post.WriteString('temptxtTexto_captcha_serpro_gov_br='+Trim(ACaptcha)+'&');
Post.WriteString('Enviar=Consultar');
Post.Position:= 0;
HttpSend.Clear;
HttpSend.Document.Position:= 0;
HttpSend.Document.CopyFrom(Post, Post.Size);
HTTPSend.MimeType := 'application/x-www-form-urlencoded';
// HTTPPost('http://www.receita.fazenda.gov.br/aplicacoes/atcta/cpf/ConsultaPublicaExibir.asp');
HTTPPost('https://www.receita.fazenda.gov.br/Aplicacoes/SSL/ATCTA/CPF/ConsultaPublicaExibir.asp');
Erro := VerificarErros(RespHTTP.Text);
if Erro = '' then
begin
Result:= True;
Resposta := TStringList.Create;
try
Resposta.Text := StripHTML(RespHTTP.Text);
RemoveEmptyLines( Resposta );
//DEBUG:
//Resposta.SaveToFile('C:\temp\cpf.txt');
FCPF := LerCampo(Resposta,'No do CPF:');
FNome := LerCampo(Resposta,'Nome da Pessoa Física:');
FSituacao := LerCampo(Resposta,'Situação Cadastral:');
FEmissao := LerCampo(Resposta,'Comprovante emitido às:');
FCodCtrlControle := LerCampo(Resposta,'Código de controle do comprovante:');
FDigitoVerificador := LerCampo(Resposta,'Digito Verificador:');
finally
Resposta.Free;
end ;
if Trim(FNome) = '' then
raise EACBrConsultaCPFException.Create('Não foi possível obter os dados.');
if ARemoverEspacosDuplos then
begin
FNome := RemoverEspacosDuplos(FNome);
end;
end
else
begin
Result:= False;
raise EACBrConsultaCPFException.Create(Erro);
end;
finally
Post.Free;
end;
end;
end.