SDK PHP
SDK oficial para PHP 8.0+ com tipagem estrita, tratamento de exceções e suporte a PSR-18.
Instalação
bash
composer require cpfhub/cpfhub-phpRequerimentos: PHP 8.0+, ext-json
Inicialização
PHP
use CPFHub\Client;
$client = new Client(
apiKey: $_ENV['CPFHUB_API_KEY'],
// timeout: 10, // opcional, padrão: 10 segundos
);Parâmetros do construtor
| Parâmetro | Tipo | Padrão | Descrição |
|---|---|---|---|
apiKey | string | - | Sua API Key (obrigatório) |
timeout | int | 10 | Timeout em segundos |
baseUrl | string | https://api.cpfhub.io | URL base da API |
Métodos
$client->lookup(string $cpf)
Consulta um CPF e retorna os dados de identidade.
PHP
$result = $client->lookup('12345678909');
echo $result->data->name; // "João da Silva"
echo $result->data->gender; // "M"Retorno: CPFHubResult
PHP
class CPFHubResult {
public bool $success;
public CPFData $data;
}
class CPFData {
public string $cpf;
public string $name;
public string $nameUpper;
public string $gender; // "M" | "F"
public string $birthDate; // "DD/MM/AAAA"
public int $day;
public int $month;
public int $year;
}Tratamento de erros
PHP
use CPFHub\Client;
use CPFHub\Exceptions\CPFHubException;
$client = new Client(apiKey: $_ENV['CPFHUB_API_KEY']);
try {
$result = $client->lookup('12345678909');
} catch (CPFHubException $e) {
echo $e->getCode(); // "CPF_NOT_FOUND"
echo $e->getMessage(); // "CPF not found in our database"
echo $e->getStatusCode(); // 404
}Códigos de erro
$e->getCode() | $e->getStatusCode() | Descrição |
|---|---|---|
CPF_NOT_FOUND | 404 | CPF não encontrado (sem consumo de crédito) |
INVALID_CPF_FORMAT | 400 | Formato inválido |
INVALID_CPF_DIGITS | 422 | Dígitos verificadores inválidos |
MISSING_API_KEY | 401 | API Key ausente |
INVALID_API_KEY | 401 | API Key inválida |
RATE_LIMIT_EXCEEDED | 429 | Limite de taxa excedido |
INSUFFICIENT_CREDITS | 403 | Sem créditos disponíveis |
Exemplos de integração
Laravel - Controller
PHP
namespace App\Http\Controllers;
use CPFHub\Client;
use CPFHub\Exceptions\CPFHubException;
use Illuminate\Http\JsonResponse;
class CPFController extends Controller
{
private Client $cpfhub;
public function __construct()
{
$this->cpfhub = new Client(apiKey: config('services.cpfhub.key'));
}
public function show(string $cpf): JsonResponse
{
try {
$result = $this->cpfhub->lookup($cpf);
return response()->json($result->data);
} catch (CPFHubException $e) {
return response()->json(['error' => $e->getCode()], $e->getStatusCode());
}
}
}Validação de CPF em formulário Laravel
PHP
// app/Rules/CPFValido.php
namespace App\Rules;
use CPFHub\Client;
use CPFHub\Exceptions\CPFHubException;
use Illuminate\Contracts\Validation\Rule;
class CPFValido implements Rule
{
public function passes($attribute, $value): bool
{
$client = new Client(apiKey: config('services.cpfhub.key'));
try {
$client->lookup($value);
return true;
} catch (CPFHubException $e) {
return false;
}
}
public function message(): string
{
return 'O CPF informado não foi encontrado.';
}
}Repositório e suporte
- github.com/cpfhub/cpfhub-php - código-fonte, issues e contribuições
- Packagist: cpfhub/cpfhub-php - versões e changelog
Atualizado em 12 de maio de 2026