├── .coveralls.yml ├── .github └── workflows │ └── php.yml ├── .gitignore ├── .travis.yml ├── Dockerfile ├── LICENSE.md ├── README.md ├── certs ├── README.txt └── metadata │ └── README.txt ├── composer.json ├── composer.lock ├── docker-compose.yml ├── exemplos ├── consulta-config-uf.php ├── consulta-lote-sefaz.php ├── docs │ ├── Manual de Integração_Contribuintes_GNRE_v2.01.pdf │ └── Manual_de_Integracao_Contribuintes_GNRE_v2.00.zip ├── enviar-lote-sefaz.php ├── extrair-dados-certificado.php ├── gerar-codigo-de-barras.php ├── gerar-pdf.php ├── gerar-xml.php ├── guia.jpg ├── index.php ├── retorno-sefaz-original.txt ├── tratar-retorno-sefaz.php └── xml │ ├── envelope-consulta-config-uf.xml │ ├── envelope-consultar-gnre.xml │ ├── estrutura-lote-completo-gnre.xml │ ├── lote-emit-cnpj-dest-cnpj-sem-campos-extras.xml │ ├── lote-emit-cpf-dest-cpf-sem-campos-extras.xml │ ├── lote-emit-cpf-dest-cpf-sem-cep-emitente.xml │ ├── lote-emit-cpf-dest-cpf-sem-inscricao-estadual-emitente.xml │ ├── lote-emit-cpf-dest-cpf-sem-telefone-emitente.xml │ └── resultado-consulta-gnre.xml ├── lib └── Sped │ └── Gnre │ ├── Configuration │ ├── CertificatePfx.php │ ├── CertificatePfxFileOperation.php │ ├── FileOperation.php │ ├── FilePrefix.php │ └── Setup.php │ ├── Exception │ ├── CannotOpenCertificate.php │ ├── ConnectionFactoryUnavailable.php │ ├── UnableToWriteFile.php │ ├── UndefinedProperty.php │ └── UnreachableFile.php │ ├── Helper │ └── GnreHelper.php │ ├── Parser │ ├── Rules.php │ └── SefazRetorno.php │ ├── Render │ ├── Barcode128.php │ ├── Html.php │ ├── Pdf.php │ └── SmartyFactory.php │ ├── Sefaz │ ├── ConfigUf.php │ ├── Consulta.php │ ├── ConsultaConfigUf.php │ ├── ConsultaGnre.php │ ├── EstadoFactory.php │ ├── Estados │ │ ├── AC.php │ │ ├── AL.php │ │ ├── AM.php │ │ ├── AP.php │ │ ├── BA.php │ │ ├── CE.php │ │ └── Padrao.php │ ├── Guia.php │ ├── Lote.php │ ├── LoteGnre.php │ ├── LoteV2.php │ ├── ObjetoSefaz.php │ └── Send.php │ └── Webservice │ ├── Connection.php │ └── ConnectionFactory.php ├── phpunit.xml.dist ├── templates └── gnre.tpl ├── testes ├── Configuration │ ├── CertificatePfxTest.php │ ├── FileOperationTest.php │ ├── FilePrefixTest.php │ └── MyFile.php ├── Parser │ └── SefazRetornoTest.php ├── Render │ ├── BarcodeTest.php │ ├── CoveragePdf.php │ ├── HtmlTest.php │ ├── PdfTest.php │ └── SmartyFactoryTest.php ├── Sefaz │ ├── ConfigUfTest.php │ ├── ConsultaConfigUfTest.php │ ├── ConsultaGnreTest.php │ ├── ConsultaTest.php │ ├── EstadoFactoryTest.php │ ├── GuiaTest.php │ ├── LoteGnreTest.php │ ├── LoteTest.php │ ├── MinhaConsultaConfigUf.php │ ├── MinhaConsultaGnre.php │ └── SendTest.php └── Webservice │ ├── ConnectionFactoryTest.php │ └── ConnectionTest.php ├── wsdl ├── GnreLoteResultado.wsdl └── GnreRecepcaoLote.wsdl └── xsd ├── v1 ├── config_uf_v1.00.xsd ├── consulta_config_uf_v1.00.xsd ├── lote_gnre_consulta_v1.00.xsd ├── lote_gnre_recibo_v1.00.xsd ├── lote_gnre_result_v1.00.xsd ├── lote_gnre_v1.00.xsd └── tiposBasicoGNRE_v1.00.xsd └── v2 ├── dados_gnre_v2.00.xsd ├── lote_gnre_result_v2.00.xsd ├── lote_gnre_v2.00.xsd └── tiposBasicoGNRE_v2.00.xsd /.coveralls.yml: -------------------------------------------------------------------------------- 1 | src_dir: . 2 | -------------------------------------------------------------------------------- /.github/workflows/php.yml: -------------------------------------------------------------------------------- 1 | name: PHP Composer 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | pull_request: 7 | branches: [ "master" ] 8 | 9 | permissions: 10 | contents: read 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | 19 | - uses: actions/checkout@v3 20 | 21 | - name: Setup PHP 22 | uses: shivammathur/setup-php@v2 23 | with: 24 | php-version: 7.3 25 | 26 | - name: Validate composer.json and composer.lock 27 | run: composer validate --strict 28 | 29 | - name: Cache Composer packages 30 | id: composer-cache 31 | uses: actions/cache@v3 32 | with: 33 | path: vendor 34 | key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }} 35 | restore-keys: | 36 | ${{ runner.os }}-php- 37 | 38 | - name: Install dependencies 39 | run: composer install --prefer-dist --no-progress 40 | 41 | # Add a test script to composer.json, for instance: "test": "vendor/bin/phpunit" 42 | # Docs: https://getcomposer.org/doc/articles/scripts.md 43 | 44 | - name: Run test suite 45 | run: composer run-script test 46 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | certs/ 2 | vendor/ 3 | .idea/ 4 | coverage/ 5 | local/ 6 | nbproject 7 | .phpunit.result.cache 8 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: php 2 | 3 | dist: bionic 4 | 5 | php: 6 | - 7.3 7 | - 7.4snapshot 8 | 9 | matrix: 10 | allow_failures: 11 | - php: 7.4snapshot 12 | 13 | before_script: 14 | - composer install --prefer-dist --no-interaction --no-progress 15 | - composer update #required to install zend-servicemanager and zend-barcode 16 | 17 | script: 18 | - mkdir -p build/logs 19 | - ./vendor/bin/phpunit --coverage-clover build/logs/clover.xml 20 | 21 | after_script: 22 | - php vendor/bin/coveralls -v 23 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM php:7.3 2 | 3 | WORKDIR /var/www 4 | 5 | COPY . . 6 | 7 | RUN apt-get update && \ 8 | apt-get install -y libzip-dev libxml2-dev \ 9 | libfreetype6-dev libjpeg62-turbo-dev \ 10 | libgd-dev libpng-dev && \ 11 | docker-php-ext-configure gd \ 12 | --with-freetype-dir=/usr/include/ \ 13 | --with-jpeg-dir=/usr/include/ && \ 14 | docker-php-ext-install -j$(nproc) zip soap gd && \ 15 | curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer 16 | 17 | RUN pecl install xdebug \ 18 | pecl install gmagick \ 19 | && docker-php-ext-enable xdebug \ 20 | && echo "xdebug.remote_enable=on" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \ 21 | && echo "xdebug.remote_host = host.docker.internal" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini 22 | 23 | EXPOSE 8181 24 | 25 | RUN composer install 26 | 27 | CMD php -S 0.0.0.0:8181 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build status (PHP Composer)](https://github.com/nfephp-org/sped-gnre/actions/workflows/php.yml/badge.svg)](https://github.com/nfephp-org/sped-gnre/actions/workflows/php.yml) 2 | [![Coverage Status](https://coveralls.io/repos/marabesi/gnrephp/badge.svg)](https://coveralls.io/r/nfephp-org/sped-gnre) 3 | [![Total Downloads](https://poser.pugx.org/marabesi/gnre/downloads)](https://packagist.org/packages/nfephp-org/sped-gnre) 4 | [![Latest Stable Version](https://poser.pugx.org/marabesi/gnre/v/stable)](https://packagist.org/packages/nfephp-org/sped-gnre) 5 | [![Latest Unstable Version](https://poser.pugx.org/marabesi/gnre/v/unstable.png)](https://packagist.org/packages/nfephp-org/sped-gnre) 6 | [![License](https://poser.pugx.org/marabesi/gnre/license)](https://packagist.org/packages/nfephp-org/sped-gnre) 7 | 8 | Atenção!! 9 | ================= 10 | Caso encontre algum estado que possua uma regra especial para gerar uma GNRE por favor informar abrindo uma **issue**. 11 | Dessa forma podemos manter a API atualizada e ajudar a todos que utlizam a GNRE PHP 12 | 13 | Atenção 2!! 14 | ================= 15 | Se você possui um certificado da certisign e está com o erro "Bad request" veja a solução encontrada pelo [renandelmonico](https://github.com/renandelmonico) utilizando 16 | as classes da sped-common nesse [link](https://groups.google.com/d/msg/gnrephp/kbNWB3aEBbs/0g067FKlBgAJ) 17 | 18 | Os certificados da certisign possuem algum problema em que não é possível extrair a cadeia de certificação, portanto é necessário fazer o download da cadeia manualmente nesse [link](https://www.certisign.com.br/duvidas-suporte/downloads/hierarquias/icp-brasil/ac-instituto-fenacon-rfb) (Hierarquia V5). 19 | 20 | Após o download é necessário extrair usando o openssl, copiar o conteúdo gerado pelos 3 certificados e colar em um novo arquivo .pem. 21 | 22 | ```sh 23 | openssl x509 -inform der -in ARQUIVO.cer -pubkey -noout > ARQUIVO.pem 24 | ``` 25 | 26 | Depois de realizar o processo acima, é necessário utilizar o método addCurlOption da classe Sped\Gnre\Webservice\Connection para alterar algumas configurações e informar manualmente a cadeia de certificação. 27 | 28 | ```php 29 | $webService->addCurlOption([ 30 | CURLOPT_SSL_VERIFYHOST => 2, 31 | CURLOPT_SSL_VERIFYPEER => 1, 32 | CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1, 33 | CURLOPT_CAINFO => 'ARQUIVO.pem' 34 | ]); 35 | ``` 36 | 37 | Versões suportadas 38 | ================= 39 | 40 | |PHP| GNRE| 41 | |---|-----| 42 | | PHP 5.6 | 0.1.4 | 43 | | HHVM | 0.1.4 | 44 | | PHP 7.0 | 0.1.5 | 45 | | PHP 7.3 | 0.1.6 | 46 | 47 | 48 | Antes de usar a API 49 | ================= 50 | 51 | - Verifique se seu certificado digital não foi expedido através da [certisign](https://www.certisign.com.br), pois existe um problema na cadeia do certificado que impossibilita a emissão de guias GNRE. Certificados expedidos através do [SERASA](https://serasa.certificadodigital.com.br/) funcionam normalmente para a emissão (até agora nenhum erro foi relatado). 52 | 53 | - É permitido utilizar o mesmo certificado utilizado para emitir NF-e. 54 | 55 | - É necessário entrar em contato com a SEFAZ de cada estado pedindo liberação do serviço de emissão de GNRE. 56 | 57 | - Leita todos os tópicos no FAQ oficial em http://www.gnre.pe.gov.br/gnre/portal/faq.jsp. Os tópicos abordados são muito úteis para quem está começando nesse serviço. 58 | 59 | GNRE PHP 60 | ================= 61 | 62 | Objetivo 63 | ----- 64 | API possibilita a comunicação com a SEFAZ para a emissão da nota GNRE (Guia Nacional de Recolhimento de Tributos Estaduais). 65 | A API GNRE tem como maior inspiração a API NFEPHP que você pode encontrar através do link https://github.com/nfephp 66 | 67 | Dependências 68 | ------- 69 | * [Apache](http://httpd.apache.org/) / [Nginx](http://nginx.org/) 70 | * [PHP 5.3+](http://php.net) 71 | * Extensões PHP 72 | * [DOMDocument](http://br2.php.net/manual/en/domdocument.construct.php) 73 | * [cURL](http://br2.php.net/manual/book.curl.php) 74 | * [GD (Utilizada para renderizar o código de barras)] (http://php.net/manual/pt_BR/book.image.php) 75 | 76 | ------ 77 | 78 | Road-map 79 | ----- 80 | 81 | Atualmente estamos utilizando o trello para gerenciar o que será implementado nas próximas versões e melhorias na API, esse road map poe ser acessado em https://trello.com/b/kNP1tvsi/gnre-api-github 82 | 83 | ------ 84 | 85 | Informações úteis 86 | ----- 87 | 88 | |Descrição|Endereço| 89 | |---------|--------| 90 | |Grupo de discussão | https://groups.google.com/forum/#!forum/gnrephp| 91 | |Site oficial do governo | http://www.gnre.pe.gov.br/gnre/index.html| 92 | |Site do Projeto | http://nfephp-org.github.io/sped-gnre/| 93 | |Wiki, onde é possível encontrar maiores informações de como utilizar a API | https://github.com/nfephp-org/sped-gnre/wiki| 94 | |Site oficial da SEFAZ de todo os estados|http://www.gnre.pe.gov.br/gnre/portal/linksUteis.jsp| 95 | 96 | 1. Antes de gerar qualquer guia GNRE com o seu certificado, tenha **CERTEZA** que você possui autorização para isso. A geração de 97 | GNRE depende de cada estado, ou seja, se você deseja gerar a guia para o Acre (com destino ao Acre) tenha certeza que 98 | já pediu a liberação do certificado no SEFAZ Acre e repita esse processo para cada estado. 99 | 100 | Documentação 101 | ------ 102 | * Documentação da GNRE PHP gerada com o PHPDOC pode ser visualizada [aqui](http://nfephp-org.github.io/sped-gnre//doc/namespaces/Gnre.html) 103 | 104 | * Nosso wiki de como utilizar a API e gerar as GNRES está disponível [aqui no github](https://github.com/nfephp-org/sped-gnre/wiki) 105 | 106 | * Exemplos com código fonte são encontrados na pasta [exemplos/](https://github.com/nfephp-org/sped-gnre/tree/master/exemplos) 107 | 108 | Instalação via composer 109 | ------ 110 | Adicionando a GNRE PHP em um projeto existente com o composer 111 | 112 | Caso você não possua o composer veja [esse link](https://getcomposer.org/doc/01-basic-usage.md) antes de prosseguir 113 | 114 | Adicione a dependência da GNRE PHP no arquivo composer.json : 115 | 116 | Para PHP <= 5.5 117 | ``` json 118 | { 119 | "nfephp-org/sped-gnre": "0.1.1" 120 | } 121 | ``` 122 | 123 | Para PHP = 5.6 124 | ``` json 125 | { 126 | "nfephp-org/sped-gnre": "0.1.4" 127 | } 128 | ``` 129 | 130 | 131 | Para PHP >= 7.0 132 | ``` json 133 | { 134 | "nfephp-org/sped-gnre": "0.1.5" 135 | } 136 | ``` 137 | 138 | Atualize suas depedências existentes no composer : 139 | 140 | ``` terminal 141 | composer update 142 | ``` 143 | ----- 144 | Possíveis erros 145 | ----- 146 | 147 | Erro : **unable to use client certificate (no key found or wrong pass phrase?)** 148 | 149 | Se você está obtendo essa mensagem após enviar a requisição para o web service da SEFAZ verifique a senha que você está utilizando, pois esse erro ocorre quando a senha informada não bate com a senha do certificado utilizado 150 | 151 | Erro: **[InvalidArgumentException] 152 | Could not find package marabesi/gnre at any version for your minimum-stability (stable). Check the package spelling or your minimum-stability** 153 | 154 | Esse problema ocorre pois não estamos informando ao composer qual a versão mínima que queremos utilizar, para resolver esse problema basta adicionar a seguinte linha no seu arquivo composer.json 155 | 156 | ``` json 157 | { 158 | "minimum-stability": "dev" 159 | } 160 | ``` 161 | ----- 162 | Quick start 163 | ----- 164 | Clone o repositório do projeto 165 | ``` terminal 166 | git clone https://github.com/nfephp-org/sped-gnre.git 167 | ``` 168 | Vá para a pasta de exemplos 169 | ``` 170 | cd exemplos/ 171 | ``` 172 | Rode o servidor built-in do PHP 173 | ``` 174 | php -S localhost:8181 175 | ``` 176 | Abra o seu navegador e digite a seguinte URL 177 | ``` 178 | http://localhost:8181/gerar-xml.php 179 | ``` 180 | ----- 181 | 182 | Caso queira ver outros exemplos utilizados pela API acesse esse link https://github.com/nfephp-org/sped-gnre/tree/master/exemplos 183 | -------------------------------------------------------------------------------- /certs/README.txt: -------------------------------------------------------------------------------- 1 | Essa pasta contém todos os certificados que serão utilizados pela API -------------------------------------------------------------------------------- /certs/metadata/README.txt: -------------------------------------------------------------------------------- 1 | Essa pasta contém todos os meta dados extraidos dos certificados pela API -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nfephp-org/sped-gnre", 3 | "description": "API para a emissão de guias GNRE para a SEFAZ", 4 | "license": ["GPL-3.0-or-later", "MIT"], 5 | "require": { 6 | "php": ">=7.3.0", 7 | "dompdf/dompdf": "^1.0", 8 | "laminas/laminas-servicemanager": "~3.0", 9 | "laminas/laminas-barcode": "^2.3", 10 | "smarty/smarty": "~3.1", 11 | "nfephp-org/sped-nfe": "~5.0", 12 | "ext-gd": "*", 13 | "ext-dom": "*" 14 | }, 15 | "scripts": { 16 | "test": "phpunit" 17 | }, 18 | "autoload": { 19 | "psr-4": { 20 | "Sped\\Gnre\\": "lib/Sped/Gnre/", 21 | "Sped\\Gnre\\Test\\": "testes/" 22 | } 23 | }, 24 | "minimum-stability": "dev", 25 | "prefer-stable": true, 26 | "require-dev": { 27 | "phpunit/phpunit": "^9.0", 28 | "squizlabs/php_codesniffer": "^3.5", 29 | "php-coveralls/php-coveralls": "^2.2", 30 | "mikey179/vfsstream": "^1.6" 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "2" 2 | 3 | services: 4 | gnre: 5 | build: 6 | context: . 7 | ports: 8 | - '8181:8181' 9 | volumes: 10 | - ./:/var/www 11 | command: php -S 0.0.0.0:8181 12 | -------------------------------------------------------------------------------- /exemplos/consulta-config-uf.php: -------------------------------------------------------------------------------- 1 | setEnvironment(1); 67 | $config->setReceita(100099); 68 | $config->setEstado('PR'); 69 | 70 | $webService = new Sped\Gnre\Webservice\Connection($minhaConfiguracao, $config->getHeaderSoap(), $config->toXml()); 71 | 72 | $consulta = $webService->doRequest($config->soapAction()); 73 | echo '
';
74 | echo htmlspecialchars($consulta);
75 | 


