| 1 | package Business::BR::NFSe; | ||
| 2 | 1 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 3 | 1 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | 1 | ▶ | use Carp qw(croak); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 5 | 1 | ▶ | use Encode qw(encode); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 6 | 1 | ▶ | use MIME::Base64 qw(encode_base64); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 7 | 1 | ▶ | use Digest::SHA qw(sha256); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 8 | 1 | ▶ | use IO::Compress::Gzip qw(gzip $GzipError); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 9 | 0 | ▶ | use JSON; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 10 | use HTTP::Tiny; | ||
| 11 | use Crypt::PK::RSA; | ||
| 12 | |||
| 13 | our $VERSION = '0.01'; | ||
| 14 | |||
| 15 | |||
| 16 | sub new { | ||
| 17 | my ($class, %args) = @_; | ||
| 18 | |||
| 19 | for my $req (qw(cert_pem_path key_pem_path cnpj_prestador ibge_cidade)) { | ||
| 20 | croak "Business::BR::NFSe->new: '$req' is required" unless defined $args{$req}; | ||
| 21 | } | ||
| 22 | |||
| 23 | my $cert_pem = _slurp($args{cert_pem_path}); | ||
| 24 | my $key_pem = _slurp($args{key_pem_path}); | ||
| 25 | |||
| 26 | my ($cert_b64) = $cert_pem =~ /-----BEGIN CERTIFICATE-----(.+?)-----END CERTIFICATE-----/s; | ||
| 27 | croak "Business::BR::NFSe->new: could not parse certificate PEM" unless $cert_b64; | ||
| 28 | $cert_b64 =~ s/\s+//g; | ||
| 29 | |||
| 30 | return bless { | ||
| 31 | cert_pem_path => $args{cert_pem_path}, | ||
| 32 | key_pem_path => $args{key_pem_path}, | ||
| 33 | key_pem => $key_pem, | ||
| 34 | cert_b64 => $cert_b64, | ||
| 35 | cnpj_prestador => $args{cnpj_prestador}, | ||
| 36 | ibge_cidade => $args{ibge_cidade}, | ||
| 37 | op_simples_nacional => $args{op_simples_nacional} // '3', | ||
| 38 | reg_ap_trib_sn => $args{reg_ap_trib_sn} // '1', | ||
| 39 | regime_especial => $args{regime_especial} // '0', | ||
| 40 | p_tot_trib_sn => $args{p_tot_trib_sn} // '17.99', | ||
| 41 | ambiente => $args{ambiente} // '1', | ||
| 42 | _namespace => 'http://www.sped.fazenda.gov.br/nfse', | ||
| 43 | _versao => '1.01', | ||
| 44 | _url => $args{url} // 'https://sefin.nfse.gov.br/SefinNacional/nfse', | ||
| 45 | http => HTTP::Tiny->new( | ||
| 46 | SSL_options => { | ||
| 47 | SSL_cert_file => $args{cert_pem_path}, | ||
| 48 | SSL_key_file => $args{key_pem_path}, | ||
| 49 | }, | ||
| 50 | ), | ||
| 51 | }, $class; | ||
| 52 | } | ||
| 53 | |||
| 54 | |||
| 55 | sub emitir { | ||
| 56 | my ($self, %dados) = @_; | ||
| 57 | |||
| 58 | for my $req (qw(serie n_dps data_emissao nome_tomador | ||
| 59 | cod_tributacao_nacional cod_tributacao_municipal | ||
| 60 | descricao_servico valor_servico)) { | ||
| 61 | croak "emitir: '$req' is required" unless defined $dados{$req}; | ||
| 62 | } | ||
| 63 | croak "emitir: one (and only one) of 'cpf_tomador', 'cnpj_tomador', or 'nao_nif_tomador' is required" | ||
| 64 | if !!$dados{cpf_tomador} + !!$dados{cnpj_tomador} + !!$dados{nao_nif_tomador} != 1; | ||
| 65 | |||
| 66 | # Mesclando dados do objeto com dados do método: | ||
| 67 | my %d = ( | ||
| 68 | cnpj_prestador => $self->{cnpj_prestador}, | ||
| 69 | ibge_cidade => $self->{ibge_cidade}, | ||
| 70 | op_simples_nacional => $self->{op_simples_nacional}, | ||
| 71 | reg_ap_trib_sn => $self->{reg_ap_trib_sn}, | ||
| 72 | regime_especial => $self->{regime_especial}, | ||
| 73 | p_tot_trib_sn => $self->{p_tot_trib_sn}, | ||
| 74 | ambiente => $self->{ambiente}, | ||
| 75 | %dados, | ||
| 76 | ); | ||
| 77 | |||
| 78 | my $NS = $self->{_namespace}; | ||
| 79 | my $VERSAO = $self->{_versao}; | ||
| 80 | |||
| 81 | # --- 1. identificador DPS (TSIdDPS: "DPS" + ibge(7) + type(1) + cnpj(14) + serie(5) + ndps(15)) --- | ||
| 82 | # type=2 para prestador com CNPJ, type=1 para prestador com CPF | ||
| 83 | my $id_dps = sprintf('DPS%s2%014s%05s%015s', | ||
| 84 | $d{ibge_cidade}, $d{cnpj_prestador}, $d{serie}, $d{n_dps}, | ||
| 85 | ); | ||
| 86 | |||
| 87 | # dCompet é YYYY-MM-DD | ||
| 88 | my $d_compet = substr($d{data_emissao}, 0, 10); | ||
| 89 | |||
| 90 | # --- 2. Tomador --- | ||
| 91 | my $toma_id; | ||
| 92 | if (defined $d{cpf_tomador}) { $toma_id = "<CPF>$d{cpf_tomador}</CPF>" } | ||
| 93 | elsif (defined $d{cnpj_tomador}) { $toma_id = "<CNPJ>$d{cnpj_tomador}</CNPJ>" } | ||
| 94 | else { $toma_id = "<cNaoNIF>$d{nao_nif_tomador}</cNaoNIF>" } | ||
| 95 | |||
| 96 | # --- 3. Constrói XML infDPS --- | ||
| 97 | my $inf_dps = join '', | ||
| 98 | qq(<infDPS Id="$id_dps">), | ||
| 99 | qq(<tpAmb>$d{ambiente}</tpAmb>), | ||
| 100 | qq(<dhEmi>$d{data_emissao}</dhEmi>), | ||
| 101 | q(<verAplic>BUSINESS_BR_NFSE_V1</verAplic>), | ||
| 102 | qq(<serie>$d{serie}</serie>), | ||
| 103 | qq(<nDPS>$d{n_dps}</nDPS>), | ||
| 104 | qq(<dCompet>$d_compet</dCompet>), | ||
| 105 | q(<tpEmit>1</tpEmit>), | ||
| 106 | qq(<cLocEmi>$d{ibge_cidade}</cLocEmi>), | ||
| 107 | q(<prest>), | ||
| 108 | qq(<CNPJ>$d{cnpj_prestador}</CNPJ>), | ||
| 109 | (defined $d{email_prestador} ? qq(<email>$d{email_prestador}</email>) : ()), | ||
| 110 | q(<regTrib>), | ||
| 111 | qq(<opSimpNac>$d{op_simples_nacional}</opSimpNac>), | ||
| 112 | qq(<regApTribSN>$d{reg_ap_trib_sn}</regApTribSN>), | ||
| 113 | qq(<regEspTrib>$d{regime_especial}</regEspTrib>), | ||
| 114 | q(</regTrib>), | ||
| 115 | q(</prest>), | ||
| 116 | qq(<toma>${toma_id}<xNome>) . _xml_escape($d{nome_tomador}) . q(</xNome></toma>), | ||
| 117 | q(<serv>), | ||
| 118 | qq(<locPrest><cLocPrestacao>$d{ibge_cidade}</cLocPrestacao></locPrest>), | ||
| 119 | q(<cServ>), | ||
| 120 | qq(<cTribNac>$d{cod_tributacao_nacional}</cTribNac>), | ||
| 121 | qq(<cTribMun>$d{cod_tributacao_municipal}</cTribMun>), | ||
| 122 | qq(<xDescServ>) . _xml_escape($d{descricao_servico}) . q(</xDescServ>), | ||
| 123 | q(</cServ>), | ||
| 124 | q(</serv>), | ||
| 125 | q(<valores>), | ||
| 126 | qq(<vServPrest><vServ>$d{valor_servico}</vServ></vServPrest>), | ||
| 127 | q(<trib>), | ||
| 128 | q(<tribMun><tribISSQN>1</tribISSQN><tpRetISSQN>1</tpRetISSQN></tribMun>), | ||
| 129 | q(<tribFed><piscofins><CST>00</CST></piscofins></tribFed>), | ||
| 130 | qq(<totTrib><pTotTribSN>$d{p_tot_trib_sn}</pTotTribSN></totTrib>), | ||
| 131 | q(</trib>), | ||
| 132 | q(</valores>), | ||
| 133 | q(</infDPS>); | ||
| 134 | |||
| 135 | # --- 4. Digest do infDPS --- | ||
| 136 | # O elemento sendo assinado herda o namespace do pai no documento final, | ||
| 137 | # então adicionamos o xmlns explicitamente antes do hash. | ||
| 138 | (my $inf_dps_for_hash = $inf_dps) =~ s/<infDPS/<infDPS xmlns="$NS"/; | ||
| 139 | my $digest_b64 = encode_base64(sha256(encode('UTF-8', $inf_dps_for_hash)), ''); | ||
| 140 | |||
| 141 | # --- 5. SignedInfo --- | ||
| 142 | # Precisa fechar tags explicitamente (nada de auto-fechar) porque o servidor verifica | ||
| 143 | # as tags contra o formulário canônico exc-c14n#WithComments, que expande <Bla/> em <Bla></Bla>. | ||
| 144 | my $signed_info = join '', | ||
| 145 | q(<SignedInfo xmlns="http://www.w3.org/2000/09/xmldsig#">), | ||
| 146 | q(<CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#WithComments"></CanonicalizationMethod>), | ||
| 147 | q(<SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"></SignatureMethod>), | ||
| 148 | qq(<Reference URI="#$id_dps">), | ||
| 149 | q(<Transforms>), | ||
| 150 | q(<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"></Transform>), | ||
| 151 | q(<Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#WithComments"></Transform>), | ||
| 152 | q(</Transforms>), | ||
| 153 | q(<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"></DigestMethod>), | ||
| 154 | qq(<DigestValue>$digest_b64</DigestValue>), | ||
| 155 | q(</Reference>), | ||
| 156 | q(</SignedInfo>); | ||
| 157 | |||
| 158 | # --- 6. Assinatura RSA-SHA256 sobre os bytes SignedInfo --- | ||
| 159 | my $rsa = Crypt::PK::RSA->new(\$self->{key_pem}); | ||
| 160 | my $sig_b64 = encode_base64($rsa->sign_message(encode('UTF-8', $signed_info), 'SHA256', 'v1.5'), ''); | ||
| 161 | |||
| 162 | # --- 7. Monta o XML final --- | ||
| 163 | my $xml = join '', | ||
| 164 | q(<?xml version="1.0" encoding="UTF-8"?>), | ||
| 165 | qq(<DPS xmlns="$NS" versao="$VERSAO">), | ||
| 166 | $inf_dps, | ||
| 167 | q(<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">), | ||
| 168 | $signed_info, | ||
| 169 | qq(<SignatureValue>$sig_b64</SignatureValue>), | ||
| 170 | qq(<KeyInfo><X509Data><X509Certificate>$self->{cert_b64}</X509Certificate></X509Data></KeyInfo>), | ||
| 171 | q(</Signature>), | ||
| 172 | q(</DPS>); | ||
| 173 | |||
| 174 | # --- 8. GZip + base64 --- | ||
| 175 | my $xml_bytes = encode('UTF-8', $xml); | ||
| 176 | my $gzipped; | ||
| 177 | gzip(\$xml_bytes, \$gzipped) or croak "gzip failed: $GzipError"; | ||
| 178 | my $payload_b64 = encode_base64($gzipped, ''); | ||
| 179 | |||
| 180 | # --- 9. POST com TLS mútuo --- | ||
| 181 | my $res = $self->{http}->post( | ||
| 182 | $self->{_url}, | ||
| 183 | { | ||
| 184 | content => encode_json({ dpsXmlGZipB64 => $payload_b64 }), | ||
| 185 | headers => { 'Content-Type' => 'application/json' }, | ||
| 186 | }, | ||
| 187 | ); | ||
| 188 | my $body = eval { decode_json($res->{content}) } // {}; | ||
| 189 | return $body; | ||
| 190 | } | ||
| 191 | |||
| 192 | |||
| 193 | sub danfse { | ||
| 194 | my ($self, $chave_acesso) = @_; | ||
| 195 | croak "danfse() precisa de uma chave de acesso." unless defined $chave_acesso; | ||
| 196 | my $res = $self->{http}->get('https://adn.nfse.gov.br/danfse/' . $chave_acesso); | ||
| 197 | return $res->{success} ? $res->{content} : (); | ||
| 198 | } | ||
| 199 | |||
| 200 | |||
| 201 | sub _slurp { | ||
| 202 | my ($path) = @_; | ||
| 203 | open my $fh, '<', $path or croak "Cannot open '$path': $!"; | ||
| 204 | local $/; | ||
| 205 | my $content = <$fh>; | ||
| 206 | close $fh; | ||
| 207 | return $content; | ||
| 208 | } | ||
| 209 | |||
| 210 | sub _xml_escape { | ||
| 211 | my ($str) = @_; | ||
| 212 | $str =~ s/&/&/g; | ||
| 213 | $str =~ s/</</g; | ||
| 214 | $str =~ s/>/>/g; | ||
| 215 | return $str; | ||
| 216 | } | ||
| 217 | |||
| 218 | 1; | ||
| 219 | |||
| 220 | __END__ | ||