PHP

Exemplos em PHP

Seis exemplos prontos para copiar, da primeira chamada ao tratamento de erros, com a certidão de exemplo hospedada (dados fictícios).

Antes de começar

Três passos, uma vez só.

  1. Crie uma chave de API

    No painel, em Chaves de API.

  2. Guarde a chave no ambiente

    Na variável DOCSOCR_API_KEY, que os exemplos leem. O exemplo de preços não precisa de chave.

  3. Salve e rode

    Salve cada exemplo com o nome que aparece sobre o código. As primeiras linhas dizem do que ele precisa para rodar.

Primeira chamada

Envia a certidão de exemplo hospedada (dados fictícios) e mostra o JSON da resposta.

first-call.php
<?php
// Your first call: extract the hosted sample certificate (fictitious data).
// Needs the curl extension and DOCSOCR_API_KEY in the environment.

$request = curl_init('https://api.docsocr.com/api/v1/documents/birth-certificate');
curl_setopt_array($request, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 120, // above the API's 90 s extraction budget
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('DOCSOCR_API_KEY'),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'imageType' => 'url',
        'imageUrl' => 'https://docsocr.com/samples/certidao-nascimento-exemplo.jpg',
        'requestId' => bin2hex(random_bytes(16)), // one id per document
    ]),
]);
$body = curl_exec($request);
if ($body === false) {
    fwrite(STDERR, curl_error($request) . PHP_EOL);
    exit(1);
}
$status = curl_getinfo($request, CURLINFO_RESPONSE_CODE);
$answer = json_decode($body, true);
if ($status !== 201 || empty($answer['success'])) {
    fwrite(STDERR, "$status " . ($answer['errorCode'] ?? '') . ' ' . implode('; ', (array) ($answer['message'] ?? $answer['error'] ?? '')) . PHP_EOL);
    exit(1);
}
echo $answer['data']['dados_pessoais']['nome_completo'], PHP_EOL;

Arquivo local em base64

Lê uma imagem do seu computador e a envia em base64, sem precisar de uma URL pública.

local-file.php
<?php
// Extract a certificate from a local file, sent in base64.
// Needs the curl extension and DOCSOCR_API_KEY in the environment.

$imageBase64 = base64_encode(file_get_contents('certificate.jpg'));

$request = curl_init('https://api.docsocr.com/api/v1/documents/birth-certificate');
curl_setopt_array($request, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 120, // above the API's 90 s extraction budget
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('DOCSOCR_API_KEY'),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'imageType' => 'base64',
        'imageBase64' => $imageBase64,
        'requestId' => bin2hex(random_bytes(16)), // one id per document
    ]),
]);
$body = curl_exec($request);
if ($body === false) {
    fwrite(STDERR, curl_error($request) . PHP_EOL);
    exit(1);
}
$status = curl_getinfo($request, CURLINFO_RESPONSE_CODE);
$answer = json_decode($body, true);
if ($status !== 201 || empty($answer['success'])) {
    fwrite(STDERR, "$status " . ($answer['errorCode'] ?? '') . ' ' . implode('; ', (array) ($answer['message'] ?? $answer['error'] ?? '')) . PHP_EOL);
    exit(1);
}
echo $answer['data']['dados_pessoais']['nome_completo'], PHP_EOL;

Imagem fora do padrão

Com resizeImage: true, uma imagem fora do nosso padrão de tamanho é redimensionada do nosso lado por 1 crédito a mais, em vez de recusada.

resize.php
<?php
// Extract an image outside our standard: resizeImage brings it to the
// standard first, for one extra credit (the 800x640 sample is too small).
// Needs the curl extension and DOCSOCR_API_KEY in the environment.

$request = curl_init('https://api.docsocr.com/api/v1/documents/birth-certificate');
curl_setopt_array($request, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 120, // above the API's 90 s extraction budget
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('DOCSOCR_API_KEY'),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'imageType' => 'url',
        'imageUrl' => 'https://docsocr.com/samples/certidao-nascimento-exemplo-800x640.jpg',
        'requestId' => bin2hex(random_bytes(16)), // one id per document
        'resizeImage' => true,
    ]),
]);
$body = curl_exec($request);
if ($body === false) {
    fwrite(STDERR, curl_error($request) . PHP_EOL);
    exit(1);
}
$status = curl_getinfo($request, CURLINFO_RESPONSE_CODE);
$answer = json_decode($body, true);
if ($status !== 201 || empty($answer['success'])) {
    fwrite(STDERR, "$status " . ($answer['errorCode'] ?? '') . ' ' . implode('; ', (array) ($answer['message'] ?? $answer['error'] ?? '')) . PHP_EOL);
    exit(1);
}
echo $answer['data']['dados_pessoais']['nome_completo'], PHP_EOL;
echo 'resized: ', var_export($answer['imageResized'] ?? false, true), ' credits: ', $answer['creditsCharged'], PHP_EOL;

Motor fast

Pede o motor fast: ele é tentado primeiro, pelo preço dele, e os motores padrão respondem quando ele não consegue. A resposta diz qual motor respondeu e quanto custou.

fast.php
<?php
// Ask for the fast engine: it is tried first, at its own price, and the
// standard engines follow when it cannot answer. The answer names the engine
// that answered and what it cost.
// Needs the curl extension and DOCSOCR_API_KEY in the environment.