--------------------------------------------------------------------------------
/exemplos/consulta-lote-sefaz.php:
--------------------------------------------------------------------------------
 1 | setRecibo(12345123);
65 | 
66 | /**
67 |  * O número que representa em qual ambiente sera realizada a consulta
68 |  * 1 - produção 2 - homologação
69 |  */
70 | $consulta->setEnvironment(1);
71 | //$consulta->utilizarAmbienteDeTeste(true); //Descomente essa linha para utilizar o ambiente de testes
72 | 
73 | //header('Content-Type: text/xml');
74 | //print $consulta->toXml(); // exibe o XML da consulta
75 | 
76 | $webService = new Sped\Gnre\Webservice\Connection($minhaConfiguracao, $consulta->getHeaderSoap(), $consulta->toXml());
77 | echo $webService->doRequest($consulta->soapAction());
78 | 


--------------------------------------------------------------------------------
/exemplos/docs/Manual de Integração_Contribuintes_GNRE_v2.01.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nfephp-org/sped-gnre/08c4e6d3f9c8fba185f9c5966e509c410ec95f83/exemplos/docs/Manual de Integração_Contribuintes_GNRE_v2.01.pdf


--------------------------------------------------------------------------------
/exemplos/docs/Manual_de_Integracao_Contribuintes_GNRE_v2.00.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nfephp-org/sped-gnre/08c4e6d3f9c8fba185f9c5966e509c410ec95f83/exemplos/docs/Manual_de_Integracao_Contribuintes_GNRE_v2.00.zip


--------------------------------------------------------------------------------
/exemplos/enviar-lote-sefaz.php:
--------------------------------------------------------------------------------
 1 | utilizarAmbienteDeTeste(true); Descomente essa linha para utilizar o ambiente de testes
73 | 
74 | $lote->addGuia($guia);
75 | 
76 | $webService = new Sped\Gnre\Webservice\Connection($minhaConfiguracao, $lote->getHeaderSoap(), $lote->toXml());
77 | echo $webService->doRequest($lote->soapAction());
78 | 


--------------------------------------------------------------------------------
/exemplos/extrair-dados-certificado.php:
--------------------------------------------------------------------------------
 1 | getPrivateKey();
13 | 
14 | print 'Certificate .pem' . PHP_EOL;
15 | print $gnre->getCertificatePem();
16 | 


--------------------------------------------------------------------------------
/exemplos/gerar-codigo-de-barras.php:
--------------------------------------------------------------------------------
 1 |  (string) $text, 'barHeight' => 40, 'barWidth' => 100, 'imageType' => 'jpeg');
 9 | $barcode = new \Laminas\Barcode\Object\Code128();
10 | $barcode->setOptions($options);
11 | 
12 | $barcodeOBj = \Laminas\Barcode\Barcode::factory($barcode);
13 | 
14 | $imageResource = $barcodeOBj->draw();
15 | 
16 | imagejpeg($imageResource);
17 | 
18 | $contents = ob_get_contents();
19 | ob_end_clean();
20 | 
21 | 
22 | $barcodeGnre = new Sped\Gnre\Render\Barcode128();
23 | $barcodeGnre->setNumeroCodigoBarras('91910919190191091090109109190109');
24 | 
25 | ?>
26 | 
27 | 
28 | 
29 | 
30 | 


--------------------------------------------------------------------------------
/exemplos/gerar-pdf.php:
--------------------------------------------------------------------------------
 1 | c01_UfFavorecida = 'SP';
 9 | $guia->c02_receita = 1000099;
10 | $guia->c25_detalhamentoReceita = 10101010;
11 | $guia->c26_produto = 'TESTE DE PROD';
12 | $guia->c27_tipoIdentificacaoEmitente = 1;
13 | $guia->c03_idContribuinteEmitente = 41819055000105;
14 | $guia->c28_tipoDocOrigem = 10;
15 | $guia->c04_docOrigem = 5656;
16 | $guia->c06_valorPrincipal = 10.99;
17 | $guia->c10_valorTotal = 12.52;
18 | $guia->c14_dataVencimento = '01/05/2015';
19 | $guia->c15_convenio = 546456;
20 | $guia->c16_razaoSocialEmitente = 'GNRE PHP EMITENTE';
21 | $guia->c17_inscricaoEstadualEmitente = 56756;
22 | $guia->c18_enderecoEmitente = 'Queens St';
23 | $guia->c19_municipioEmitente = 5300108;
24 | $guia->c20_ufEnderecoEmitente = 'DF';
25 | $guia->c21_cepEmitente = '08215917';
26 | $guia->c22_telefoneEmitente = 1199999999;
27 | $guia->c34_tipoIdentificacaoDestinatario = 1;
28 | $guia->c35_idContribuinteDestinatario = 86268158000162;
29 | $guia->c36_inscricaoEstadualDestinatario = 10809181;
30 | $guia->c37_razaoSocialDestinatario = 'RAZAO SOCIAL GNRE PHP DESTINATARIO';
31 | $guia->c38_municipioDestinatario = 2702306;
32 | $guia->c33_dataPagamento = '2015-11-30';
33 | $guia->retornoInformacoesComplementares = 'teste teste teste';
34 | $guia->retornoAtualizacaoMonetaria = 1.88;
35 | $guia->retornoNumeroDeControle = '0000000000000000';
36 | $guia->retornoCodigoDeBarras = '1118929812912011000000001818181000000001212';
37 | $guia->retornoRepresentacaoNumerica = '11189298129120110000000018181810000000012121201';
38 | $guia->retornoJuros = 2.78;
39 | $guia->retornoMulta = 3.55;
40 | $guia->mes = '05';
41 | $guia->ano = 2015;
42 | $guia->parcela = 2;
43 | $guia->periodo = 2014;
44 | 
45 | $lote = new Sped\Gnre\Sefaz\Lote();
46 | $lote->addGuia($guia);
47 | 
48 | $html = new Sped\Gnre\Render\Html();
49 | $html->create($lote);
50 | 
51 | $pdf = new Sped\Gnre\Render\Pdf();
52 | $pdf->create($html)->stream('gnre.pdf', array('Attachment' => 0));
53 | 


--------------------------------------------------------------------------------
/exemplos/gerar-xml.php:
--------------------------------------------------------------------------------
 1 | c01_UfFavorecida = 'SP';
 9 | $guia->c02_receita = 1000099;
10 | $guia->c25_detalhamentoReceita = 10101010;
11 | $guia->c26_produto = 'TESTE DE PROD';
12 | $guia->c27_tipoIdentificacaoEmitente = 1;
13 | $guia->c03_idContribuinteEmitente = 41819055000105;
14 | $guia->c28_tipoDocOrigem = 10;
15 | $guia->c04_docOrigem = 5656;
16 | $guia->c06_valorPrincipal = 10.99;
17 | $guia->c10_valorTotal = 12.52;
18 | $guia->c14_dataVencimento = '01/05/2015';
19 | $guia->c15_convenio = 546456;
20 | $guia->c16_razaoSocialEmitente = 'GNRE PHP EMITENTE';
21 | $guia->c17_inscricaoEstadualEmitente = 56756;
22 | $guia->c18_enderecoEmitente = 'Queens St';
23 | $guia->c19_municipioEmitente = 5300108;
24 | $guia->c20_ufEnderecoEmitente = 'DF';
25 | $guia->c21_cepEmitente = '08215917';
26 | $guia->c22_telefoneEmitente = 1199999999;
27 | $guia->c34_tipoIdentificacaoDestinatario = 1;
28 | $guia->c35_idContribuinteDestinatario = 86268158000162;
29 | $guia->c36_inscricaoEstadualDestinatario = 10809181;
30 | $guia->c37_razaoSocialDestinatario = 'RAZAO SOCIAL GNRE PHP DESTINATARIO';
31 | $guia->c38_municipioDestinatario = 2702306;
32 | $guia->c33_dataPagamento = '2015-11-30';
33 | $guia->retornoInformacoesComplementares = 'teste teste teste';
34 | $guia->retornoAtualizacaoMonetaria = 1.88;
35 | $guia->retornoNumeroDeControle = '0000000000000000';
36 | $guia->retornoCodigoDeBarras = '1118929812912011000000001818181000000001212';
37 | $guia->retornoRepresentacaoNumerica = '11189298129120110000000018181810000000012121201';
38 | $guia->retornoJuros = 2.78;
39 | $guia->retornoMulta = 3.55;
40 | $guia->mes = '05';
41 | $guia->ano = 2015;
42 | $guia->parcela = 2;
43 | $guia->periodo = 2014;
44 | $guia->c39_camposExtras = array(
45 |     array(
46 |         'campoExtra' => array(
47 |             'codigo' => 666,
48 |             'tipo' => 'TXT',
49 |             'valor' => 'GNRE'
50 |         )
51 |     ),
52 |     array(
53 |         'campoExtra' => array(
54 |             'codigo' => 111,
55 |             'tipo' => 'INT',
56 |             'valor' => 'GNRE2'
57 |         )
58 |     ),
59 | );
60 | 
61 | $lote = new Sped\Gnre\Sefaz\Lote();
62 | $lote->addGuia($guia);
63 | 
64 | header('Content-Type: text/xml');
65 | print $lote->toXml();
66 | 


--------------------------------------------------------------------------------
/exemplos/guia.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nfephp-org/sped-gnre/08c4e6d3f9c8fba185f9c5966e509c410ec95f83/exemplos/guia.jpg


--------------------------------------------------------------------------------
/exemplos/index.php:
--------------------------------------------------------------------------------
 1 | 

2 | Gerar XML 3 |

4 |

5 | Gerar PDF 6 |

7 |

8 | Tratar retorno sefaz 9 |

10 |

11 | Gerar código de barras 12 |

13 |

14 | Consultar configuração UF 15 |

16 |

17 | Consultar lote sefaz 18 |

19 |

20 | Enviar lote sefaz 21 |

22 |

23 | Extrair dados certificado 24 |

