PHP code example of noclick11 / click-nfse

1. Go to this page and download the library: Download noclick11/click-nfse library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

noclick11 / click-nfse example snippets


use Carbon\CarbonInterface;
use ClickNfse\Contracts\Faturavel;
use ClickNfse\Contracts\Tomador;
use Illuminate\Database\Eloquent\Model;

class Pagamento extends Model implements Faturavel
{
    public function nfseValorEmCentavos(): int          { return $this->valor; }
    public function nfseCodigoServico(): ?string        { return '010301'; }   // cTribNac
    public function nfseDescricaoServico(): ?string     { return 'Consultoria em TI'; }
    public function nfseCompetencia(): CarbonInterface  { return $this->pago_em; }
    public function nfseReferenciaExterna(): ?string    { return $this->gateway_id; }
    public function nfseTomador(): ?Tomador             { return $this->cliente; }
    public function nfseEstaPago(): bool                { return $this->status === 'pago'; }
    public function nfseEstaEstornado(): bool           { return (bool) $this->estornado; }
}

class Cliente extends Model implements Tomador
{
    public function nfseDocumento(): ?string { return $this->cpf ?? $this->cnpj; }
    public function nfseNome(): ?string      { return $this->nome; }
    public function nfseEmail(): ?string     { return $this->email; }
}

use ClickNfse\Jobs\EmitirNfseJob;

EmitirNfseJob::dispatch($pagamento);

use ClickNfse\Services\NfseEmissaoService;

$emissao = app(NfseEmissaoService::class);

$nota = $emissao->prepararNota($pagamento);   // idempotente
$nota = $emissao->emitir($nota);

$nota->status;             // AUTORIZADA, REJEITADA, ...
$nota->chave_acesso;       // 50 dígitos
$nota->numero_nfse;
$nota->erros;              // [{codigo, descricao, complemento}] devolvidos pela Sefin
$nota->nfse_xml;           // XML autorizado — o documento com valor legal
$nota->faturavel;          // de volta ao seu domínio

use ClickNfse\Jobs\CancelarNfseJob;
use ClickNfse\Models\NotaFiscal;

CancelarNfseJob::dispatch($nota, NotaFiscal::MOTIVO_SERVICO_NAO_PRESTADO, 'Estorno do pagamento');

$nota->erro_mensagem;  // "Tomador sem CPF/CNPJ válido cadastrado: ..."

// Depois de corrigir o cadastro:
app(NfseEmissaoService::class)->emitirInapta($nota);

$dados = app(DanfseService::class)->dadosParaView($nota);

return Pdf::loadView('pdfs.danfse', $dados)
    ->download(app(DanfseService::class)->nomeArquivo($nota));

// routes/console.php
Schedule::command('nfse:reconciliar')->everyThirtyMinutes()->withoutOverlapping();
Schedule::command('nfse:acompanhar-analises')->dailyAt('06:00');
Schedule::command('nfse:verificar-certificado')->dailyAt('06:30');

use ClickNfse\Exceptions\NfseException;
use ClickNfse\Exceptions\NfseRejeicaoException;

try {
    $nota = $emissao->emitir($nota);
} catch (NfseRejeicaoException $e) {
    // Regra de negócio da Sefin. Reenviar sem corrigir só repete a rejeição.
    $e->erros;       // [{codigo, descricao, complemento}]
    $e->statusHttp;
} catch (NfseException $e) {
    // Falha técnica ou de configuração. Reprocessável.
}
mermaid
flowchart TD
    A[Faturável confirmado] --> B{Elegível?}
    B -- não --> I[Nota INAPTA<br/>com o motivo]
    I -. cadastro corrigido .-> J[emitirInapta]
    J --> C
    B -- sim --> C[Reserva nDPS<br/>e persiste a nota]
    C --> D[Monta a DPS<br/>e assina]
    D --> E[POST à Sefin<br/>GZip + base64, mTLS]
    E -- 2xx --> F[AUTORIZADA<br/>chave + XML guardados]
    E -- E0014 --> C
    E -- rejeição --> G[REJEITADA<br/>erros gravados]
    E -- falha técnica --> H[ERRO<br/>retry com backoff]
    H -. reconciliação .-> K{Já existe na Sefin?}
    K -- sim --> F
    K -- não --> C
bash
composer  vendor:publish --tag=nfse-config
php artisan vendor:publish --tag=nfse-migrations
php artisan migrate
bash
php artisan nfse:verificar-certificado