$request = curl_init('https://api.docsocr.com/api/v1/documents/birth-certificate');
curl_setopt_array($request, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 120, // above the API's 90 s extraction budget
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('DOCSOCR_API_KEY'),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'imageType' => 'url',
        'imageUrl' => 'https://docsocr.com/samples/certidao-nascimento-exemplo.jpg',
        'requestId' => bin2hex(random_bytes(16)), // one id per document
        'engine' => 'fast',
    ]),
]);
$body = curl_exec($request);
if ($body === false) {
    fwrite(STDERR, curl_error($request) . PHP_EOL);
    exit(1);
}
$status = curl_getinfo($request, CURLINFO_RESPONSE_CODE);
$answer = json_decode($body, true);
if ($status !== 201 || empty($answer['success'])) {
    fwrite(STDERR, "$status " . ($answer['errorCode'] ?? '') . ' ' . implode('; ', (array) ($answer['message'] ?? $answer['error'] ?? '')) . PHP_EOL);
    exit(1);
}
echo 'engine: ', $answer['engine'], ' credits: ', $answer['creditsCharged'], PHP_EOL;

Erros e novas tentativas

Trata cada resposta e repete com o mesmo requestId: por 15 minutos, a repetição de uma requisição concluída recebe a mesma resposta, sem nova cobrança, e a de uma ainda em andamento recebe 409, para esperar.

errors.php
<?php
// Extract a certificate, handling every answer, with retries that never charge twice.
// Each retry sends the same requestId: a repeat of a finished request gets its
// kept answer at no charge, and a repeat of one still running is told to wait (409).
// Needs the curl extension and DOCSOCR_API_KEY in the environment.

const ENDPOINT = 'https://api.docsocr.com/api/v1/documents/birth-certificate';
// No engine could answer: nothing was charged, and a retry may succeed
const RETRY_LATER = ['EXTRACTION_BUSY', 'EXTRACTION_TIMEOUT', 'EXTRACTION_UNAVAILABLE'];
// Still in progress, too many requests, the service restarting
const RETRY_STATUS = [409, 429, 502, 503, 504];

function extractCertificate(string $imageUrl, int $attempts = 5): array
{
    $requestId = bin2hex(random_bytes(16)); // one id per document, the same on every retry
    for ($attempt = 0; $attempt < $attempts; $attempt++) {
        $backoff = 2 ** $attempt; // seconds: 1, 2, 4, 8
        $request = curl_init(ENDPOINT);
        curl_setopt_array($request, [
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 120, // above the API's 90 s extraction budget
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . getenv('DOCSOCR_API_KEY'),
                'Content-Type: application/json',
            ],
            CURLOPT_POSTFIELDS => json_encode(['imageType' => 'url', 'imageUrl' => $imageUrl, 'requestId' => $requestId]),
        ]);
        $body = curl_exec($request);
        if ($body === false) { // a timeout or a dropped connection
            sleep($backoff);
            continue;
        }
        $status = curl_getinfo($request, CURLINFO_RESPONSE_CODE);
        $answer = json_decode($body, true) ?? [];
        if ($status === 201 && !empty($answer['success'])) {
            return $answer;
        }
        // Wait as long as the answer asks (retryAfter); a limit that resets
        // later, such as a daily quota, is not worth waiting for
        $wait = (int) ($answer['retryAfter'] ?? $backoff);
        $retry = in_array($answer['errorCode'] ?? '', RETRY_LATER, true) || in_array($status, RETRY_STATUS, true);
        if ($retry && $wait <= 60) {
            sleep($wait);
            continue;
        }
        // 400 the body, 401 the key, 402 NOT_ENOUGH_CREDITS, 422 the image
        // (its errorCode says what to fix), DOCUMENT_NOT_RECOGNIZED: fix it, don't retry
        $message = implode('; ', (array) ($answer['message'] ?? $answer['error'] ?? ''));
        throw new RuntimeException("$status " . ($answer['errorCode'] ?? '') . " $message");
    }
    throw new RuntimeException('No answer after retries: try again later');
}

try {
    $answer = extractCertificate('https://docsocr.com/samples/certidao-nascimento-exemplo.jpg');
    echo $answer['data']['dados_pessoais']['nome_completo'], ' credits: ', $answer['creditsCharged'], PHP_EOL;
} catch (RuntimeException $error) {
    fwrite(STDERR, $error->getMessage() . PHP_EOL);
    exit(1);
}

Preços

Consulta o preço de uma extração em créditos, por motor e para o resizeImage. Não precisa de chave.

prices.php
<?php
// The price of an extraction, in credits, per engine and for resizeImage.
// A public endpoint: no key needed. Needs the curl extension.

$request = curl_init('https://api.docsocr.com/api/v1/documents/prices');
curl_setopt_array($request, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30]);
$body = curl_exec($request);
if ($body === false || curl_getinfo($request, CURLINFO_RESPONSE_CODE) !== 200) {
    fwrite(STDERR, 'The price list did not answer' . PHP_EOL);
    exit(1);
}
foreach (json_decode($body, true) as $name => $credits) {
    echo "$name: $credits credit(s)", PHP_EOL;
}

Pronto para começar?

Crie sua conta, receba créditos grátis e rode o primeiro exemplo com a sua chave.