25 | -------------------------------------------------------------------------------- /exemplos/retorno-sefaz-original.txt: -------------------------------------------------------------------------------- 1 | 020560726600011014111866530 2 | 100011DF12345630000100931575117TESTE TESTE AQAA A AAAAAAAAA DF053390000000533900030000100931575117 0000012345678911111111111 01122014000000001122014001000000000001001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000 3 | 20001c02_receita 205A UF favorecida nao gera GNRE para a Receita informada. 4 | 100021DF12345630000100931575117TESTE TESTE AQAA A AAAAAAAAA DF053390000000533900030000100931575117 0000012345678911111111111 01122014000000001122014001000000000001001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000 5 | 20002c02_receita 205A UF favorecida nao gera GNRE para a Receita informada. 6 | 914111866530002a6ddd0b7dd53be0080e7991ccab1cd38bfa4f6a1285412f5a3aaf7d91c9e6850 -------------------------------------------------------------------------------- /exemplos/tratar-retorno-sefaz.php: -------------------------------------------------------------------------------- 1 | getLote(); 16 | 17 | $consulta = new Sped\Gnre\Sefaz\Consulta(); 18 | 19 | header('Content-Type: text/xml'); 20 | echo $lote->toXml(); 21 | -------------------------------------------------------------------------------- /exemplos/xml/envelope-consulta-config-uf.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 1.00 6 | 7 | 8 | 9 | 10 | 11 | 1 12 | PR 13 | 100099 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /exemplos/xml/envelope-consultar-gnre.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 1.00 6 | 7 | 8 | 9 | 10 | 11 | 12345678 12 | 123 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /exemplos/xml/estrutura-lote-completo-gnre.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 1.00 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 26 14 | 1000099 15 | 10101010 16 | TESTE DE PROD 17 | 1 18 | 19 | 41819055000105 20 | 21 | 10 22 | 5656 23 | 10.99 24 | 12.52 25 | 2015-05-01 26 | 546456 27 | GNRE PHP EMITENTE 28 | 56756 29 | Queens St 30 | 5300108 31 | DF 32 | 08215917 33 | 1199999999 34 | 1 35 | 36 | 86268158000162 37 | 38 | 10809181 39 | RAZAO SOCIAL GNRE PHP DESTINATARIO 40 | 2702306 41 | 2015-11-30 42 | 43 | 2014 44 | 05 45 | 2015 46 | 2 47 | 48 | 49 | 50 | 16 51 | T 52 | 1200012 53 | 54 | 55 | 15 56 | D 57 | 2015-03-02 58 | 59 | 60 | 10 61 | T 62 | 17.21 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /exemplos/xml/lote-emit-cnpj-dest-cnpj-sem-campos-extras.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 1.00 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 26 14 | 1000099 15 | 10101010 16 | TESTE DE PROD 17 | 1 18 | 19 | 41819055000105 20 | 21 | 10 22 | 5656 23 | 10.99 24 | 12.52 25 | 2015-05-01 26 | 546456 27 | GNRE PHP EMITENTE 28 | 56756 29 | Queens St 30 | 5300108 31 | DF 32 | 08215917 33 | 1199999999 34 | 1 35 | 36 | 86268158000162 37 | 38 | 10809181 39 | RAZAO SOCIAL GNRE PHP DESTINATARIO 40 | 2702306 41 | 2015-11-30 42 | 43 | 2014 44 | 05 45 | 2015 46 | 2 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /exemplos/xml/lote-emit-cpf-dest-cpf-sem-campos-extras.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 1.00 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 26 14 | 1000099 15 | 10101010 16 | TESTE DE PROD 17 | 2 18 | 19 | 52162197650 20 | 21 | 10 22 | 5656 23 | 10.99 24 | 12.52 25 | 2015-05-01 26 | 546456 27 | GNRE PHP EMITENTE 28 | 56756 29 | Queens St 30 | 5300108 31 | DF 32 | 08215917 33 | 1199999999 34 | 2 35 | 36 | 99942896759 37 | 38 | 10809181 39 | RAZAO SOCIAL GNRE PHP DESTINATARIO 40 | 2702306 41 | 2015-11-30 42 | 43 | 2014 44 | 05 45 | 2015 46 | 2 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /exemplos/xml/lote-emit-cpf-dest-cpf-sem-cep-emitente.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 1.00 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 26 14 | 1000099 15 | 10101010 16 | TESTE DE PROD 17 | 2 18 | 19 | 52162197650 20 | 21 | 10 22 | 5656 23 | 10.99 24 | 12.52 25 | 2015-05-01 26 | 546456 27 | GNRE PHP EMITENTE 28 | 56756 29 | Queens St 30 | 5300108 31 | DF 32 | 1199999999 33 | 2 34 | 35 | 99942896759 36 | 37 | 10809181 38 | RAZAO SOCIAL GNRE PHP DESTINATARIO 39 | 2702306 40 | 2015-11-30 41 | 42 | 2014 43 | 05 44 | 2015 45 | 2 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /exemplos/xml/lote-emit-cpf-dest-cpf-sem-inscricao-estadual-emitente.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 1.00 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 26 14 | 1000099 15 | 10101010 16 | TESTE DE PROD 17 | 2 18 | 19 | 52162197650 20 | 21 | 10 22 | 5656 23 | 10.99 24 | 12.52 25 | 2015-05-01 26 | 546456 27 | GNRE PHP EMITENTE 28 | Queens St 29 | 5300108 30 | DF 31 | 08215917 32 | 1199999999 33 | 2 34 | 35 | 99942896759 36 | 37 | 10809181 38 | RAZAO SOCIAL GNRE PHP DESTINATARIO 39 | 2702306 40 | 2015-11-30 41 | 42 | 2014 43 | 05 44 | 2015 45 | 2 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /exemplos/xml/lote-emit-cpf-dest-cpf-sem-telefone-emitente.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 1.00 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 26 14 | 1000099 15 | 10101010 16 | TESTE DE PROD 17 | 2 18 | 19 | 52162197650 20 | 21 | 10 22 | 5656 23 | 10.99 24 | 12.52 25 | 2015-05-01 26 | 546456 27 | GNRE PHP EMITENTE 28 | 56756 29 | Queens St 30 | 5300108 31 | DF 32 | 08215917 33 | 2 34 | 35 | 99942896759 36 | 37 | 10809181 38 | RAZAO SOCIAL GNRE PHP DESTINATARIO 39 | 2702306 40 | 2015-11-30 41 | 42 | 2014 43 | 05 44 | 2015 45 | 2 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /exemplos/xml/resultado-consulta-gnre.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 1 7 | 0000000000 8 | 9 | 403 10 | Lote Processado com pendencias 11 | 12 | 000000000000000000000700080 13 | 100011AC12345630000000000212112TESTE RAZAO SOCIAL RUA TESTE TESTE TESTE SP123456780001234567830000000000212112 000000000000212112212112 10102014000000003112014005000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000 14 | 20001c02_receita 205A UF favorecida nao gera GNRE para a Receita informada. 15 | 914066705180001aef4dc134cd7c735c450d58c1d6f164ab4c55ddce25511fbe0d6b4b7970c3a98 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Configuration/CertificatePfx.php: -------------------------------------------------------------------------------- 1 | 28 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 29 | * @version 1.0.0 30 | */ 31 | class CertificatePfx 32 | { 33 | 34 | /** 35 | * Atributo que armazena os dados extraidos do certificado com a função openssl_pkcs12_read 36 | * @var array 37 | */ 38 | private $dataCertificate = array(); 39 | 40 | /** 41 | * Objecto necessário para realizar operações de criação de arquivos 42 | * a partir dos dados do certificado 43 | * @var \Sped\Gnre\Configuration\CertificatePfxFileOperation 44 | */ 45 | private $cerficationFileOperation; 46 | 47 | /** 48 | * Dependências utilizadas para efetuar operação no certificado desejado 49 | * @param \Sped\Gnre\Configuration\CertificatePfxFileOperation $cerficationFileOperation 50 | * @param string $password senha utilizada para realizar operações com o certificado 51 | * @since 1.0.0 52 | */ 53 | public function __construct(CertificatePfxFileOperation $cerficationFileOperation, $password) 54 | { 55 | $this->cerficationFileOperation = $cerficationFileOperation; 56 | $this->dataCertificate = $this->cerficationFileOperation->open($password); 57 | } 58 | 59 | /** 60 | * Cria um arquivo na pasta definida nas configurações padrões (/certs/metadata) com a 61 | * chave privada do certificado. Para salvar o novo arquivo é utilizado 62 | * o mesmo nome do certificado e com prefixo definido no método 63 | * @throws Sped\Gnre\Exception\UnableToWriteFile Se a pasta de destino não tiver permissão para escrita 64 | * @return string Retorna uma string com o caminho e o nome do arquivo que foi criado 65 | * @since 1.0.0 66 | */ 67 | public function getPrivateKey() 68 | { 69 | $filePrefix = new FilePrefix(); 70 | $filePrefix->setPrefix('_privKEY'); 71 | return $this->cerficationFileOperation->writeFile($this->dataCertificate['pkey'], $filePrefix); 72 | } 73 | 74 | /** 75 | * Cria um arquivo na pasta definida nas configurações padrões (/certs/metadata) com a 76 | * chave privada do certificado. Para salvar o novo arquivo é utilizado 77 | * o mesmo nome do certificado e com prefixo definido no método 78 | * @throws Sped\Gnre\Exception\UnableToWriteFile Se a pasta de destino não tiver permissão para escrita 79 | * @return string Retorna uma string com o caminho e o nome do arquivo que foi criado 80 | * @since 1.0.0 81 | */ 82 | public function getCertificatePem() 83 | { 84 | $filePrefix = new FilePrefix(); 85 | $filePrefix->setPrefix('_certKEY'); 86 | return $this->cerficationFileOperation->writeFile($this->dataCertificate['cert'], $filePrefix); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Configuration/CertificatePfxFileOperation.php: -------------------------------------------------------------------------------- 1 | 30 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 31 | * @version 1.0.0 32 | */ 33 | class CertificatePfxFileOperation extends FileOperation 34 | { 35 | 36 | /** 37 | * O nome da pasta em que os meta dados dos certificados são armazenados. 38 | * Essa pasta ficará abaixo da pasta /certs ficando então /certs/metadata 39 | * @var string 40 | */ 41 | private $metadataFolder = 'metadata'; 42 | 43 | /** 44 | * Caminho e o nome do arquivo completo do certificado a ser utilizado 45 | * @var string 46 | */ 47 | private $pathToWrite; 48 | 49 | /** 50 | * {@inheritdoc} 51 | */ 52 | public function __construct($filePath) 53 | { 54 | parent::__construct($filePath); 55 | 56 | $explodePath = explode('/', $this->filePath); 57 | $total = count($explodePath); 58 | 59 | $this->fileName = str_replace('.pfx', '.pem', $explodePath[$total - 1]); 60 | 61 | $explodePath[$total - 1] = $this->metadataFolder; 62 | 63 | array_push($explodePath, $this->fileName); 64 | 65 | $this->pathToWrite = implode('/', $explodePath); 66 | } 67 | 68 | /** 69 | * Abre um certificado enviado com a senha informada 70 | * @param string $password A senha necessária para abrir o certificado 71 | * @return array Com os dados extraidos do certificado 72 | * @throws CannotOpenCertificate Caso a senha do certificado for inválida 73 | * @since 1.0.0 74 | */ 75 | public function open($password) 76 | { 77 | $key = file_get_contents($this->filePath); 78 | $dataCertificate = array(); 79 | if (!openssl_pkcs12_read($key, $dataCertificate, $password)) { 80 | throw new CannotOpenCertificate($this->filePath); 81 | } 82 | 83 | return $dataCertificate; 84 | } 85 | 86 | /** 87 | * Método utilizado para inserir um determinado conteúdo em um arquivo com os dados 88 | * extraídos do certificado 89 | * @param string $content Conteúdo desejado a ser escrito no arquivo 90 | * @param \Sped\Gnre\Configuration\FilePrefix $filePrefix 91 | * @throws UnableToWriteFile Caso não seja possível escrever no arquivo 92 | * @return string Retorna o caminho completo do arquivo em que foi escrito o conteúdo enviado 93 | * @since 1.0.0 94 | */ 95 | public function writeFile($content, FilePrefix $filePrefix) 96 | { 97 | $pathToWrite = $filePrefix->apply($this->pathToWrite); 98 | 99 | if (!file_put_contents($pathToWrite, $content)) { 100 | throw new UnableToWriteFile($this->pathToWrite); 101 | } 102 | 103 | return $pathToWrite; 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Configuration/FileOperation.php: -------------------------------------------------------------------------------- 1 | 27 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 28 | * @version 1.0.0 29 | */ 30 | abstract class FileOperation 31 | { 32 | 33 | /** 34 | * Caminho em que o certificado físico está alocado 35 | * @var string 36 | */ 37 | protected $filePath; 38 | 39 | /** 40 | * Define o caminho absoluto de um arquivo para que a classe trabalhe 41 | * corretamente com seus métodos 42 | * @param string $filePath caminho do arquivo a ser utilizado 43 | * @throws \Sped\Gnre\Exception\UnreachableFile Caso não seja encontrado o arquivo informado 44 | * @since 1.0.0 45 | */ 46 | public function __construct($filePath) 47 | { 48 | if (!file_exists($filePath)) { 49 | throw new UnreachableFile($filePath); 50 | } 51 | 52 | $this->filePath = $filePath; 53 | } 54 | 55 | /** 56 | * Método utilizado para escrever em um arquivo 57 | * @abstract 58 | * @param string $content Conteúdo desejado para ser escrito em um arquivo 59 | * @param FilePrefix Utilizado para aplicar algum prefixo ou regras em um determinado arquivo 60 | * @since 1.0.0 61 | */ 62 | abstract public function writeFile($content, FilePrefix $filePrefix); 63 | } 64 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Configuration/FilePrefix.php: -------------------------------------------------------------------------------- 1 | 26 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 27 | * @version 1.0.0 28 | */ 29 | class FilePrefix 30 | { 31 | 32 | /** 33 | * Armazena o prefixo desejado para ser aplicado no nome do arquivo 34 | * @var string 35 | */ 36 | private $prefix; 37 | 38 | /** 39 | * Define o prefixo desejado para ser aplicado no nome do arquivo 40 | * @param string $prefix Nome do prefixo por exemplo _private, _public etc 41 | * @since 1.0.0 42 | */ 43 | public function setPrefix($prefix) 44 | { 45 | $this->prefix = $prefix; 46 | } 47 | 48 | /** 49 | * Aplica o prefixo desejado no arquivo caso ele exista 50 | * @param string $path O caminho completo junto com o nome do arquivo por exemplo /var/foo/arquivo.tmp 51 | * @return string O novo nome do arquivo e seu caminho completo 52 | * @since 1.0.0 53 | */ 54 | public function apply($path) 55 | { 56 | if (empty($this->prefix)) { 57 | return $path; 58 | } 59 | 60 | $arrayPath = explode('/', $path); 61 | $nameFilePosition = count($arrayPath) - 1; 62 | 63 | $fileName = $arrayPath[count($arrayPath) - 1]; 64 | $arrayFileName = explode('.', $fileName); 65 | 66 | $extension = $arrayFileName[1]; 67 | $singleFileName = $arrayFileName[0]; 68 | 69 | $arrayPath[$nameFilePosition] = $singleFileName . $this->prefix . '.' . $extension; 70 | 71 | $finalPath = implode('/', $arrayPath); 72 | 73 | return $finalPath; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Configuration/Setup.php: -------------------------------------------------------------------------------- 1 | 30 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 31 | * @version 1.0.0 32 | */ 33 | abstract class Setup 34 | { 35 | 36 | /** 37 | * Define o modo de debug, geralmente utilizado para ver dados da requisição e resposta 38 | * da comunicação com o webservice 39 | * @var bool 40 | */ 41 | protected $debug = false; 42 | 43 | /** 44 | * Método utilizado para retornar o número do ambiente em que se deseja 45 | * realizar a conexão com o webservice da sefaz 1 - Produção 2 - Homologação 46 | * @abstract 47 | * @since 1.0.0 48 | * @return int 49 | */ 50 | abstract public function getEnvironment(); 51 | 52 | /** 53 | * Método utilizado para retornar o diretório onde se encontram os certificados 54 | * que seram utilizados 55 | * @abstract 56 | * @since 1.0.0 57 | * @return string 58 | */ 59 | abstract public function getCertificateDirectory(); 60 | 61 | /** 62 | * Retorna o nome do certificado que será usado junto com sua extenção por exemplo 63 | * certificado_teste.pfx 64 | * @abstract 65 | * @since 1.0.0 66 | * @return string 67 | */ 68 | abstract public function getCertificateName(); 69 | 70 | /** 71 | * Retorna a senha do certificado 72 | * @abstract 73 | * @since 1.0.0 74 | * @return string 75 | */ 76 | abstract public function getCertificatePassword(); 77 | 78 | /** 79 | * Retorna a URL base em que a api se encontra por exemplo http://gnre-api/ 80 | * @abstract 81 | * @since 1.0.0 82 | * @return string 83 | */ 84 | abstract public function getBaseUrl(); 85 | 86 | /** 87 | * Retorna o CNPJ da empresa em que que realizará a emissão da guia para a sefaz 88 | * @abstract 89 | * @since 1.0.0 90 | * @return int 91 | */ 92 | abstract public function getCertificateCnpj(); 93 | 94 | /** 95 | * Retorna o IP do proxy caso a API estaja atrás de um por exemplo 192.168.0.1 96 | * @abstract 97 | * @since 1.0.0 98 | * @return string 99 | */ 100 | abstract public function getProxyIp(); 101 | 102 | /** 103 | * Retorna a porta do servidor de proxy por exemplo 3128 (squid) 104 | * @abstract 105 | * @since 1.0.0 106 | * @return int 107 | */ 108 | abstract public function getProxyPort(); 109 | 110 | /** 111 | * Retorna o usuário do servidor de proxy caso seja necessário a indentificação 112 | * @abstract 113 | * @since 1.0.0 114 | * @return string 115 | */ 116 | abstract public function getProxyUser(); 117 | 118 | /** 119 | * Retorna a senha do usuário do servidor de proxy caso seja necessário a indentificação 120 | * @abstract 121 | * @since 1.0.0 122 | * @return string 123 | */ 124 | abstract public function getProxyPass(); 125 | 126 | /** 127 | * Método que retorna o caminho e o nome do arquivo privado extraido do certificado por exemplo 128 | * /var/www/chave_privada.pem 129 | * @abstract 130 | * @since 1.0.0 131 | * @return string 132 | */ 133 | abstract public function getPrivateKey(); 134 | 135 | /** 136 | * Método que retorna o caminho e o nome do arquivo extraido do certificado por exemplo 137 | * /var/www/certificado_pem.pem 138 | * @abstract 139 | * @since 1.0.0 140 | * @return string 141 | */ 142 | abstract public function getCertificatePemFile(); 143 | 144 | /** 145 | * Método utilizado para retornar o modo de debug 146 | * @return bool 147 | */ 148 | public function getDebug() 149 | { 150 | return $this->debug; 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Exception/CannotOpenCertificate.php: -------------------------------------------------------------------------------- 1 | 25 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 26 | * @version 1.0.0 27 | */ 28 | class CannotOpenCertificate extends \Exception 29 | { 30 | 31 | /** 32 | * Define uma mensagem padrão caso a exceção seja lançada 33 | * @param string $certificate O nome do certificado que está sendo aberto 34 | * @since 1.0.0 35 | */ 36 | public function __construct($certificate) 37 | { 38 | parent::__construct( 39 | 'Não foi possível abrir o certificado ' . $certificate . ' verifique a senha informada', 40 | null, 41 | null 42 | ); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Exception/ConnectionFactoryUnavailable.php: -------------------------------------------------------------------------------- 1 | \Sped\Gnre\Webservice\ConnectionFactory 23 | * @package gnre 24 | * @subpackage exception 25 | * @author Matheus Marabesi 26 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 27 | * @version 1.0.0 28 | */ 29 | class ConnectionFactoryUnavailable extends \Exception 30 | { 31 | 32 | /** 33 | * Define uma mensagem padrão caso a exceção seja lançada 34 | * @since 1.0.0 35 | */ 36 | public function __construct() 37 | { 38 | parent::__construct('Unable to use a valid Sped\Gnre\Webservice\ConnectionFactory', null, null); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Exception/UnableToWriteFile.php: -------------------------------------------------------------------------------- 1 | 26 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 27 | * @version 1.0.0 28 | */ 29 | class UnableToWriteFile extends \Exception 30 | { 31 | 32 | /** 33 | * Define uma mensagem padrão caso a exceção seja lançada 34 | * @param string $file O nome do arquivo em que está tentando escrever/criar 35 | * @since 1.0.0 36 | */ 37 | public function __construct($file) 38 | { 39 | parent::__construct('Não foi possível criar/escrever no arquivo ' . $file, null, null); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Exception/UndefinedProperty.php: -------------------------------------------------------------------------------- 1 | 25 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 26 | * @version 1.0.0 27 | */ 28 | class UndefinedProperty extends \Exception 29 | { 30 | 31 | /** 32 | * Define uma mensagem padrão caso a exceção seja lançada 33 | * @since 1.0.0 34 | */ 35 | public function __construct() 36 | { 37 | parent::__construct('Não foi possível encontrar o atributo desejado na classe', 100, null); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Exception/UnreachableFile.php: -------------------------------------------------------------------------------- 1 | 25 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 26 | * @version 1.0.0 27 | */ 28 | class UnreachableFile extends \Exception 29 | { 30 | 31 | /** 32 | * Define uma mensagem padrão caso a exceção seja lançada 33 | * @param string $file O nome do arquivo que se deseja utilizar 34 | * @since 1.0.0 35 | */ 36 | public function __construct($file) 37 | { 38 | parent::__construct('Não foi possível encontrar o arquivo ' . $file, null, null); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Helper/GnreHelper.php: -------------------------------------------------------------------------------- 1 | 30 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 31 | * @link http://en.wikipedia.org/wiki/Template_method_pattern Template Method Design Pattern 32 | * @version 1.0.0 33 | */ 34 | class GnreHelper 35 | { 36 | 37 | protected static $xmlNf; 38 | 39 | 40 | public function __construct($xmlNf) 41 | { 42 | } 43 | 44 | /** 45 | * Método utilizado para gerar os dados principais da GNRE utilizando os dados encontrados dentro do XML 46 | * 47 | * 48 | * @param string $dadosArquivo

String contendo o xml da NF de venda 49 | * utilizada no SEFAZ

50 | * @since 1.0.0 51 | */ 52 | public static function getGuiaGnre($xmlNf): Guia 53 | { 54 | 55 | $xml = self::parseNf($xmlNf); 56 | $guia = new Guia(); 57 | $guia->c04_docOrigem = $xml->NrNf; 58 | $guia->c28_tipoDocOrigem = $xml->TipoDoc; 59 | $guia->c21_cepEmitente = $xml->CEPEmpresa; 60 | $guia->c16_razaoSocialEmitente = $xml->NmEmpresa; 61 | $guia->c03_idContribuinteEmitente = $xml->NrDocumentoEmpresa; 62 | $guia->c18_enderecoEmitente = $xml->EnderecoEmpresa; 63 | $guia->c19_municipioEmitente = $xml->MunicipioEmpresa; 64 | $guia->c20_ufEnderecoEmitente = $xml->UfEmpresa; 65 | $guia->c17_inscricaoEstadualEmitente = $xml->NrIEEmpresa; 66 | $guia->c22_telefoneEmitente = $xml->TelefoneEmpresa; 67 | $guia->c01_UfFavorecida = $xml->IdUfCliente; 68 | $guia->c35_idContribuinteDestinatario = $xml->NrDocumentoCliente; 69 | $guia->c36_inscricaoEstadualDestinatario = $xml->NrIECliente; 70 | $guia->c37_razaoSocialDestinatario = $xml->NmCliente; 71 | $guia->c38_municipioDestinatario = $xml->MunicipioCliente; 72 | 73 | return $guia; 74 | } 75 | 76 | 77 | public static function parseNf($xmlNf): stdClass 78 | { 79 | $xml = simplexml_load_string($xmlNf); 80 | $parsed = new stdClass(); 81 | 82 | 83 | $parsed->CEPEmpresa = $xml->NFe->infNFe->emit->enderEmit->CEP; 84 | $parsed->EnderecoEmpresa = $xml->NFe->infNFe->emit->enderEmit->xLgr; 85 | $parsed->CdMunicipioEmpresa = $xml->NFe->infNFe->emit->enderEmit->cMun; 86 | $parsed->MunicipioEmpresa = $xml->NFe->infNFe->emit->enderEmit->xMun; 87 | $parsed->UfEmpresa = $xml->NFe->infNFe->emit->enderEmit->UF; 88 | $parsed->TelefoneEmpresa = $xml->NFe->infNFe->emit->enderEmit->fone; 89 | $parsed->NrIEEmpresa = $xml->NFe->infNFe->emit->IE; 90 | $parsed->NmEmpresa = $xml->NFe->infNFe->emit->xNome; 91 | $parsed->NrDocumentoEmpresa = $xml->NFe->infNFe->emit->CNPJ; 92 | 93 | 94 | $parsed->NrDocumentoCliente = $xml->NFe->infNFe->dest->CNPJ ?: $xml->NFe->infNFe->dest->CPF; 95 | $parsed->NrIECliente = $xml->NFe->infNFe->dest->IE; 96 | $parsed->NmCliente = $xml->NFe->infNFe->dest->xNome; 97 | $parsed->NmCidade = $xml->NFe->infNFe->dest->enderDest->xMun; 98 | $parsed->IdUfCliente = $xml->NFe->infNFe->dest->enderDest->UF; 99 | $parsed->CdMunicipioCliente = $xml->NFe->infNFe->dest->enderDest->cMun; 100 | $parsed->MunicipioCliente = $xml->NFe->infNFe->dest->enderDest->xMun; 101 | $parsed->ISUFCliente = $xml->NFe->infNFe->dest->ISUF; 102 | $parsed->TipoDoc = $xml->NFe->infNFe->ide->tpDoc; 103 | $parsed->NrChaveNFe = $xml->protNFe->infProt->chNFe; 104 | $parsed->VlNf = $xml->NFe->infNFe->total->ICMSTot->vNF; 105 | $parsed->NrNf = $xml->NFe->infNFe->ide->nNF; 106 | 107 | return $parsed; 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Parser/Rules.php: -------------------------------------------------------------------------------- 1 | 28 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 29 | * @link http://en.wikipedia.org/wiki/Template_method_pattern Template Method Design Pattern 30 | * @version 1.0.0 31 | */ 32 | abstract class Rules 33 | { 34 | 35 | const ERRO_VALIDACAO = 2; 36 | const GUIA_EMITIDA_COM_SUCESSO = 9; 37 | 38 | /** 39 | * @var string 40 | */ 41 | protected $dadosArquivo; 42 | 43 | /** 44 | * @var int 45 | */ 46 | protected $index; 47 | 48 | /** 49 | * @var int 50 | */ 51 | protected $indentificador; 52 | 53 | /** 54 | * @var string 55 | */ 56 | protected $sequencialGuiaErroValidacao; 57 | 58 | /** 59 | * @var array 60 | */ 61 | protected $lote = array(); 62 | 63 | /** 64 | * Utiliza o método construtor da classe para ser enviado um conteúdo de 65 | * arquivo para ser extraido 66 | * 67 | * @param string $dadosArquivo

String contendo o conteúdo de retorno do 68 | * web service da SEFAZ

69 | * @since 1.0.0 70 | */ 71 | public function __construct($dadosArquivo) 72 | { 73 | $this->dadosArquivo = explode(PHP_EOL, $dadosArquivo); 74 | } 75 | 76 | abstract protected function getTipoIdentificadorDoSolicitante(); 77 | 78 | abstract protected function getIdentificador(); 79 | 80 | abstract protected function getSequencialGuia(); 81 | 82 | abstract protected function getSituacaoGuia(); 83 | 84 | abstract protected function getUfFavorecida(); 85 | 86 | abstract protected function getCodigoReceita(); 87 | 88 | abstract protected function getTipoEmitente(); 89 | 90 | abstract protected function getDocumentoEmitente(); 91 | 92 | abstract protected function getEnderecoEmitente(); 93 | 94 | abstract protected function getMunicipioEmitente(); 95 | 96 | abstract protected function getUFEmitente(); 97 | 98 | abstract protected function getCEPEmitente(); 99 | 100 | abstract protected function getTelefoneEmitente(); 101 | 102 | abstract protected function getTipoDocDestinatario(); 103 | 104 | abstract protected function getDocumentoDestinatario(); 105 | 106 | abstract protected function getMunicipioDestinatario(); 107 | 108 | abstract protected function getProduto(); 109 | 110 | abstract protected function getNumeroDocumentoDeOrigem(); 111 | 112 | abstract protected function getConvenio(); 113 | 114 | abstract protected function getInformacoesComplementares(); 115 | 116 | abstract protected function getDataDeVencimento(); 117 | 118 | abstract protected function getDataLimitePagamento(); 119 | 120 | abstract protected function getPeriodoReferencia(); 121 | 122 | abstract protected function getParcela(); 123 | 124 | abstract protected function getValorPrincipal(); 125 | 126 | abstract protected function getAtualizacaoMonetaria(); 127 | 128 | abstract protected function getJuros(); 129 | 130 | abstract protected function getMulta(); 131 | 132 | abstract protected function getRepresentacaoNumerica(); 133 | 134 | abstract protected function getCodigoBarras(); 135 | 136 | abstract protected function getNumeroDeControle(); 137 | 138 | abstract protected function getIdentificadorGuia(); 139 | 140 | abstract protected function getNumeroProtocolo(); 141 | 142 | abstract protected function getTotalGuias(); 143 | 144 | abstract protected function getHashDeValidacao(); 145 | 146 | abstract protected function getIdentificadorDoSolicitante(); 147 | 148 | abstract protected function getNumeroDoProtocoloDoLote(); 149 | 150 | abstract protected function getAmbiente(); 151 | 152 | abstract protected function getNomeCampo(); 153 | 154 | abstract protected function getCodigoMotivoRejeicao(); 155 | 156 | abstract protected function getDescricaoMotivoRejeicao(); 157 | 158 | abstract protected function aplicarParser(); 159 | 160 | /** 161 | * @return \Sped\Gnre\Sefaz\Lote 162 | */ 163 | public function getLote() 164 | { 165 | $lote = new \Sped\Gnre\Sefaz\Lote(); 166 | 167 | for ($i = 0; $i < sizeof($this->dadosArquivo); $i++) { 168 | $this->index = $i; 169 | $this->getIdentificador(); 170 | $this->sequencialGuiaErroValidacao = null; 171 | 172 | if ($this->identificador == 0) { 173 | $this->getTipoIdentificadorDoSolicitante(); 174 | $this->getIdentificadorDoSolicitante(); 175 | $this->getNumeroDoProtocoloDoLote(); 176 | $this->getAmbiente(); 177 | } elseif ($this->identificador == 1) { 178 | $this->lote['lote'][$i] = new \Sped\Gnre\Sefaz\Guia(); 179 | 180 | $this->getSequencialGuia(); 181 | $this->getSituacaoGuia(); 182 | $this->getUfFavorecida(); 183 | $this->getCodigoReceita(); 184 | $this->getTipoEmitente(); 185 | $this->getDocumentoEmitente(); 186 | $this->getEnderecoEmitente(); 187 | $this->getMunicipioEmitente(); 188 | $this->getUFEmitente(); 189 | $this->getCEPEmitente(); 190 | $this->getTelefoneEmitente(); 191 | $this->getTipoDocDestinatario(); 192 | $this->getDocumentoDestinatario(); 193 | $this->getMunicipioDestinatario(); 194 | $this->getProduto(); 195 | $this->getNumeroDocumentoDeOrigem(); 196 | $this->getConvenio(); 197 | $this->getInformacoesComplementares(); 198 | $this->getDataDeVencimento(); 199 | $this->getDataLimitePagamento(); 200 | $this->getPeriodoReferencia(); 201 | $this->getParcela(); 202 | $this->getValorPrincipal(); 203 | $this->getAtualizacaoMonetaria(); 204 | $this->getJuros(); 205 | $this->getMulta(); 206 | $this->getRepresentacaoNumerica(); 207 | $this->getCodigoBarras(); 208 | $this->getNumeroDeControle(); 209 | $this->getIdentificadorGuia(); 210 | 211 | $lote->addGuia($this->lote['lote'][$i]); 212 | } elseif ($this->identificador == self::GUIA_EMITIDA_COM_SUCESSO) { 213 | $this->getNumeroProtocolo(); 214 | $this->getTotalGuias(); 215 | $this->getHashDeValidacao(); 216 | } elseif ($this->identificador == self::ERRO_VALIDACAO) { 217 | $this->getSequencialGuiaErroValidacao(); 218 | $this->getNomeCampo(); 219 | $this->getCodigoMotivoRejeicao(); 220 | $this->getDescricaoMotivoRejeicao(); 221 | } 222 | } 223 | 224 | $this->aplicarParser(); 225 | 226 | return $lote; 227 | } 228 | 229 | /** 230 | * Esse método é mais utilizado pelas classes filhas onde é necessário 231 | * pegar uma parte do conteúdo baseado em uma string 232 | * @see \Sped\Gnre\Parser\SefazRetorno 233 | * @param string $content 234 | * @param int $positionStart 235 | * @param int $length 236 | * @return string 237 | */ 238 | public function getContent($content, $positionStart, $length) 239 | { 240 | return substr($content, $positionStart, $length); 241 | } 242 | } 243 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Render/Barcode128.php: -------------------------------------------------------------------------------- 1 | 25 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 26 | * @version 1.0.0 27 | */ 28 | class Barcode128 29 | { 30 | 31 | /** 32 | * Propriedade utilizada para armazenar o código de barras 33 | * @var int 34 | */ 35 | private $numeroCodigoBarras; 36 | 37 | /** 38 | * Retorna o número de código de barras definido 39 | * @return mixed

Se o código de barras for definido retorna o mesmo, 40 | * caso contrário é retornado null

41 | */ 42 | public function getNumeroCodigoBarras() 43 | { 44 | return $this->numeroCodigoBarras; 45 | } 46 | 47 | /** 48 | * Define o código de barras a ser usado pela classe 49 | * @param int $numeroCodigoBarras 50 | * @return \Sped\Gnre\Render\Barcode128 51 | */ 52 | public function setNumeroCodigoBarras($numeroCodigoBarras) 53 | { 54 | $this->numeroCodigoBarras = $numeroCodigoBarras; 55 | return $this; 56 | } 57 | 58 | /** 59 | * Gera a imagem do código de barras e o transforma em base64 60 | * @return string Retorna a imagem gerada no formato base64 61 | */ 62 | public function getCodigoBarrasBase64() 63 | { 64 | ob_start(); 65 | 66 | $text = $this->getNumeroCodigoBarras(); 67 | $options = array( 68 | 'text' => (string) $text, 69 | 'imageType' => 'jpeg', 70 | 'drawText' => false 71 | ); 72 | 73 | $barcode = new \Laminas\Barcode\Object\Code128(); 74 | $barcode->setOptions($options); 75 | 76 | $barcodeOBj = \Laminas\Barcode\Barcode::factory($barcode); 77 | 78 | $imageResource = $barcodeOBj->draw(); 79 | 80 | imagejpeg($imageResource); 81 | 82 | $contents = ob_get_contents(); 83 | ob_end_clean(); 84 | 85 | return base64_encode($contents); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Render/Html.php: -------------------------------------------------------------------------------- 1 | 29 | * @author Matheus Marabesi 30 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 31 | * @version 1.0.0 32 | */ 33 | class Html 34 | { 35 | 36 | /** 37 | * Conteúdo HTML gerado pela classe 38 | * @var string 39 | */ 40 | private $html; 41 | 42 | /** 43 | * Objeto utilizado para gerar o código de barras 44 | * @var \Sped\Gnre\Render\Barcode128 45 | */ 46 | private $barCode; 47 | 48 | /** 49 | * @var type 50 | */ 51 | private $smartyFactory; 52 | 53 | /** 54 | * Retorna a instância do objeto atual ou cria uma caso não exista 55 | * @return \Sped\Gnre\Render\Barcode128 56 | */ 57 | public function getBarCode() 58 | { 59 | if (!$this->barCode instanceof Barcode128) { 60 | $this->barCode = new Barcode128(); 61 | } 62 | 63 | return $this->barCode; 64 | } 65 | 66 | /** 67 | * Define um objeto \Sped\Gnre\Render\Barcode128 para ser utilizado 68 | * internamente pela classe 69 | * @param \Sped\Gnre\Render\Barcode128 $barCode 70 | * @return \Sped\Gnre\Render\Html 71 | */ 72 | public function setBarCode(Barcode128 $barCode) 73 | { 74 | $this->barCode = $barCode; 75 | return $this; 76 | } 77 | 78 | public function setSmartyFactory(\Sped\Gnre\Render\SmartyFactory $smartyFactory) 79 | { 80 | $this->smartyFactory = $smartyFactory; 81 | return $this; 82 | } 83 | 84 | /** 85 | * Retorna uma factory para ser possível utilizar o Smarty 86 | * @return Sped\Gnre\Render\SmartyFactory 87 | */ 88 | public function getSmartyFactory() 89 | { 90 | if ($this->smartyFactory === null) { 91 | $this->smartyFactory = new SmartyFactory(); 92 | } 93 | 94 | return $this->smartyFactory; 95 | } 96 | 97 | /** 98 | * Utiliza o lote como parâmetro para transforma-lo em uma guia HTML 99 | * @param \Sped\Gnre\Sefaz\Lote $lote 100 | * @link https://github.com/marabesi/gnrephp/blob/dev-pdf/exemplos/guia.jpg

101 | * Exemplo de como é transformado o objeto \Sped\Gnre\Sefaz\Lote após ser 102 | * utilizado por esse método

103 | * @since 1.0.0 104 | */ 105 | public function create(Lote $lote) 106 | { 107 | $guiaViaInfo = array( 108 | 1 => '1ª via Banco', 109 | 2 => '2ª via Contrinuinte', 110 | 3 => '3ª via Contribuinte/Fisco' 111 | ); 112 | 113 | $guias = $lote->getGuias(); 114 | $html = ''; 115 | 116 | for ($index = 0; $index < count($guias); $index++) { 117 | $guia = $lote->getGuia($index); 118 | 119 | $barcode = $this->getBarCode() 120 | ->setNumeroCodigoBarras($guia->retornoCodigoDeBarras); 121 | 122 | $smarty = $this->getSmartyFactory() 123 | ->create(); 124 | $smarty->assign('guiaViaInfo', $guiaViaInfo); 125 | $smarty->assign('barcode', $barcode); 126 | $smarty->assign('guia', $guia); 127 | 128 | $documentRoot = dirname(dirname(dirname(dirname(dirname(__FILE__))))) . DIRECTORY_SEPARATOR ; 129 | 130 | $html .= $smarty->fetch($documentRoot . 'templates' . DIRECTORY_SEPARATOR . 'gnre.tpl'); 131 | } 132 | 133 | $this->html = $html; 134 | } 135 | 136 | /** 137 | * Retorna o conteúdo HTML gerado pela classe 138 | * @return string 139 | */ 140 | public function getHtml() 141 | { 142 | return $this->html; 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Render/Pdf.php: -------------------------------------------------------------------------------- 1 | 28 | * @author Matheus Marabesi 29 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 30 | * @version 1.0.0 31 | */ 32 | class Pdf 33 | { 34 | 35 | /** 36 | * Método criado para ser possível testar a utilização do objeto 37 | * Dompdf pela classe 38 | * @return \Dompdf\Dompdf 39 | */ 40 | protected function getDomPdf() 41 | { 42 | return new Dompdf(); 43 | } 44 | 45 | /** 46 | * Gera o PDF através do HTML 47 | * @param \Sped\Gnre\Render\Html $html 48 | * @return \Dompdf\Dompdf 49 | */ 50 | public function create(Html $html) 51 | { 52 | $dompdf = $this->getDomPdf(); 53 | $dompdf->load_html($html->getHtml()); 54 | $dompdf->render(); 55 | 56 | return $dompdf; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Render/SmartyFactory.php: -------------------------------------------------------------------------------- 1 | \Smarty e definir 22 | * algumas configurações padrões para o objeto 23 | * @package gnre 24 | * @author Matheus Marabesi 25 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 26 | * @version 1.0.0 27 | */ 28 | class SmartyFactory 29 | { 30 | 31 | /** 32 | * Cria um objeto smarty com o diretório padrão /root/templates para 33 | * os templates e utiliza o diretório temporário padrão 34 | * do sistema operacional para definir o diretório que os arquivos 35 | * compilados pelo smarty serão salvos 36 | * @return \Smarty 37 | */ 38 | public function create() 39 | { 40 | $documentRoot = getenv('DOCUMENT_ROOT') . DIRECTORY_SEPARATOR; 41 | 42 | $smarty = new \Smarty(); 43 | $smarty->caching = false; 44 | $smarty->setTemplateDir($documentRoot . 'templates'); 45 | $smarty->setCompileDir(sys_get_temp_dir()); 46 | 47 | return $smarty; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Sefaz/ConfigUf.php: -------------------------------------------------------------------------------- 1 | 26 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 27 | * @version 1.0.0 28 | */ 29 | class ConfigUf extends ConsultaConfigUf 30 | { 31 | 32 | /** 33 | * @var int 34 | */ 35 | private $ambienteDeTeste = false; 36 | 37 | /** 38 | * Retorna o header da requisição SOAP 39 | * @return array 40 | */ 41 | public function getHeaderSoap() 42 | { 43 | $action = $this->ambienteDeTeste ? 44 | 'http://www.testegnre.pe.gov.br/webservice/GnreConfigUF' : 45 | 'http://www.gnre.pe.gov.br/webservice/GnreConfigUF'; 46 | 47 | return array( 48 | 'Content-Type: application/soap+xml;charset=utf-8;action="' . $action . '"', 49 | 'SOAPAction: consultar' 50 | ); 51 | } 52 | 53 | /** 54 | * Retorna a action da requisição SOAP 55 | * @return string 56 | */ 57 | public function soapAction() 58 | { 59 | return $this->ambienteDeTeste ? 60 | 'https://www.testegnre.pe.gov.br/gnreWS/services/GnreConfigUF' : 61 | 'https://www.gnre.pe.gov.br/gnreWS/services/GnreConfigUF'; 62 | } 63 | 64 | /** 65 | * Retorna o XML que será enviado na requisição SOAP 66 | * @return string 67 | */ 68 | public function toXml() 69 | { 70 | $gnre = new \DOMDocument('1.0', 'UTF-8'); 71 | $gnre->formatOutput = false; 72 | $gnre->preserveWhiteSpace = false; 73 | 74 | $consulta = $gnre->createElement('TConsultaConfigUf'); 75 | $consulta->setAttribute('xmlns', 'http://www.gnre.pe.gov.br'); 76 | 77 | $ambiente = $gnre->createElement('ambiente', $this->getEnvironment()); 78 | $estado = $gnre->createElement('uf', $this->getEstado()); 79 | $receita = $gnre->createElement('receita', $this->getReceita()); 80 | 81 | $consulta->appendChild($ambiente); 82 | $consulta->appendChild($estado); 83 | $consulta->appendChild($receita); 84 | 85 | $this->getSoapEnvelop($gnre, $consulta); 86 | 87 | return $gnre->saveXML(); 88 | } 89 | 90 | /** 91 | * Retorna o envelope que sera enviado na requisicao SOAP 92 | * @return string 93 | */ 94 | public function getSoapEnvelop($gnre, $consulta) 95 | { 96 | $soapEnv = $gnre->createElement('soap12:Envelope'); 97 | $soapEnv->setAttribute('xmlns:soap12', 'http://www.w3.org/2003/05/soap-envelope'); 98 | $soapEnv->setAttribute('xmlns:gnr', 'http://www.gnre.pe.gov.br/webservice/GnreConfigUF'); 99 | 100 | $gnreCabecalhoSoap = $gnre->createElement('gnr:gnreCabecMsg'); 101 | $gnreCabecalhoSoap->appendChild($gnre->createElement('gnr:versaoDados', '1.00')); 102 | 103 | $soapHeader = $gnre->createElement('soap12:Header'); 104 | $soapHeader->appendChild($gnreCabecalhoSoap); 105 | 106 | $soapEnv->appendChild($soapHeader); 107 | $gnre->appendChild($soapEnv); 108 | 109 | $gnreDadosMsg = $gnre->createElement('gnr:gnreDadosMsg'); 110 | $gnreDadosMsg->appendChild($consulta); 111 | 112 | $soapBody = $gnre->createElement('soap12:Body'); 113 | $soapBody->appendChild($gnreDadosMsg); 114 | 115 | $soapEnv->appendChild($soapBody); 116 | } 117 | 118 | /** 119 | * Define se será utilizado o ambiente de testes ou não 120 | * @param boolean $ambiente Ambiente 121 | */ 122 | public function utilizarAmbienteDeTeste($ambiente = false) 123 | { 124 | $this->ambienteDeTeste = $ambiente; 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Sefaz/Consulta.php: -------------------------------------------------------------------------------- 1 | 28 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 29 | * @version 1.0.0 30 | */ 31 | class Consulta extends ConsultaGnre 32 | { 33 | 34 | /** 35 | * @var bool 36 | */ 37 | private $ambienteDeTeste = false; 38 | 39 | /** 40 | * {@inheritdoc} 41 | */ 42 | public function getHeaderSoap() 43 | { 44 | $action = $this->ambienteDeTeste ? 45 | 'http://www.testegnre.pe.gov.br/webservice/GnreResultadoLote' : 46 | 'http://www.gnre.pe.gov.br/webservice/GnreResultadoLote'; 47 | 48 | return array( 49 | 'Content-Type: application/soap+xml;charset=utf-8;action="' . $action . '"', 50 | 'SOAPAction: consultar' 51 | ); 52 | } 53 | 54 | /** 55 | * {@inheritdoc} 56 | */ 57 | public function soapAction() 58 | { 59 | return $this->ambienteDeTeste ? 60 | 'https://www.testegnre.pe.gov.br/gnreWS/services/GnreResultadoLote' : 61 | 'https://www.gnre.pe.gov.br/gnreWS/services/GnreResultadoLote'; 62 | } 63 | 64 | /** 65 | * {@inheritdoc} 66 | */ 67 | public function toXml() 68 | { 69 | $gnre = new \DOMDocument('1.0', 'UTF-8'); 70 | $gnre->formatOutput = false; 71 | $gnre->preserveWhiteSpace = false; 72 | 73 | $consulta = $gnre->createElement('TConsLote_GNRE'); 74 | $consulta->setAttribute('xmlns', 'http://www.gnre.pe.gov.br'); 75 | 76 | $ambiente = $gnre->createElement('ambiente', $this->getEnvironment()); 77 | $numeroRecibo = $gnre->createElement('numeroRecibo', $this->getRecibo()); 78 | 79 | $consulta->appendChild($ambiente); 80 | $consulta->appendChild($numeroRecibo); 81 | 82 | $this->getSoapEnvelop($gnre, $consulta); 83 | 84 | return $gnre->saveXML(); 85 | } 86 | 87 | /** 88 | * {@inheritdoc} 89 | */ 90 | public function getSoapEnvelop($gnre, $consulta) 91 | { 92 | $soapEnv = $gnre->createElement('soap12:Envelope'); 93 | $soapEnv->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); 94 | $soapEnv->setAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema'); 95 | $soapEnv->setAttribute('xmlns:soap12', 'http://www.w3.org/2003/05/soap-envelope'); 96 | 97 | $gnreCabecalhoSoap = $gnre->createElement('gnreCabecMsg'); 98 | $gnreCabecalhoSoap->setAttribute('xmlns', 'http://www.gnre.pe.gov.br/wsdl/consultar'); 99 | $gnreCabecalhoSoap->appendChild($gnre->createElement('versaoDados', '1.00')); 100 | 101 | $soapHeader = $gnre->createElement('soap12:Header'); 102 | $soapHeader->appendChild($gnreCabecalhoSoap); 103 | 104 | $soapEnv->appendChild($soapHeader); 105 | $gnre->appendChild($soapEnv); 106 | 107 | $action = $this->ambienteDeTeste ? 108 | 'http://www.testegnre.pe.gov.br/webservice/GnreResultadoLote' : 109 | 'http://www.gnre.pe.gov.br/webservice/GnreResultadoLote'; 110 | 111 | $gnreDadosMsg = $gnre->createElement('gnreDadosMsg'); 112 | $gnreDadosMsg->setAttribute('xmlns', $action); 113 | 114 | $gnreDadosMsg->appendChild($consulta); 115 | 116 | $soapBody = $gnre->createElement('soap12:Body'); 117 | $soapBody->appendChild($gnreDadosMsg); 118 | 119 | $soapEnv->appendChild($soapBody); 120 | } 121 | 122 | /** 123 | * {@inheritdoc} 124 | */ 125 | public function utilizarAmbienteDeTeste($ambiente = false) 126 | { 127 | $this->ambienteDeTeste = $ambiente; 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Sefaz/ConsultaConfigUf.php: -------------------------------------------------------------------------------- 1 | 26 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 27 | * @version 1.0.0 28 | */ 29 | abstract class ConsultaConfigUf implements ObjetoSefaz 30 | { 31 | 32 | /** 33 | * O número representa qual ambiente deve ser realizada a consulta 34 | * 1 - produção 2 - homologação 35 | * @var int 36 | */ 37 | private $environment; 38 | 39 | /** 40 | * UF do estado 41 | * @var string 42 | */ 43 | private $estado; 44 | 45 | /** 46 | * Código da receita 47 | * @var int 48 | */ 49 | private $receita; 50 | 51 | /** 52 | * Retorna a UF que deve ser consultada 53 | * @return string 54 | */ 55 | public function getEstado() 56 | { 57 | return $this->estado; 58 | } 59 | 60 | /** 61 | * Define a UF que deve ser consultada 62 | * @param string $uf UF 63 | */ 64 | public function setEstado($estado) 65 | { 66 | $this->estado = $estado; 67 | } 68 | 69 | /** 70 | * Retorna a receita que deve ser consultada 71 | * @return int 72 | */ 73 | public function getReceita() 74 | { 75 | return $this->receita; 76 | } 77 | 78 | /** 79 | * Define a receita que deve ser consultada 80 | * @param int $receita Código da receita 81 | */ 82 | public function setReceita($receita) 83 | { 84 | $this->receita = $receita; 85 | } 86 | 87 | /** 88 | * Retorna em qual ambiente deve ser consultado 89 | * @return int 90 | */ 91 | public function getEnvironment() 92 | { 93 | return $this->environment; 94 | } 95 | 96 | /** 97 | * Define em qual ambiente deve ser consultado 98 | * @param int $environment O número do ambiente que se deseja consultar. 1 = produção - 2 = homologação 99 | */ 100 | public function setEnvironment($environment) 101 | { 102 | $this->environment = $environment; 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Sefaz/ConsultaGnre.php: -------------------------------------------------------------------------------- 1 | 29 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 30 | * @version 1.0.0 31 | */ 32 | abstract class ConsultaGnre implements ObjetoSefaz 33 | { 34 | 35 | /** 36 | * O número que representa em qual ambiente sera realizada a consulta 37 | * 1 - produção 2 - homologação 38 | * @var int 39 | */ 40 | private $environment; 41 | 42 | /** 43 | * O número do recibo enviado apos um lote recebido com sucesso pelo webservice 44 | * da sefaz geralmente com 10 posições (1406670518) 45 | * @var int 46 | */ 47 | private $recibo; 48 | 49 | /** 50 | * Retorna o número de recibo armazenado no atributo interno da classe 51 | * @since 1.0.0 52 | * @return int 53 | */ 54 | public function getRecibo() 55 | { 56 | return $this->recibo; 57 | } 58 | 59 | /** 60 | * Define um número de recibo para ser utilizado na consulta ao 61 | * webservice da sefaz 62 | * @param int $recibo Número retornado pelo webservice da sefaz após ter recebido um lote com sucesso 63 | * @since 1.0.0 64 | */ 65 | public function setRecibo($recibo) 66 | { 67 | $this->recibo = $recibo; 68 | } 69 | 70 | /** 71 | * Retorna o valor do ambiente armazenado no atributo interno na classe 72 | * @return int 73 | * @since 1.0.0 74 | */ 75 | public function getEnvironment() 76 | { 77 | return $this->environment; 78 | } 79 | 80 | /** 81 | * Define o ambiente desejado para realizar a consulta no webservice da sefaz 82 | * @param int $environment O número do ambiente que se deseja consultar. 1 = produção e 2 = homologação 83 | * @since 1.0.0 84 | */ 85 | public function setEnvironment($environment) 86 | { 87 | $this->environment = $environment; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Sefaz/EstadoFactory.php: -------------------------------------------------------------------------------- 1 | c39_camposExtras) && count($gnreGuia->c39_camposExtras) > 0) { 33 | $c39_camposExtras = $gnre->createElement('c39_camposExtras'); 34 | 35 | foreach ($gnreGuia->c39_camposExtras as $key => $campos) { 36 | $campoExtra = $gnre->createElement('campoExtra'); 37 | $codigo = $gnre->createElement('codigo', $campos['campoExtra']['codigo']); 38 | $tipo = $gnre->createElement('tipo', $campos['campoExtra']['tipo']); 39 | $valor = $gnre->createElement('valor', $campos['campoExtra']['valor']); 40 | 41 | $campoExtra->appendChild($codigo); 42 | $campoExtra->appendChild($tipo); 43 | $campoExtra->appendChild($valor); 44 | 45 | $c39_camposExtras->appendChild($campoExtra); 46 | } 47 | 48 | return $c39_camposExtras; 49 | } 50 | 51 | return null; 52 | } 53 | 54 | /** 55 | * @param \DOMDocument $gnre 56 | * @param \Sped\Gnre\Sefaz\Guia $gnreGuia 57 | * @return \DOMElement 58 | */ 59 | public function getNodeReferencia(\DOMDocument $gnre, Guia $gnreGuia) 60 | { 61 | if (!$gnreGuia->periodo && !$gnreGuia->mes && !$gnreGuia->ano && !$gnreGuia->parcela) { 62 | return null; 63 | } 64 | 65 | $c05 = $gnre->createElement('c05_referencia'); 66 | 67 | if ($gnreGuia->periodo) { 68 | $periodo = $gnre->createElement('periodo', $gnreGuia->periodo); 69 | } 70 | $mes = $gnre->createElement('mes', $gnreGuia->mes); 71 | $ano = $gnre->createElement('ano', $gnreGuia->ano); 72 | if ($gnreGuia->parcela) { 73 | $parcela = $gnre->createElement('parcela', $gnreGuia->parcela); 74 | } 75 | 76 | if (isset($periodo)) { 77 | $c05->appendChild($periodo); 78 | } 79 | $c05->appendChild($mes); 80 | $c05->appendChild($ano); 81 | if (isset($parcela)) { 82 | $c05->appendChild($parcela); 83 | } 84 | 85 | return $c05; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Sefaz/LoteGnre.php: -------------------------------------------------------------------------------- 1 | 29 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 30 | * @version 1.0.0 31 | */ 32 | abstract class LoteGnre implements ObjetoSefaz 33 | { 34 | 35 | const EMITENTE_PESSOA_JURIDICA = 1; 36 | const DESTINATARIO_PESSOA_JURIDICA = 1; 37 | 38 | /** 39 | * Atributo que armazenará todas as guias desejadas 40 | * @var array 41 | */ 42 | private $guias = array(); 43 | 44 | /** 45 | * Método utilizado para armazenar a guia desejada na classe 46 | * @param \Sped\Gnre\Sefaz\Guia $guia Para armazenar uma guia com sucesso é necessário 47 | * enviar um objeto do tipo Guia 48 | * @since 1.0.0 49 | */ 50 | public function addGuia(Guia $guia) 51 | { 52 | $this->guias[] = $guia; 53 | } 54 | 55 | /** 56 | * Método utilizado para retornar todas as guias existentes no lote 57 | * @return array 58 | * @since 1.0.0 59 | */ 60 | public function getGuias(): array 61 | { 62 | return $this->guias; 63 | } 64 | 65 | /** 66 | * Método utilizado para retornar uma guia específica existente no lote 67 | * @param int $index 68 | * @return Guia 69 | * @since 1.0.0 70 | */ 71 | public function getGuia($index) 72 | { 73 | return $this->guias[$index]; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Sefaz/ObjetoSefaz.php: -------------------------------------------------------------------------------- 1 | 26 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 27 | * @version 1.0.0 28 | */ 29 | interface ObjetoSefaz 30 | { 31 | 32 | /** 33 | * Retorna em um formato de array os cabeçalhos necessários para a comunicação com o webservice da SEFAZ. 34 | * Esses cabeçalhos são diferentes para cada tipo de ação no webservice de destino 35 | * @since 1.0.0 36 | * @return array 37 | */ 38 | public function getHeaderSoap(); 39 | 40 | /** 41 | * Retorna uma string com a ação SOAP que será enviada ao webservice para ser executada 42 | * @since 1.0.0 43 | * @return string Retorna uma string com o nome da ação que será executa pelo webservice 44 | */ 45 | public function soapAction(); 46 | 47 | /** 48 | * Método que transforma o objeto que sera enviado para o webservice em XML (O tipo de dado aceito pelo webservice) 49 | * @return string Uma string contendo todo o XML gerado 50 | * @since 1.0.0 51 | * @return string Uma string XML contendo um documento XML formatado 52 | */ 53 | public function toXml(); 54 | 55 | /** 56 | * Método responsável por encapsular todo o XML gerado e encapsula-lo dentro 57 | * de um envelop SOAP válido para ser enviado 58 | * @return mixed 59 | */ 60 | public function getSoapEnvelop($noRaiz, $conteudoEnvelope); 61 | 62 | /** 63 | * Define se a requisição será realizada no ambiente de testes ou não 64 | * @param boolen $ambiente Define se será utilizado o ambiente de teste ou não, o padrão é false(para 65 | * não usar o ambiente de testes) 66 | * @return mixed 67 | */ 68 | public function utilizarAmbienteDeTeste($ambiente = false); 69 | } 70 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Sefaz/Send.php: -------------------------------------------------------------------------------- 1 | 32 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 33 | * @version 1.0.0 34 | */ 35 | class Send 36 | { 37 | 38 | /** 39 | * As configuraçoes definidas pelo usuarios que sera utilizada para a 40 | * transmissao dos dados 41 | * @var \Sped\Gnre\Configuration\Setup 42 | */ 43 | private $setup; 44 | 45 | /** 46 | * Propriedade utilizada para armazenar o objecto de conexão com a SEFAZ 47 | * @var \Sped\Gnre\Webservice\ConnectionFactory 48 | */ 49 | private $connectionFactory; 50 | 51 | /** 52 | * Armazena as configurações padrões em um atributo interno da classe para ser utilizado 53 | * posteriormente pela classe 54 | * @param \Sped\Gnre\Configuration\Setup $setup Configuraçoes definidas pelo usuário 55 | * @since 1.0.0 56 | */ 57 | public function __construct(Setup $setup) 58 | { 59 | $this->setup = $setup; 60 | } 61 | 62 | /** 63 | * Retorna o objeto de conexão com a SEFAZ 64 | * @return \Sped\Gnre\Webservice\ConnectionFactory 65 | * @throws \Sped\Gnre\Exception\ConnectionFactoryUnavailable 66 | */ 67 | public function getConnectionFactory() 68 | { 69 | if (!$this->connectionFactory instanceof ConnectionFactory) { 70 | throw new ConnectionFactoryUnavailable(); 71 | } 72 | 73 | return $this->connectionFactory; 74 | } 75 | 76 | /** 77 | * Define um objeto de comunicação com a SEFAZ 78 | * @param \Sped\Gnre\Webservice\ConnectionFactory $connectionFactory 79 | * @return \Sped\Gnre\Sefaz\Send 80 | */ 81 | public function setConnectionFactory(ConnectionFactory $connectionFactory) 82 | { 83 | $this->connectionFactory = $connectionFactory; 84 | return $this; 85 | } 86 | 87 | /** 88 | * Obtém os dados necessários e realiza a conexão com o webservice da sefaz 89 | * @param $objetoSefaz Uma classe que implemente a interface ObjectoSefaz 90 | * @return string|boolean Caso a conexão seja feita com sucesso retorna um xml válido caso contrário retorna false 91 | * @since 1.0.0 92 | */ 93 | public function sefaz(ObjetoSefaz $objetoSefaz) 94 | { 95 | $data = $objetoSefaz->toXml(); 96 | $header = $objetoSefaz->getHeaderSoap(); 97 | 98 | if ($this->setup->getDebug()) { 99 | print $data; 100 | } 101 | 102 | $connection = $this->getConnectionFactory()->createConnection($this->setup, $header, $data); 103 | 104 | return $connection->doRequest($objetoSefaz->soapAction()); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Webservice/Connection.php: -------------------------------------------------------------------------------- 1 | 29 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 30 | * @version 1.0.0 31 | */ 32 | class Connection 33 | { 34 | 35 | /** 36 | * Armazena todas as opções desejadas para serem incluídas no curl() 37 | * @var array 38 | */ 39 | private $curlOptions = array(); 40 | 41 | /** 42 | * @var \Sped\Gnre\Configuration\Setup 43 | */ 44 | private $setup; 45 | 46 | /** 47 | * Inicia os parâmetros com o curl para se comunicar com o webservice da SEFAZ. 48 | * São setadas a URL de acesso o certificado que será usado e uma série de parâmetros 49 | * para a header do curl e caso seja usado proxy esse método o adiciona 50 | * @param \Sped\Gnre\Configuration\Interfaces\Setup $setup 51 | * @param $headers array 52 | * @param $data string 53 | * @since 1.0.0 54 | */ 55 | public function __construct(Setup $setup, $headers, $data) 56 | { 57 | $this->setup = $setup; 58 | 59 | $this->curlOptions = array( 60 | CURLOPT_PORT => 443, 61 | CURLOPT_VERBOSE => 1, 62 | CURLOPT_HEADER => 1, 63 | CURLOPT_SSLVERSION => 3, 64 | CURLOPT_SSL_VERIFYHOST => 0, 65 | CURLOPT_SSL_VERIFYPEER => 0, 66 | CURLOPT_SSLCERT => $setup->getCertificatePemFile(), 67 | CURLOPT_SSLKEY => $setup->getPrivateKey(), 68 | CURLOPT_POST => 1, 69 | CURLOPT_RETURNTRANSFER => 1, 70 | CURLOPT_POSTFIELDS => $data, 71 | CURLOPT_HTTPHEADER => $headers, 72 | CURLOPT_VERBOSE => $setup->getDebug(), 73 | ); 74 | 75 | $ip = $setup->getProxyIp(); 76 | $port = $setup->getProxyPort(); 77 | 78 | if (!empty($ip) && $port) { 79 | $this->curlOptions[CURLOPT_HTTPPROXYTUNNEL] = 1; 80 | $this->curlOptions[CURLOPT_PROXYTYPE] = 'CURLPROXY_HTTP'; 81 | $this->curlOptions[CURLOPT_PROXY] = $setup->getProxyIp() . ':' . $setup->getProxyPort(); 82 | } 83 | } 84 | 85 | /** 86 | * Retorna as opções definidas para o curl 87 | * @return array 88 | */ 89 | public function getCurlOptions() 90 | { 91 | return $this->curlOptions; 92 | } 93 | 94 | /** 95 | * Com esse método é possível adicionar novas opções ou alterar o valor das 96 | * opções exitentes antes de realizar a requisição para o web service, 97 | * exemplo de utilização com apenas uma opção: 98 | *
 99 |      * $connection->addCurlOption(
100 |      * array(
101 |      *       CURLOPT_PORT => 123
102 |      *  )
103 |      * );
104 |      * 
105 | * Exemplo de utilização com mais de uma opção : 106 | *
107 |      * $connection->addCurlOption(
108 |      * array(
109 |      *       CURLOPT_SSLVERSION => 6,
110 |      *       CURLOPT_SSL_VERIFYPEER => 1
111 |      *  )
112 |      * );
113 |      * 
114 | * 115 | * @param array $option 116 | * @return \Sped\Gnre\Webservice\Connection 117 | */ 118 | public function addCurlOption(array $option) 119 | { 120 | foreach ($option as $key => $value) { 121 | $this->curlOptions[$key] = $value; 122 | } 123 | 124 | return $this; 125 | } 126 | 127 | /** 128 | * Realiza a requisição ao webservice desejado através do curl() do php 129 | * @param string $url String com a URL que será enviada a requisição 130 | * @since 1.0.0 131 | * @return string|boolean Caso a requisição não seja feita com sucesso false, caso contrário um XML formatado 132 | */ 133 | public function doRequest($url) 134 | { 135 | $curl = curl_init($url); 136 | curl_setopt_array($curl, $this->curlOptions); 137 | $ret = curl_exec($curl); 138 | 139 | $n = strlen($ret); 140 | $x = stripos($ret, "<"); 141 | $xml = substr($ret, $x, $n - $x); 142 | 143 | if ($this->setup->getDebug()) { 144 | print_r(curl_getinfo($curl)); 145 | } 146 | 147 | if ($xml === false || $xml === '') { 148 | $xml = curl_error($curl); 149 | } 150 | 151 | curl_close($curl); 152 | 153 | return $xml; 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /lib/Sped/Gnre/Webservice/ConnectionFactory.php: -------------------------------------------------------------------------------- 1 | \Sped\Gnre\Webservice\Connection 24 | * @package gnre 25 | * @subpackage webservice 26 | * @author Matheus Marabesi 27 | * @license http://www.gnu.org/licenses/gpl-howto.html GPL 28 | * @version 1.0.0 29 | */ 30 | class ConnectionFactory 31 | { 32 | 33 | /** 34 | * Cria um objeto \Sped\Gnre\Webservice\Connection 35 | * @param \Sped\Gnre\Webservice\Setup $setup 36 | * @param array $headers 37 | * @param string $data 38 | * @return \Sped\Gnre\Webservice\Connection 39 | */ 40 | public function createConnection(Setup $setup, $headers, $data) 41 | { 42 | return new Connection($setup, $headers, $data); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /phpunit.xml.dist: -------------------------------------------------------------------------------- 1 | 2 | 24 | 25 | 26 | ./lib 27 | 28 | 29 | ./vendor/ 30 | 31 | 32 | 33 | 34 | ./testes 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /testes/Configuration/CertificatePfxTest.php: -------------------------------------------------------------------------------- 1 | getMockBuilder('\Sped\Gnre\Configuration\CertificatePfxFileOperation') 31 | ->disableOriginalConstructor() 32 | ->getMock(); 33 | 34 | $stubFileOperation->expects($this->once()) 35 | ->method('writeFile') 36 | ->will($this->returnValue('vfs://certificadoDir/metadata/certificado_Private.pem')); 37 | 38 | $certificatePfx = new \Sped\Gnre\Configuration\CertificatePfx($stubFileOperation, 'senha'); 39 | $caminhoDoArquivoCriado = $certificatePfx->getPrivateKey(); 40 | 41 | $this->assertEquals('vfs://certificadoDir/metadata/certificado_Private.pem', $caminhoDoArquivoCriado); 42 | } 43 | 44 | public function testPassarAoCriarCertificadoPemApartirDoCertificado() 45 | { 46 | $mockFileOperation = $this->getMockBuilder('\Sped\Gnre\Configuration\CertificatePfxFileOperation') 47 | ->disableOriginalConstructor() 48 | ->getMock(); 49 | 50 | $mockFileOperation->expects($this->once()) 51 | ->method('writeFile') 52 | ->will($this->returnValue('vfs://certificadoDir/metadata/certificado_pemKEY.pem')); 53 | 54 | $certificatePfx = new \Sped\Gnre\Configuration\CertificatePfx($mockFileOperation, 'senha'); 55 | $caminhoDoArquivoCriado = $certificatePfx->getCertificatePem(); 56 | 57 | $this->assertEquals('vfs://certificadoDir/metadata/certificado_pemKEY.pem', $caminhoDoArquivoCriado); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /testes/Configuration/FileOperationTest.php: -------------------------------------------------------------------------------- 1 | expectException(UnreachableFile::class); 33 | $myFile = new MyFile('/foo/bar.txt'); 34 | } 35 | 36 | public function testArquivoInformadoExistente() 37 | { 38 | $file = __DIR__ . '/../../exemplos/xml/estrutura-lote-completo-gnre.xml'; 39 | $myFile = new MyFile($file); 40 | $this->assertFileExists($file); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /testes/Configuration/FilePrefixTest.php: -------------------------------------------------------------------------------- 1 | setPrefix('meuPref'); 32 | $this->assertEquals('/var/www/filemeuPref.doc', $prefix->apply('/var/www/file.doc')); 33 | } 34 | 35 | public function testPassarSemAdicionarPrefixoEmUmArquivo() 36 | { 37 | $prefix = new \Sped\Gnre\Configuration\FilePrefix(); 38 | $this->assertEquals('/path/to/foo.doc', $prefix->apply('/path/to/foo.doc')); 39 | } 40 | 41 | public function testPassarAoEnviarUmCaminhoDeArquivoVazio() 42 | { 43 | $prefix = new \Sped\Gnre\Configuration\FilePrefix(); 44 | $this->assertEmpty($prefix->apply('')); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /testes/Configuration/MyFile.php: -------------------------------------------------------------------------------- 1 | setNumeroCodigoBarras('91910919190191091090109109190109'); 14 | 15 | $this->assertEquals('91910919190191091090109109190109', $barcodeGnre->getNumeroCodigoBarras()); 16 | } 17 | 18 | public function testDeveRetornarUmNumeroDeCodigoDeBarras() 19 | { 20 | $barcodeGnre = new \Sped\Gnre\Render\Barcode128(); 21 | $this->assertNull($barcodeGnre->getNumeroCodigoBarras()); 22 | 23 | $barcodeGnre->setNumeroCodigoBarras('91910919190191091090109109190109'); 24 | 25 | $this->assertEquals('91910919190191091090109109190109', $barcodeGnre->getNumeroCodigoBarras()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /testes/Render/CoveragePdf.php: -------------------------------------------------------------------------------- 1 | assertInstanceOf('\Sped\Gnre\Render\Barcode128', $html->getBarCode()); 18 | } 19 | 20 | public function testDeveRetornarUmaInstanciaDoSmartyFactory() 21 | { 22 | $html = new Html(); 23 | $this->assertInstanceOf('\Sped\Gnre\Render\SmartyFactory', $html->getSmartyFactory()); 24 | } 25 | 26 | public function testDeveDefinirUmObjetoDeCodigoDeBarrasParaSerUtilizado() 27 | { 28 | $barCode = new \Sped\Gnre\Render\Barcode128(); 29 | $html = new Html(); 30 | 31 | $this->assertInstanceOf('\Sped\Gnre\Render\Html', $html->setBarCode($barCode)); 32 | $this->assertSame($barCode, $html->getBarCode()); 33 | } 34 | 35 | public function testDeveRetornarNullSeNaoForCriadoOhtmlDaGuia() 36 | { 37 | $html = new \Sped\Gnre\Render\Html(); 38 | $this->assertEmpty($html->getHtml()); 39 | } 40 | 41 | public function testNaoDeveGerarOhtmlDoLoteQuandoOloteEvazio() 42 | { 43 | $html = new Html(); 44 | $mkcLote = $this->createMock('\Sped\Gnre\Sefaz\Lote'); 45 | $mkcLote->expects($this->once()) 46 | ->method('getGuias'); 47 | $mkcLote->expects($this->never()) 48 | ->method('getGuia'); 49 | 50 | $html->create($mkcLote); 51 | 52 | $this->assertEmpty($html->getHtml()); 53 | } 54 | 55 | public function testDeveGerarOhtmlDoLoteQuandoPossuirGuias() 56 | { 57 | $smarty = $this->createMock('\Smarty'); 58 | $smarty->expects($this->at(0)) 59 | ->method('assign') 60 | ->with('guiaViaInfo'); 61 | $smarty->expects($this->at(1)) 62 | ->method('assign') 63 | ->with('barcode'); 64 | $smarty->expects($this->at(2)) 65 | ->method('assign') 66 | ->with('guia'); 67 | $smarty->expects($this->at(3)) 68 | ->method('fetch') 69 | ->will($this->returnValue('')); 70 | 71 | $smartyFactory = $this->createMock('\Sped\Gnre\Render\SmartyFactory'); 72 | $smartyFactory->expects($this->once()) 73 | ->method('create') 74 | ->will($this->returnValue($smarty)); 75 | 76 | $html = new Html(); 77 | $html->setSmartyFactory($smartyFactory); 78 | 79 | $lote = new \Sped\Gnre\Sefaz\Lote(); 80 | $lote->addGuia(new \Sped\Gnre\Sefaz\Guia()); 81 | 82 | $html->create($lote); 83 | 84 | $this->assertNotEmpty($html->getHtml()); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /testes/Render/PdfTest.php: -------------------------------------------------------------------------------- 1 | createMock('\Dompdf\Dompdf'); 16 | 17 | $html = $this->createMock('\Sped\Gnre\Render\Html'); 18 | 19 | $pdf = $this->createMock('\Sped\Gnre\Render\Pdf'); 20 | $pdf->expects($this->once()) 21 | ->method('create') 22 | ->will($this->returnValue($dom)); 23 | 24 | $domPdf = $pdf->create($html); 25 | 26 | $this->assertInstanceOf('\Dompdf\Dompdf', $domPdf); 27 | } 28 | 29 | public function testDeveRetornarUmaInstanciaDoDomPdf() 30 | { 31 | $dom = new CoveragePdf(); 32 | $this->assertInstanceOf('\Dompdf\Dompdf', $dom->getDomPdf()); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /testes/Render/SmartyFactoryTest.php: -------------------------------------------------------------------------------- 1 | assertInstanceOf('\Smarty', $factory->create()); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /testes/Sefaz/ConfigUfTest.php: -------------------------------------------------------------------------------- 1 | getHeaderSoap(); 17 | 18 | $header = 'Content-Type: application/soap+xml;charset=utf-8;action="http://www.gnre.pe.gov.br/webservice/GnreConfigUF"'; 19 | $this->assertEquals($header, $headersArray[0]); 20 | $this->assertEquals('SOAPAction: consultar', $headersArray[1]); 21 | } 22 | 23 | public function testDeveRetornarOsCabecalhosParaArequisicaoSoapAoWebserviceDeTestes() 24 | { 25 | $consulta = new \Sped\Gnre\Sefaz\ConfigUf(); 26 | $consulta->utilizarAmbienteDeTeste(true); 27 | 28 | $headersArray = $consulta->getHeaderSoap(); 29 | 30 | $header = 'Content-Type: application/soap+xml;charset=utf-8;action="http://www.testegnre.pe.gov.br/webservice/GnreConfigUF"'; 31 | $this->assertEquals($header, $headersArray[0]); 32 | $this->assertEquals('SOAPAction: consultar', $headersArray[1]); 33 | } 34 | 35 | public function testDeveRetornarAacaoAserExecutadaNoSoap() 36 | { 37 | $consulta = new \Sped\Gnre\Sefaz\ConfigUf(); 38 | 39 | $this->assertEquals('https://www.gnre.pe.gov.br/gnreWS/services/GnreConfigUF', $consulta->soapAction()); 40 | } 41 | 42 | public function testDeveRetornarXmlCompletoVazioParaRealizarAconsulta() 43 | { 44 | $dadosParaConsulta = file_get_contents(__DIR__ . '/../../exemplos/xml/envelope-consulta-config-uf.xml'); 45 | 46 | $consulta = new \Sped\Gnre\Sefaz\ConfigUf(); 47 | $consulta->setEnvironment(1); 48 | $consulta->setEstado('PR'); 49 | $consulta->setReceita(100099); 50 | 51 | $this->assertXmlStringEqualsXmlString($dadosParaConsulta, $consulta->toXml()); 52 | } 53 | 54 | public function testDeveRetornarAactionAserExecutadaNoWebServiceDeProducao() 55 | { 56 | $consulta = new \Sped\Gnre\Sefaz\ConfigUf(); 57 | 58 | $this->assertEquals($consulta->soapAction(), 'https://www.gnre.pe.gov.br/gnreWS/services/GnreConfigUF'); 59 | } 60 | 61 | public function testDeveRetornarAactionAserExecutadaNoWebServiceDeTestes() 62 | { 63 | $consulta = new \Sped\Gnre\Sefaz\ConfigUf(); 64 | $consulta->utilizarAmbienteDeTeste(true); 65 | 66 | $this->assertEquals($consulta->soapAction(), 'https://www.testegnre.pe.gov.br/gnreWS/services/GnreConfigUF'); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /testes/Sefaz/ConsultaConfigUfTest.php: -------------------------------------------------------------------------------- 1 | assertNull($gnreConsulta->setReceita(100099)); 18 | } 19 | 20 | public function testDeveRetornarAreceitaDefinida() 21 | { 22 | $gnreConsulta = new MinhaConsultaConfigUf(); 23 | $gnreConsulta->setReceita(100099); 24 | 25 | $this->assertEquals(100099, $gnreConsulta->getReceita()); 26 | } 27 | 28 | public function testDeveDefinirOestadoParaSerUtilizado() 29 | { 30 | $gnreConsulta = new MinhaConsultaConfigUf(); 31 | $this->assertNull($gnreConsulta->setEstado('PR')); 32 | } 33 | 34 | public function testDeveRetornarOestadoDefinido() 35 | { 36 | $gnreConsulta = new MinhaConsultaConfigUf(); 37 | $gnreConsulta->setEstado('PR'); 38 | 39 | $this->assertEquals('PR', $gnreConsulta->getEstado()); 40 | } 41 | 42 | public function testDeveDefinirOambienteParaSerUtilizado() 43 | { 44 | $gnreConsulta = new MinhaConsultaConfigUf(); 45 | $this->assertNull($gnreConsulta->setEnvironment(1)); 46 | } 47 | 48 | public function testDeveRetornarOambienteDefinido() 49 | { 50 | $gnreConsulta = new MinhaConsultaConfigUf(); 51 | $gnreConsulta->setEnvironment(1); 52 | 53 | $this->assertEquals(1, $gnreConsulta->getEnvironment()); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /testes/Sefaz/ConsultaGnreTest.php: -------------------------------------------------------------------------------- 1 | assertNull($gnreConsulta->setRecibo(12345)); 18 | } 19 | 20 | public function testDeveRetornarOreciboDefinido() 21 | { 22 | $gnreConsulta = new MinhaConsultaGnre(); 23 | $gnreConsulta->setRecibo(123456); 24 | 25 | $this->assertEquals(123456, $gnreConsulta->getRecibo()); 26 | } 27 | 28 | public function testDeveDefinirOambienteParaSerUtilizado() 29 | { 30 | $gnreConsulta = new MinhaConsultaGnre(); 31 | $this->assertNull($gnreConsulta->setEnvironment(1)); 32 | } 33 | 34 | public function testDeveRetornarOambienteDefinido() 35 | { 36 | $gnreConsulta = new MinhaConsultaGnre(); 37 | $gnreConsulta->setEnvironment(1); 38 | 39 | $this->assertEquals(1, $gnreConsulta->getEnvironment()); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /testes/Sefaz/ConsultaTest.php: -------------------------------------------------------------------------------- 1 | getHeaderSoap(); 17 | 18 | $header = 'Content-Type: application/soap+xml;charset=utf-8;action="http://www.gnre.pe.gov.br/webservice/GnreResultadoLote"'; 19 | $this->assertEquals($header, $headersArray[0]); 20 | $this->assertEquals('SOAPAction: consultar', $headersArray[1]); 21 | } 22 | 23 | public function testDeveRetornarOsCabecalhosParaArequisicaoSoapAoWebserviceDeTestes() 24 | { 25 | $consulta = new \Sped\Gnre\Sefaz\Consulta(); 26 | $consulta->utilizarAmbienteDeTeste(true); 27 | 28 | $headersArray = $consulta->getHeaderSoap(); 29 | 30 | $header = 'Content-Type: application/soap+xml;charset=utf-8;action="http://www.testegnre.pe.gov.br/webservice/GnreResultadoLote"'; 31 | $this->assertEquals($header, $headersArray[0]); 32 | $this->assertEquals('SOAPAction: consultar', $headersArray[1]); 33 | } 34 | 35 | public function testDeveRetornarAacaoAserExecutadaNoSoap() 36 | { 37 | $consulta = new \Sped\Gnre\Sefaz\Consulta(); 38 | 39 | $this->assertEquals('https://www.gnre.pe.gov.br/gnreWS/services/GnreResultadoLote', $consulta->soapAction()); 40 | } 41 | 42 | public function testDeveRetornarXmlCompletoVazioParaRealizarAconsulta() 43 | { 44 | $dadosParaConsulta = file_get_contents(__DIR__ . '/../../exemplos/xml/envelope-consultar-gnre.xml'); 45 | 46 | $consulta = new \Sped\Gnre\Sefaz\Consulta(); 47 | $consulta->setEnvironment(12345678); 48 | $consulta->setRecibo(123); 49 | 50 | $this->assertXmlStringEqualsXmlString($dadosParaConsulta, $consulta->toXml()); 51 | } 52 | 53 | public function testDeveRetornarAactionAserExecutadaNoWebServiceDeProducao() 54 | { 55 | $consulta = new \Sped\Gnre\Sefaz\Consulta(); 56 | 57 | $this->assertEquals($consulta->soapAction(), 'https://www.gnre.pe.gov.br/gnreWS/services/GnreResultadoLote'); 58 | } 59 | 60 | public function testDeveRetornarAactionAserExecutadaNoWebServiceDeTestes() 61 | { 62 | $consulta = new \Sped\Gnre\Sefaz\Consulta(); 63 | $consulta->utilizarAmbienteDeTeste(true); 64 | 65 | $action = 'https://www.testegnre.pe.gov.br/gnreWS/services/GnreResultadoLote'; 66 | $this->assertEquals($consulta->soapAction(), $action); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /testes/Sefaz/EstadoFactoryTest.php: -------------------------------------------------------------------------------- 1 | assertInstanceOf('Sped\Gnre\Sefaz\Estados\Padrao', $estado->create('BA')); 19 | $this->assertInstanceOf('Sped\Gnre\Sefaz\Estados\BA', $estado->create('BA')); 20 | } 21 | 22 | public function testShouldReturnACObjectwhenAclassDoesExists() 23 | { 24 | $estado = new EstadoFactory(); 25 | 26 | $this->assertInstanceOf('Sped\Gnre\Sefaz\Estados\Padrao', $estado->create('AC')); 27 | $this->assertInstanceOf('Sped\Gnre\Sefaz\Estados\AC', $estado->create('AC')); 28 | } 29 | 30 | public function testReturnAdefaultObject() 31 | { 32 | $estado = new EstadoFactory(); 33 | 34 | $this->assertInstanceOf('Sped\Gnre\Sefaz\Estados\BA', $estado->create('EstadoNaoExistente')); 35 | } 36 | 37 | public function testShouldCreateACObjectFromFactory() 38 | { 39 | $factory = new EstadoFactory(); 40 | $estado = $factory->create('AC'); 41 | 42 | $this->assertInstanceOf('Sped\Gnre\Sefaz\Estados\Padrao', $estado); 43 | $this->assertInstanceOf('Sped\Gnre\Sefaz\Estados\AC', $estado); 44 | } 45 | 46 | public function testShouldCreateALObjectFromFactory() 47 | { 48 | $factory = new EstadoFactory(); 49 | $estado = $factory->create('AL'); 50 | 51 | $this->assertInstanceOf('Sped\Gnre\Sefaz\Estados\Padrao', $estado); 52 | $this->assertInstanceOf('Sped\Gnre\Sefaz\Estados\AL', $estado); 53 | } 54 | 55 | public function testShouldCreateAMObjectFromFactory() 56 | { 57 | $factory = new EstadoFactory(); 58 | $estado = $factory->create('AM'); 59 | 60 | $this->assertInstanceOf('Sped\Gnre\Sefaz\Estados\Padrao', $estado); 61 | $this->assertInstanceOf('Sped\Gnre\Sefaz\Estados\AM', $estado); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /testes/Sefaz/GuiaTest.php: -------------------------------------------------------------------------------- 1 | c01_UfFavorecida = 'SP'; 19 | 20 | $this->assertEquals('SP', $gnreGuia->c01_UfFavorecida); 21 | } 22 | 23 | public function testAcessarUmaPropriedadeQueNaoExisteNaClasse() 24 | { 25 | $this->expectException(UndefinedProperty::class); 26 | $this->expectExceptionMessage('Não foi possível encontrar o atributo desejado na classe'); 27 | $this->expectExceptionCode(100); 28 | 29 | $gnreGuia = new \Sped\Gnre\Sefaz\Guia(); 30 | $gnreGuia->teste = 'SP'; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /testes/Sefaz/LoteGnreTest.php: -------------------------------------------------------------------------------- 1 | lote = new \Sped\Gnre\Sefaz\Lote(); 33 | } 34 | 35 | public function tearDown():void 36 | { 37 | $this->lote = null; 38 | } 39 | 40 | public function testAdicionarUmaGuiaAoLote() 41 | { 42 | $this->lote->addGuia(new \Sped\Gnre\Sefaz\Guia()); 43 | $this->assertEquals(1, count($this->lote->getGuias())); 44 | } 45 | 46 | public function testBuscarUmaGuiaEmEspecifico() 47 | { 48 | $this->lote->addGuia(new \Sped\Gnre\Sefaz\Guia()); 49 | $this->lote->addGuia(new \Sped\Gnre\Sefaz\Guia()); 50 | 51 | $this->assertInstanceOf('\Sped\Gnre\Sefaz\Guia', $this->lote->getGuia(0)); 52 | $this->assertInstanceOf('\Sped\Gnre\Sefaz\Guia', $this->lote->getGuia(1)); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /testes/Sefaz/MinhaConsultaConfigUf.php: -------------------------------------------------------------------------------- 1 | setup = $this->createMock('\Sped\Gnre\Configuration\Setup'); 22 | $this->objetoSefaz = $this->createMock('\Sped\Gnre\Sefaz\ObjetoSefaz'); 23 | } 24 | 25 | public function testDeveLancarExcecaoAoNaoSetarUmaConnectionFactoryParaSerUsada() 26 | { 27 | $this->expectException(ConnectionFactoryUnavailable::class); 28 | 29 | $send = new Send($this->setup); 30 | $send->sefaz($this->objetoSefaz); 31 | } 32 | 33 | public function testDeveSetarUmaConnectionFactoryParaSerUsada() 34 | { 35 | $connectionFactory = $this->createMock('\Sped\Gnre\Webservice\ConnectionFactory'); 36 | 37 | $send = new Send($this->setup); 38 | $this->assertInstanceOf('\Sped\Gnre\Sefaz\Send', $send->setConnectionFactory($connectionFactory)); 39 | } 40 | 41 | public function testDeveRetornarUmaConnectionFactory() 42 | { 43 | $connectionFactory = $this->createMock('\Sped\Gnre\Webservice\ConnectionFactory'); 44 | 45 | $send = new Send($this->setup); 46 | $send->setConnectionFactory($connectionFactory); 47 | 48 | $this->assertInstanceOf('\Sped\Gnre\Webservice\ConnectionFactory', $send->getConnectionFactory()); 49 | } 50 | 51 | public function testDeveRealizarAconexaoComAsefaz() 52 | { 53 | $connection = $this->getMockBuilder('\Sped\Gnre\Webservice\Connection') 54 | ->disableOriginalConstructor() 55 | ->getMock(); 56 | $connection->expects($this->once()) 57 | ->method('doRequest') 58 | ->will($this->returnValue(true)); 59 | 60 | $connectionFactory = $this->createMock('\Sped\Gnre\Webservice\ConnectionFactory'); 61 | $connectionFactory->expects($this->once()) 62 | ->method('createConnection') 63 | ->will($this->returnValue($connection)); 64 | 65 | $send = new Send($this->setup); 66 | $send->setConnectionFactory($connectionFactory); 67 | $send->sefaz($this->objetoSefaz); 68 | } 69 | 70 | public function testDeveExibirDebug() 71 | { 72 | $connection = $this->getMockBuilder('\Sped\Gnre\Webservice\Connection') 73 | ->disableOriginalConstructor() 74 | ->getMock(); 75 | $connection->expects($this->once()) 76 | ->method('doRequest') 77 | ->will($this->returnValue(true)); 78 | 79 | $connectionFactory = $this->createMock('\Sped\Gnre\Webservice\ConnectionFactory'); 80 | $connectionFactory->expects($this->once()) 81 | ->method('createConnection') 82 | ->will($this->returnValue($connection)); 83 | 84 | $this->setup->expects($this->once()) 85 | ->method('getDebug') 86 | ->will($this->returnValue(true)); 87 | 88 | $send = new Send($this->setup); 89 | $send->setConnectionFactory($connectionFactory); 90 | $send->sefaz($this->objetoSefaz); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /testes/Webservice/ConnectionFactoryTest.php: -------------------------------------------------------------------------------- 1 | getMockForAbstractClass('\Sped\Gnre\Configuration\Setup'); 17 | 18 | $factory = new ConnectionFactory(); 19 | $connection = $factory->createConnection($setup, array(), 'my data'); 20 | 21 | $this->assertInstanceOf('\Sped\Gnre\Webservice\Connection', $connection); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /testes/Webservice/ConnectionTest.php: -------------------------------------------------------------------------------- 1 | curlOptions = array( 19 | CURLOPT_PORT => 443, 20 | CURLOPT_VERBOSE => 1, 21 | CURLOPT_HEADER => 1, 22 | CURLOPT_SSLVERSION => 3, 23 | CURLOPT_SSL_VERIFYHOST => 0, 24 | CURLOPT_SSL_VERIFYPEER => 0, 25 | CURLOPT_SSLCERT => null, 26 | CURLOPT_SSLKEY => null, 27 | CURLOPT_POST => 1, 28 | CURLOPT_RETURNTRANSFER => 1, 29 | CURLOPT_POSTFIELDS => '', 30 | CURLOPT_HTTPHEADER => array(), 31 | CURLOPT_VERBOSE => false, 32 | ); 33 | } 34 | 35 | public function tearDown():void 36 | { 37 | $this->curlOptions = array(); 38 | } 39 | 40 | public function testDeveAdicionarUmaNocaOpcaoAsOpcoesDoCurl() 41 | { 42 | $setup = $this->getMockForAbstractClass('\Sped\Gnre\Configuration\Setup'); 43 | 44 | $connection = new Connection($setup, array(), ''); 45 | 46 | $this->assertEquals($this->curlOptions, $connection->getCurlOptions()); 47 | 48 | $connection->addCurlOption(array( 49 | CURLOPT_PORT => 123 50 | )); 51 | 52 | $this->curlOptions[CURLOPT_PORT] = 123; 53 | 54 | $this->assertEquals($this->curlOptions, $connection->getCurlOptions()); 55 | } 56 | 57 | public function testDeveCriarUmObjetoConnectionSemProxy() 58 | { 59 | $this->curlOptions[CURLOPT_SSLCERT] = '/foo/bar/cert.pem'; 60 | $this->curlOptions[CURLOPT_SSLKEY] = '/foo/bar/priv.pem'; 61 | 62 | $setup = $this->getMockForAbstractClass('\Sped\Gnre\Configuration\Setup'); 63 | $setup->expects($this->once()) 64 | ->method('getCertificatePemFile') 65 | ->will($this->returnValue('/foo/bar/cert.pem')); 66 | $setup->expects($this->once()) 67 | ->method('getPrivateKey') 68 | ->will($this->returnValue('/foo/bar/priv.pem')); 69 | 70 | $connection = new Connection($setup, array(), ''); 71 | 72 | $this->assertEquals($this->curlOptions, $connection->getCurlOptions()); 73 | } 74 | 75 | public function testDeveCriarUmObjetoConnectionComProxy() 76 | { 77 | $this->curlOptions[CURLOPT_HTTPPROXYTUNNEL] = 1; 78 | $this->curlOptions[CURLOPT_PROXYTYPE] = 'CURLPROXY_HTTP'; 79 | $this->curlOptions[CURLOPT_PROXY] = '192.168.0.1:3128'; 80 | 81 | $setup = $this->getMockForAbstractClass('\Sped\Gnre\Configuration\Setup'); 82 | $setup->expects($this->exactly(2)) 83 | ->method('getProxyIp') 84 | ->will($this->returnValue('192.168.0.1')); 85 | $setup->expects($this->exactly(2)) 86 | ->method('getProxyPort') 87 | ->will($this->returnValue('3128')); 88 | 89 | $connection = new Connection($setup, array(), ''); 90 | 91 | $this->assertEquals($this->curlOptions, $connection->getCurlOptions()); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /wsdl/GnreLoteResultado.wsdl: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /wsdl/GnreRecepcaoLote.wsdl: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /xsd/v1/consulta_config_uf_v1.00.xsd: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /xsd/v1/lote_gnre_consulta_v1.00.xsd: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /xsd/v1/lote_gnre_recibo_v1.00.xsd: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | Número do recibo de gerado pelo 48 | portal GNRE 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 59 | 60 | Data e Hora do recebimento do lote 61 | 62 | 63 | 65 | 66 | Tempo estimado para processamento do lote em ms. 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /xsd/v1/lote_gnre_result_v1.00.xsd: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /xsd/v1/tiposBasicoGNRE_v1.00.xsd: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | Tipo Código do Município da tabela do IBGE 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | Tipo Número do CNPJ 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | Tipo Número do CPF 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | Tipo Inscrição Estadual 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | Tipo Sigla da UF 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | Tipo Versão do Aplicativo 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | Tipo ano 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | Tipo string genérico 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | Tipo data AAAA-MM-DD 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | Tipo data AAAA-MM-DD HH:MM:SS 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | Tipo Meses do Ano 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | Tipo Campos possíveis na GNRE 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | Tipo Versão da GNRE - 1.10 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | Código do Tipo de Identificação do Destinatário: 203 | 1 - CNPJ; 204 | 2 - CPF; 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | Tipo Decimal com 15 dígitos, sendo 13 de corpo e 2 decimais 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | Código do tipo de dados dos Campos Extras: 225 | T - Texto 226 | N - Numérico 227 | D - Data 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | -------------------------------------------------------------------------------- /xsd/v2/lote_gnre_result_v2.00.xsd: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | Atualização monetária do valor original até a data de pagamento. 15 | 16 | 17 | 18 | 19 | Valor de juros sobre o valor original até a data de pagamento. 20 | 21 | 22 | 23 | 24 | Valor da multa aplicada sobre o valor original. 25 | 26 | 27 | 28 | 29 | 30 | Data máxima que o banco pode receber o pagamento, que estará impressa na guia e no código de barras. 31 | 32 | 33 | 34 | 35 | 36 | Informação complementar a ser impressa na guia. 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | Número interno da guia gerado pela UF 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 165 | 166 | 167 | 168 | 169 | 170 | 0 - Processada com sucesso 1 - Invalidada pelo 171 | Portal 2 - Invalidada pela UF 3 - Erro de 172 | comunicação 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 188 | 189 | 190 | 192 | 194 | 195 | 196 | Data máxima que o banco pode receber o 197 | pagamento, que estará impressa na guia e no 198 | código de barras. 199 | 200 | 201 | 202 | 204 | 205 | 206 | Informação complementar a ser impressa na guia. 207 | 208 | 209 | 210 | 211 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 227 | 228 | 229 | 230 | 231 | Número interno da guia gerado pela UF 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 245 | 246 | 248 | 249 | 251 | 253 | 254 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | -------------------------------------------------------------------------------- /xsd/v2/lote_gnre_v2.00.xsd: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 32 | 33 | 34 | 35 | 36 | 37 | 39 | 40 | 42 | 44 | 45 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /xsd/v2/tiposBasicoGNRE_v2.00.xsd: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 18 | 19 | 21 | 22 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | Campos da GNRE 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | --------------------------------------------------------------------------------