├── src ├── media │ └── formatters │ │ ├── formatterBase.php │ │ ├── jsonFormatter.php │ │ └── formDataFormatter.php ├── helper.php ├── exceptions │ ├── invalidApiKeyException.php │ ├── unauthorizedException.php │ ├── requestException.php │ └── apiException.php ├── apiBase.php ├── prefeituraApi.php ├── fileParameter.php ├── response.php ├── servicosMunicipaisApi.php ├── request.php ├── proxy │ ├── curlProxy.php │ └── proxyBase.php ├── empresaApi.php ├── eNotasGW.php └── nfeApi.php ├── composer.json ├── LICENSE ├── samples ├── uploadLogoEmpresa.php ├── uploadCertificadoEmpresa.php ├── cancelamento.php ├── consulta.php ├── downloadPdf.php ├── downloadXml.php ├── emissao.php ├── WebHook │ └── webHook.php └── inserirAtualizarEmpresa.php └── README.md /src/media/formatters/formatterBase.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/helper.php: -------------------------------------------------------------------------------- 1 | format('Y-m-d'); 7 | } 8 | 9 | public static function formatDateTime($date) { 10 | return $date->format('Y-m-d H:i:s'); 11 | } 12 | } 13 | ?> 14 | -------------------------------------------------------------------------------- /src/exceptions/invalidApiKeyException.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/exceptions/unauthorizedException.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/apiBase.php: -------------------------------------------------------------------------------- 1 | proxy = $proxy; 9 | } 10 | 11 | protected function callOperation($operation) { 12 | return $this->proxy->doRequest($operation); 13 | } 14 | } 15 | ?> -------------------------------------------------------------------------------- /src/media/formatters/jsonFormatter.php: -------------------------------------------------------------------------------- 1 | 18 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "enotas/php-client", 3 | "description": "eNotas GW API client for PHP", 4 | "keywords": ["eNotas", "NFS-e"], 5 | "homepage": "https://github.com/eNotasGW/php-client", 6 | "type": "library", 7 | "license": "MIT", 8 | "authors": [ 9 | { 10 | "name": "eNotas Gateway", 11 | "email": "suporte@enotasgw.com.br" 12 | } 13 | ], 14 | "require": { 15 | "php": ">=5.3.0" 16 | }, 17 | "autoload": { 18 | "psr-4": { 19 | "eNotasGW\\Api\\": "src/" 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/exceptions/requestException.php: -------------------------------------------------------------------------------- 1 | requestedUrl = $requestedUrl; 21 | $this->responseBody = $responseBody; 22 | 23 | parent::__construct($faultMessage, $httpCode, null); 24 | } 25 | } 26 | ?> -------------------------------------------------------------------------------- /src/exceptions/apiException.php: -------------------------------------------------------------------------------- 1 | errors = $errors; 11 | $message = $this->formatMessage(); 12 | 13 | parent::__construct($message, $httpCode, null); 14 | } 15 | 16 | protected function formatMessage() { 17 | $message = ''; 18 | $padding = ''; 19 | 20 | foreach ($this->errors as &$error) { 21 | $message .= $padding . "{$error->codigo} - {$error->mensagem}"; 22 | $padding = PHP_EOL; 23 | } 24 | 25 | return $message; 26 | } 27 | } 28 | ?> -------------------------------------------------------------------------------- /src/prefeituraApi.php: -------------------------------------------------------------------------------- 1 | callOperation(array( 17 | 'path' => '/estados/cidades/{codigoIbge}/provedor', 18 | 'parameters' => array( 19 | 'path' => array( 20 | 'codigoIbge' => $codigoIbge 21 | ) 22 | ) 23 | )); 24 | } 25 | } 26 | ?> 27 | -------------------------------------------------------------------------------- /src/fileParameter.php: -------------------------------------------------------------------------------- 1 | rawData = $rawData; 14 | $file->contentType = $contentType; 15 | $file->name = $fileName; 16 | 17 | return $file; 18 | } 19 | 20 | private function __contruct() { 21 | } 22 | 23 | /** 24 | * File name 25 | * @var string 26 | */ 27 | public $name; 28 | 29 | /** 30 | * The file content type, for example: "image/jpeg" 31 | * @var string 32 | */ 33 | public $contentType; 34 | 35 | /** 36 | * The file Raw Data (bytes) 37 | * @var array 38 | */ 39 | public $rawData; 40 | } 41 | ?> -------------------------------------------------------------------------------- /src/response.php: -------------------------------------------------------------------------------- 1 | body === FALSE; 31 | } 32 | 33 | public function getResponseData() { 34 | if($this->isEmpty()) { 35 | return NULL; 36 | } 37 | else { 38 | return $this->decodeResponse(); 39 | } 40 | } 41 | 42 | private function decodeResponse() { 43 | $formatter = eNotasGW::getMediaFormatter($this->contentType); 44 | 45 | return $formatter->decode($this->body); 46 | } 47 | } 48 | ?> -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 eNotas GW 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /src/servicosMunicipaisApi.php: -------------------------------------------------------------------------------- 1 | callOperation(array( 21 | 'path' => '/estados/{uf}/cidades/{nome}/servicos', 22 | 'parameters' => array( 23 | 'path' => array( 24 | 'uf' => $uf, 25 | 'nome' => $cidade 26 | ), 27 | 'query' => array( 28 | 'pageNumber' => $pageNumber, 29 | 'pageSize' => $pageSize, 30 | 'filter' => $termoPesquisa != NULL ? "contains(descricao, '{$termoPesquisa}')" : NULL 31 | ) 32 | ) 33 | )); 34 | } 35 | } 36 | ?> 37 | -------------------------------------------------------------------------------- /samples/uploadLogoEmpresa.php: -------------------------------------------------------------------------------- 1 | '{api key}', 11 | )); 12 | 13 | $empresaId = '{empresa id}'; 14 | 15 | try 16 | { 17 | $file = fileParameter::fromPath('{logo image path}', 18 | 'image/png', 'logo.png'); 19 | 20 | eNotasGW::$EmpresaApi->atualizarLogo($empresaId, $file); 21 | echo 'Logo atualizada com sucesso!'; 22 | } 23 | catch(Exceptions\invalidApiKeyException $ex) { 24 | echo 'Erro de autenticação:

'; 25 | echo $ex->getMessage(); 26 | } 27 | catch(Exceptions\unauthorizedException $ex) { 28 | echo 'Acesso negado:

'; 29 | echo $ex->getMessage(); 30 | } 31 | catch(Exceptions\apiException $ex) { 32 | echo 'Erro de validação:

'; 33 | echo $ex->getMessage(); 34 | } 35 | catch(Exceptions\requestException $ex) { 36 | echo 'Erro na requisição web:

'; 37 | 38 | echo 'Requested url: ' . $ex->requestedUrl; 39 | echo '
'; 40 | echo 'Response Code: ' . $ex->getCode(); 41 | echo '
'; 42 | echo 'Message: ' . $ex->getMessage(); 43 | echo '
'; 44 | echo 'Response Body: ' . $ex->responseBody; 45 | } 46 | ?> 47 | -------------------------------------------------------------------------------- /samples/uploadCertificadoEmpresa.php: -------------------------------------------------------------------------------- 1 | '{api key}', 11 | )); 12 | 13 | $empresaId = '{empresa id}'; 14 | 15 | try 16 | { 17 | $file = fileParameter::fromPath('{certificate file path}.pfx', 18 | 'application/x-pkcs12', '{file name}.pfx'); 19 | $pass = '{your pass}'; 20 | 21 | eNotasGW::$EmpresaApi->atualizarCertificado($empresaId, $file, $pass); 22 | echo 'Certificado atualizado com sucesso!'; 23 | } 24 | catch(Exceptions\invalidApiKeyException $ex) { 25 | echo 'Erro de autenticação:

'; 26 | echo $ex->getMessage(); 27 | } 28 | catch(Exceptions\unauthorizedException $ex) { 29 | echo 'Acesso negado:

'; 30 | echo $ex->getMessage(); 31 | } 32 | catch(Exceptions\apiException $ex) { 33 | echo 'Erro de validação:

'; 34 | echo $ex->getMessage(); 35 | } 36 | catch(Exceptions\requestException $ex) { 37 | echo 'Erro na requisição web:

'; 38 | 39 | echo 'Requested url: ' . $ex->requestedUrl; 40 | echo '
'; 41 | echo 'Response Code: ' . $ex->getCode(); 42 | echo '
'; 43 | echo 'Message: ' . $ex->getMessage(); 44 | echo '
'; 45 | echo 'Response Body: ' . $ex->responseBody; 46 | } 47 | ?> 48 | -------------------------------------------------------------------------------- /samples/cancelamento.php: -------------------------------------------------------------------------------- 1 | '' 10 | )); 11 | 12 | $empresaId = 'a9f9d282-fdb9-4259-a7b8-2f19be4da06d'; 13 | 14 | try 15 | { 16 | $nfeId = 'ab765f39-a2e0-4c4b-88b4-4b6b4a2baace'; 17 | eNotasGW::$NFeApi->cancelar($empresaId, $nfeId); 18 | 19 | /** 20 | descomentar caso não possua o id único e queira efetuar o cancelamento pelo id externo 21 | 22 | $idExterno = '1'; 23 | eNotasGW::$NFeApi->cancelarPorIdExterno($empresaId, $idExterno); 24 | 25 | */ 26 | 27 | echo 'Cancelamento solicitado com sucesso!'; 28 | } 29 | catch(Exceptions\invalidApiKeyException $ex) { 30 | echo 'Erro de autenticação:

'; 31 | echo $ex->getMessage(); 32 | } 33 | catch(Exceptions\unauthorizedException $ex) { 34 | echo 'Acesso negado:

'; 35 | echo $ex->getMessage(); 36 | } 37 | catch(Exceptions\apiException $ex) { 38 | echo 'Erro de validação:

'; 39 | echo $ex->getMessage(); 40 | } 41 | catch(Exceptions\requestException $ex) { 42 | echo 'Erro na requisição web:

'; 43 | 44 | echo 'Requested url: ' . $ex->requestedUrl; 45 | echo '
'; 46 | echo 'Response Code: ' . $ex->getCode(); 47 | echo '
'; 48 | echo 'Message: ' . $ex->getMessage(); 49 | echo '
'; 50 | echo 'Response Body: ' . $ex->responseBody; 51 | } 52 | ?> -------------------------------------------------------------------------------- /samples/consulta.php: -------------------------------------------------------------------------------- 1 | '' 10 | )); 11 | 12 | $empresaId = 'a9f9d282-fdb9-4259-a7b8-2f19be4da06d'; 13 | 14 | try 15 | { 16 | $nfeId = 'ab765f39-a2e0-4c4b-88b4-4b6b4a2baace'; 17 | $dadosNFe = eNotasGW::$NFeApi->consultar($empresaId, $nfeId); 18 | 19 | echo 'Dados da nota (consulta por id único):
'; 20 | echo json_encode($dadosNFe); 21 | 22 | $idExterno = '1'; 23 | $dadosNFe2 = eNotasGW::$NFeApi->consultarPorIdExterno($empresaId, $idExterno); 24 | 25 | echo '

'; 26 | echo 'Dados da nota (consulta por id externo):
'; 27 | echo json_encode($dadosNFe2); 28 | } 29 | catch(Exceptions\invalidApiKeyException $ex) { 30 | echo 'Erro de autenticação:

'; 31 | echo $ex->getMessage(); 32 | } 33 | catch(Exceptions\unauthorizedException $ex) { 34 | echo 'Acesso negado:

'; 35 | echo $ex->getMessage(); 36 | } 37 | catch(Exceptions\apiException $ex) { 38 | echo 'Erro de validação:

'; 39 | echo $ex->getMessage(); 40 | } 41 | catch(Exceptions\requestException $ex) { 42 | echo 'Erro na requisição web:

'; 43 | 44 | echo 'Requested url: ' . $ex->requestedUrl; 45 | echo '
'; 46 | echo 'Response Code: ' . $ex->getCode(); 47 | echo '
'; 48 | echo 'Message: ' . $ex->getMessage(); 49 | echo '
'; 50 | echo 'Response Body: ' . $ex->responseBody; 51 | } 52 | ?> -------------------------------------------------------------------------------- /samples/downloadPdf.php: -------------------------------------------------------------------------------- 1 | '' 10 | )); 11 | 12 | $empresaId = 'a9f9d282-fdb9-4259-a7b8-2f19be4da06d'; 13 | 14 | try 15 | { 16 | $nfeId = 'ab765f39-a2e0-4c4b-88b4-4b6b4a2baace'; 17 | $pdf = eNotasGW::$NFeApi->downloadPdf($empresaId, $nfeId); 18 | 19 | /* 20 | descomentar para efetuar o download pelo id externo 21 | 22 | $idExterno = '1'; 23 | $pdf = eNotasGW::$NFeApi->downloadPdfPorIdExterno($empresaId, $idExterno); 24 | 25 | */ 26 | 27 | $folder = 'Downloads'; 28 | 29 | if (!file_exists($folder)) { 30 | mkdir($folder, 0777, true); 31 | } 32 | 33 | $pdfFileName = "{$folder}/NF-{$nfeId}.pdf"; 34 | file_put_contents($pdfFileName, $pdf); 35 | echo "Download do pdf, arquivo salvo em \"{$pdfFileName}\""; 36 | } 37 | catch(Exceptions\invalidApiKeyException $ex) { 38 | echo 'Erro de autenticação:

'; 39 | echo $ex->getMessage(); 40 | } 41 | catch(Exceptions\unauthorizedException $ex) { 42 | echo 'Acesso negado:

'; 43 | echo $ex->getMessage(); 44 | } 45 | catch(Exceptions\apiException $ex) { 46 | echo 'Erro de validação:

'; 47 | echo $ex->getMessage(); 48 | } 49 | catch(Exceptions\requestException $ex) { 50 | echo 'Erro na requisição web:

'; 51 | 52 | echo 'Requested url: ' . $ex->requestedUrl; 53 | echo '
'; 54 | echo 'Response Code: ' . $ex->getCode(); 55 | echo '
'; 56 | echo 'Message: ' . $ex->getMessage(); 57 | echo '
'; 58 | echo 'Response Body: ' . $ex->responseBody; 59 | } 60 | ?> -------------------------------------------------------------------------------- /samples/downloadXml.php: -------------------------------------------------------------------------------- 1 | '' 10 | )); 11 | 12 | $empresaId = 'a9f9d282-fdb9-4259-a7b8-2f19be4da06d'; 13 | 14 | try 15 | { 16 | $nfeId = 'ab765f39-a2e0-4c4b-88b4-4b6b4a2baace'; 17 | $xml = eNotasGW::$NFeApi->downloadXml($empresaId, $nfeId); 18 | 19 | /* 20 | descomentar para efetuar o download pelo id externo 21 | 22 | $idExterno = '1'; 23 | $xml = eNotasGW::$NFeApi->downloadXmlPorIdExterno($empresaId, $idExterno); 24 | 25 | */ 26 | 27 | $folder = 'Downloads'; 28 | 29 | if (!file_exists($folder)) { 30 | mkdir($folder, 0777, true); 31 | } 32 | 33 | $xmlFileName = "{$folder}/NF-{$nfeId}.xml"; 34 | file_put_contents($xmlFileName, $xml); 35 | echo "Download do xml, arquivo salvo em \"{$xmlFileName}\""; 36 | } 37 | catch(Exceptions\invalidApiKeyException $ex) { 38 | echo 'Erro de autenticação:

'; 39 | echo $ex->getMessage(); 40 | } 41 | catch(Exceptions\unauthorizedException $ex) { 42 | echo 'Acesso negado:

'; 43 | echo $ex->getMessage(); 44 | } 45 | catch(Exceptions\apiException $ex) { 46 | echo 'Erro de validação:

'; 47 | echo $ex->getMessage(); 48 | } 49 | catch(Exceptions\requestException $ex) { 50 | echo 'Erro na requisição web:

'; 51 | 52 | echo 'Requested url: ' . $ex->requestedUrl; 53 | echo '
'; 54 | echo 'Response Code: ' . $ex->getCode(); 55 | echo '
'; 56 | echo 'Message: ' . $ex->getMessage(); 57 | echo '
'; 58 | echo 'Response Body: ' . $ex->responseBody; 59 | } 60 | ?> -------------------------------------------------------------------------------- /src/request.php: -------------------------------------------------------------------------------- 1 | parameters[$name] = $value; 49 | } 50 | 51 | public function getParameter($name) { 52 | return $this->parameters[$name]; 53 | } 54 | 55 | public function getRequestBody() { 56 | if(empty($this->parameters)) { 57 | return NULL; 58 | } 59 | else { 60 | return $this->encodeRequestParameters(); 61 | } 62 | } 63 | 64 | public function encodeRequestParameters() { 65 | $contentType = $this->contentType; 66 | $formatter = eNotasGW::getMediaFormatter($contentType); 67 | 68 | if($formatter !== FALSE) { 69 | $result = $formatter->encode($this->parameters, $contentType); 70 | $this->contentType = $contentType; 71 | 72 | return $result; 73 | } 74 | 75 | return $this->parameters; 76 | } 77 | } 78 | ?> -------------------------------------------------------------------------------- /src/media/formatters/formDataFormatter.php: -------------------------------------------------------------------------------- 1 | $value) { 14 | $name = $this->removeNotAllowedChars($name); 15 | $body[] = "--" . $boundary; 16 | 17 | if(is_a($value, 'eNotasGW\Api\fileParameter')) { 18 | $this->appendFileParameter($name, $value, $body); 19 | } 20 | else { 21 | $this->appendParameter($name, $value, $body); 22 | } 23 | } 24 | } 25 | 26 | $body[] = "--" . $boundary . "--\r\n"; 27 | 28 | return implode("\r\n", $body); 29 | } 30 | 31 | private function appendParameter($name, $value, &$body) { 32 | $body[] = implode("\r\n", array( 33 | "Content-Disposition: form-data; name=\"{$name}\"", 34 | '', 35 | filter_var($value, FILTER_SANITIZE_STRING), 36 | )); 37 | } 38 | 39 | private function appendFileParameter($name, $file, &$body) { 40 | $fileName = $file->name; 41 | 42 | $body[] = implode("\r\n", array( 43 | "Content-Disposition: form-data; name=\"{$name}\"; filename=\"{$fileName}\"", 44 | 'Content-Type: ' . (isset($file->contentType) ? $file->contentType : 'application/octet-stream'), 45 | '', 46 | $file->rawData, 47 | )); 48 | } 49 | 50 | private function removeNotAllowedChars($name) { 51 | return str_replace(self::$_notAllowedChars, "_", $name); 52 | } 53 | 54 | public function decode($encodedData) { 55 | throw new Exception('This method is not supported'); 56 | } 57 | } 58 | ?> 59 | -------------------------------------------------------------------------------- /samples/emissao.php: -------------------------------------------------------------------------------- 1 | '' 10 | )); 11 | 12 | $empresaId = '{empresa id}'; 13 | $idExterno = '{id de mapeamento no sistema de origem}'; 14 | 15 | try 16 | { 17 | $nfeId = eNotasGW::$NFeApi->emitir($empresaId, array( 18 | 'tipo' => 'NFS-e', 19 | 'idExterno' => $idExterno, 20 | 'ambienteEmissao' => 'Homologacao', //'Homologacao' ou 'Producao' 21 | 'cliente' => array( 22 | 'nome' => 'Fulano de Tal', 23 | 'email' => 'fulano@mail.com', 24 | 'cpfCnpj' => '23857396237', 25 | 'tipoPessoa' => 'F', //F - pessoa física | J - pessoa jurídica 26 | 'endereco' => array( 27 | 'uf' => 'MG', 28 | 'cidade' => 'Belo Horizonte', 29 | 'logradouro' => 'Rua 01', 30 | 'numero' => '112', 31 | 'complemento' => 'AP 402', 32 | 'bairro' => 'Savassi', 33 | 'cep' => '32323111' 34 | ) 35 | ), 36 | 'servico' => array( 37 | 'descricao' => 'Discriminação do Serviço prestado' 38 | ), 39 | 'valorTotal' => 10.05 40 | )); 41 | 42 | echo 'Sucesso!
'; 43 | echo "ID da NFe: {$nfeId}"; 44 | } 45 | catch(Exceptions\invalidApiKeyException $ex) { 46 | echo 'Erro de autenticação:

'; 47 | echo $ex->getMessage(); 48 | } 49 | catch(Exceptions\unauthorizedException $ex) { 50 | echo 'Acesso negado:

'; 51 | echo $ex->getMessage(); 52 | } 53 | catch(Exceptions\apiException $ex) { 54 | echo 'Erro de validação:

'; 55 | echo $ex->getMessage(); 56 | } 57 | catch(Exceptions\requestException $ex) { 58 | echo 'Erro na requisição web:

'; 59 | 60 | echo 'Requested url: ' . $ex->requestedUrl; 61 | echo '
'; 62 | echo 'Response Code: ' . $ex->getCode(); 63 | echo '
'; 64 | echo 'Message: ' . $ex->getMessage(); 65 | echo '
'; 66 | echo 'Response Body: ' . $ex->responseBody; 67 | } 68 | ?> 69 | -------------------------------------------------------------------------------- /src/proxy/curlProxy.php: -------------------------------------------------------------------------------- 1 | method); 11 | $options = array( 12 | CURLOPT_URL => $request->url, 13 | CURLOPT_RETURNTRANSFER => TRUE, 14 | CURLOPT_TIMEOUT => $request->timeout, 15 | CURLOPT_SSL_VERIFYHOST => 2, 16 | CURLOPT_SSL_VERIFYPEER => TRUE, 17 | CURLOPT_CAINFO => $this->executionCtx->trustedCAListPath 18 | ); 19 | 20 | switch($method) { 21 | case 'POST': 22 | $options[CURLOPT_POST] = 1; 23 | $this->setRequestBody($request, $options); 24 | break; 25 | case 'PUT': 26 | $this->setRequestBody($request, $options); 27 | case 'DELETE': 28 | $options[CURLOPT_CUSTOMREQUEST] = $method; 29 | break; 30 | default: 31 | break; 32 | } 33 | 34 | //workaround to remove Expectation -> "Expect: 100-continue" that can be a problem in some networks 35 | $request->headers[] = 'Expect:'; 36 | $request->headers[] = 'Content-Type: ' . $request->contentType; 37 | $options[CURLOPT_HTTPHEADER] = $request->headers; 38 | 39 | $ch = curl_init(); 40 | curl_setopt_array($ch, $options); 41 | 42 | $response = new \eNotasGW\Api\response(); 43 | $response->body = curl_exec($ch); 44 | $response->contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); 45 | $response->code = curl_getinfo($ch, CURLINFO_HTTP_CODE); 46 | 47 | if($response->code != 200 && $response->isEmpty()) { 48 | $response->faultMessage = curl_error($ch); 49 | } 50 | 51 | return $response; 52 | } 53 | 54 | private function setRequestBody($request, &$options) { 55 | $body = $request->getRequestBody(); 56 | $options[CURLOPT_POSTFIELDS] = $body; 57 | 58 | if(is_string($body)) { 59 | $request->headers[] = 'Content-Length: ' . strlen($body); 60 | } 61 | } 62 | } 63 | ?> 64 | -------------------------------------------------------------------------------- /samples/WebHook/webHook.php: -------------------------------------------------------------------------------- 1 | '' 21 | )); 22 | 23 | function downloadXml($empresaId, $nfeId, $nfeNumero) { 24 | $xml = eNotasGW::$NFeApi->downloadXml($empresaId, $nfeId); 25 | file_put_contents("Notas\Autorizadas\NF-{$nfeNumero}.xml", $xml); 26 | } 27 | 28 | function downloadPdf($empresaId, $nfeId, $nfeNumero) { 29 | $pdf = eNotasGW::$NFeApi->downloadPdf($empresaId, $nfeId); 30 | file_put_contents("Notas\Autorizadas\NF-{$nfeNumero}.pdf", $pdf); 31 | } 32 | 33 | function gerarLogNFeNegada($id, $motivoStatus) { 34 | file_put_contents("Notas\Negadas\NF-{$id}-erros.txt", $motivoStatus); 35 | } 36 | 37 | $postContent = file_get_contents("php://input"); 38 | 39 | if(!empty($postContent)) { 40 | $formatter = eNotasGW::getMediaFormatter($_SERVER['CONTENT_TYPE']); 41 | $webHookData = $formatter->decode($postContent); 42 | 43 | switch(strtolower($webHookData->nfeStatus)) { 44 | case 'autorizada': 45 | downloadXml($webHookData->empresaId, $webHookData->nfeId, $webHookData->nfeNumero); 46 | downloadPdf($webHookData->empresaId, $webHookData->nfeId, $webHookData->nfeNumero); 47 | break; 48 | case 'negada': 49 | gerarLogNFeNegada((empty($webHookData->nfeIdExterno) ? $webHookData->nfeId : $webHookData->nfeIdExterno), 50 | $webHookData->nfeMotivoStatus); 51 | break; 52 | case 'cancelada': 53 | if(!empty($webHookData->nfeNumero)) { 54 | //download do pdf atualizado (com carimbo de cancelada) 55 | downloadPdf($webHookData->empresaId, $webHookData->nfeId, $webHookData->nfeNumero); 56 | } 57 | break; 58 | default: 59 | break; 60 | } 61 | } 62 | ?> -------------------------------------------------------------------------------- /src/empresaApi.php: -------------------------------------------------------------------------------- 1 | callOperation(array( 17 | 'path' => '/empresas/{empresaId}', 18 | 'parameters' => array( 19 | 'path' => array( 20 | 'empresaId' => $id 21 | ) 22 | ) 23 | )); 24 | } 25 | 26 | /** 27 | * Insere ou atualiza uma empresa 28 | * 29 | * @param mixed $dados dados da empresa que a serem utilizados na inserção ou atualização 30 | */ 31 | public function inserirAtualizar($dados) { 32 | return $this->callOperation(array( 33 | 'method' => 'POST', 34 | 'path' => '/empresas', 35 | 'parameters' => array( 36 | 'body' => $dados 37 | ) 38 | )); 39 | } 40 | 41 | /** 42 | * Atualiza a logo da empresa 43 | * 44 | * @param string $idEmpresa id da empresa para a qual a nota será emitida 45 | * @param fileParameter $file imagem a ser utilizada como logo. 46 | */ 47 | public function atualizarLogo($idEmpresa, $file) { 48 | $this->callOperation(array( 49 | 'method' => 'POST', 50 | 'decodeResponse' => FALSE, 51 | 'path' => '/empresas/{empresaId}/logo', 52 | 'parameters' => array( 53 | 'path' => array( 54 | 'empresaId' => $idEmpresa 55 | ), 56 | 'form' => array( 57 | 'logotipo' => $file 58 | ) 59 | ) 60 | )); 61 | } 62 | 63 | /** 64 | * Atualiza o certificado digital da empresa 65 | * 66 | * @param string $idEmpresa id da empresa para a qual a nota será emitida 67 | * @param fileParameter $file arquivo do certificado. 68 | * @param string $pass senha do certificado. 69 | */ 70 | public function atualizarCertificado($idEmpresa, $file, $pass) { 71 | $this->callOperation(array( 72 | 'method' => 'POST', 73 | 'decodeResponse' => FALSE, 74 | 'path' => '/empresas/{empresaId}/certificadoDigital', 75 | 'parameters' => array( 76 | 'path' => array( 77 | 'empresaId' => $idEmpresa 78 | ), 79 | 'form' => array( 80 | 'arquivo' => $file, 81 | 'senha' => $pass 82 | ) 83 | ) 84 | )); 85 | } 86 | } 87 | ?> 88 | -------------------------------------------------------------------------------- /src/eNotasGW.php: -------------------------------------------------------------------------------- 1 | new formatters\jsonFormatter(), 52 | 'multipart/form-data' => new formatters\formDataFormatter() 53 | ); 54 | 55 | if(!isset($config->apiKey)) { 56 | throw new Exception('A api key deve ser definida no método configure.'); 57 | } 58 | 59 | self::$_apiKey = $config->apiKey; 60 | 61 | if(isset($config->baseUrl)) { 62 | self::$_baseUrl = $config->baseUrl; 63 | } 64 | 65 | if(isset($config->version)) { 66 | self::$_version = $config->version; 67 | } 68 | 69 | if(isset($config->defaultContentType)) { 70 | self::$_defaultContentType = $config->defaultContentType; 71 | } 72 | 73 | if(isset($config->_trustedCAListPath)) { 74 | self::$_trustedCAListPath = $config->_trustedCAListPath; 75 | } 76 | else { 77 | self::$_trustedCAListPath = dirname(__FILE__) . '/files/ca-bundle.crt'; 78 | } 79 | 80 | self::$_versionedBaseUrl = self::$_baseUrl . '/v' . self::$_version; 81 | 82 | self::init(); 83 | } 84 | 85 | public static function getMediaFormatter($contentType) { 86 | $contentType = explode(';', $contentType); 87 | 88 | return self::$_formmaters[$contentType[0]]; 89 | } 90 | 91 | private static function init() { 92 | self::$_proxy = self::createProxy(); 93 | self::$NFeApi = new api\nfeApi(self::$_proxy); 94 | self::$EmpresaApi = new api\empresaApi(self::$_proxy); 95 | self::$PrefeituraApi = new api\prefeituraApi(self::$_proxy); 96 | self::$ServicosMunicipaisApi = new api\servicosMunicipaisApi(self::$_proxy); 97 | } 98 | 99 | private static function createProxy() { 100 | return new proxy\curlProxy(array( 101 | 'baseUrl' => self::$_versionedBaseUrl, 102 | 'apiKey' => self::$_apiKey, 103 | 'defaultContentType' => self::$_defaultContentType, 104 | 'trustedCAListPath' => self::$_trustedCAListPath 105 | )); 106 | } 107 | } 108 | ?> 109 | -------------------------------------------------------------------------------- /src/proxy/proxyBase.php: -------------------------------------------------------------------------------- 1 | executionCtx = (object)$executionCtx; 12 | } 13 | 14 | /** 15 | * Perform a request to the specified operation 16 | * @param array the operation info. 17 | * 18 | * For example: 19 | * 20 | * array( 21 | * 'path' => '/empresa/{empresaId}/certificadoDigital', 22 | * 'contentType' => 'multipart/form-data', 23 | * 'parameters' = array( 24 | * path => array( 25 | * 'empresaId' => '{24234-42342423-42442-43423}' 26 | * ), 27 | * form = array( 28 | * 'certificado' => $certificateRawData, 29 | * 'senha' => $certificatePassword 30 | * ) 31 | * ); 32 | * 33 | * @return $response 34 | */ 35 | public function doRequest($operation) { 36 | $operation = (object)$operation; 37 | $executionCtx = $this->executionCtx; 38 | $decodeResponse = (isset($operation->decodeResponse) ? $operation->decodeResponse : TRUE); 39 | 40 | $request = new \eNotasGW\Api\request(); 41 | $request->url = $this->buildUrl($operation); 42 | 43 | if(!empty($operation->method)) { 44 | $request->method = $operation->method; 45 | } 46 | 47 | $request->headers = $this->getDefaultHeaders($operation); 48 | $request->contentType = (isset($operation->contentType) ? $operation->contentType : $executionCtx->defaultContentType); 49 | 50 | $this->appendParameters($request, $operation->parameters); 51 | $response = $this->sendRequest($request); 52 | 53 | if($response->code != 200) { 54 | if($response->isEmpty() || $response->code == 404) { 55 | throw new Exceptions\requestException($response->code, $response->faultMessage, 56 | $request->url, $response->body); 57 | } 58 | else { 59 | $errors = $response->getResponseData(); 60 | 61 | switch($response->code) 62 | { 63 | case 401: 64 | throw new Exceptions\invalidApiKeyException($response->code, $errors); 65 | case 403: 66 | throw new Exceptions\unauthorizedException($response->code, $errors); 67 | default: 68 | throw new Exceptions\apiException($response->code, $errors); 69 | } 70 | } 71 | } 72 | 73 | if($decodeResponse) { 74 | return $response->getResponseData(); 75 | } 76 | 77 | return $response->body; 78 | } 79 | 80 | abstract protected function sendRequest($request); 81 | 82 | private function getDefaultHeaders($operation) { 83 | $executionCtx = $this->executionCtx; 84 | 85 | $headers = array( 86 | 'Accept: ' . $executionCtx->defaultContentType, 87 | 'Authorization: Basic ' . $executionCtx->apiKey 88 | ); 89 | 90 | return $headers; 91 | } 92 | 93 | private function appendParameters($request, $params) { 94 | if(!empty($params['body'])) { 95 | $request->parameters = $params['body']; 96 | } 97 | else if(!empty($params['form'])) { 98 | $request->parameters = $params['form']; 99 | //force request to be a form-data 100 | $request->contentType = 'multipart/form-data'; 101 | } 102 | } 103 | 104 | private function buildUrl($operation) { 105 | $path = $operation->path; 106 | $params = $operation->parameters; 107 | 108 | if($params !== FALSE) { 109 | if(!empty($params['path'])) { 110 | $pathParams = $params['path']; 111 | 112 | foreach($pathParams as $name => $value) { 113 | $path = str_replace('{' . $name . '}', rawurlencode($value), $path); 114 | } 115 | } 116 | 117 | if(!empty($params['query'])) { 118 | $path .= '?' . http_build_query($params['query']); 119 | } 120 | } 121 | 122 | return $this->executionCtx->baseUrl . $path; 123 | } 124 | } 125 | ?> 126 | -------------------------------------------------------------------------------- /samples/inserirAtualizarEmpresa.php: -------------------------------------------------------------------------------- 1 | '' 25 | )); 26 | 27 | try 28 | { 29 | $codigoIbgeCidade = 3106200; 30 | $caracteristicasPrefeitura = eNotasGW::$PrefeituraApi->consultar($codigoIbgeCidade); 31 | 32 | $dadosEmpresa = array( 33 | //'id' => 'CB09776E-E954-4D75-BBA6-E7A99FF20100', //informar apenas se quiser atualizar uma empresa existente 34 | 'cnpj' => '56308661000199', //sem formatação 35 | 'inscricaoMunicipal' => '12345', 36 | 'inscricaoEstadual' => null, 37 | 'razaoSocial' => 'Empresa de Teste Ltda', 38 | 'nomeFantasia' => 'Empresa de Teste', 39 | 'optanteSimplesNacional' => true, 40 | 'incentivadorCultural' => false, 41 | 'email' => null, 42 | 'telefoneComercial' => '3132323131', 43 | 'endereco' => array( 44 | 'uf' => 'MG', 45 | 'cidade' => 'Belo Horizonte', 46 | 'logradouro' => 'Rua 01', 47 | 'numero' => '112', 48 | 'complemento' => 'SL 102', 49 | 'bairro' => 'Savassi', 50 | 'cep' => '32323111' 51 | ), 52 | 'regimeEspecialTributacao' => '0', //A lista de valores possíveis deve ser obtida pela api de caraterísticas da prefeitura 53 | 'codigoServicoMunicipal' => '181309901', //código do serviço municipal padrão para emissão de NFS-e 54 | 'descricaoServico' => 'SERVICO DE SERIGRAFIA / SILK-SCREEN', //Descrição do serviço municipal padrão para emissão de NFS-e (utilizado apenas na impressão da NFS-e) 55 | 'aliquotaIss' => 2.00, 56 | 'configuracoesNFSeProducao' => array( 57 | 'sequencialNFe' => 1, 58 | 'serieNFe' => '2', 59 | 'sequencialLoteNFe' => 1 60 | ), 61 | 'configuracoesNFSeHomologacao' => array( 62 | 'sequencialNFe' => 1, 63 | 'serieNFe' => '2', 64 | 'sequencialLoteNFe' => 1 65 | ) 66 | ); 67 | 68 | if($caracteristicasPrefeitura->usaCNAE) { 69 | $dadosEmpresa->cnae = '1813099'; 70 | } 71 | 72 | if($caracteristicasPrefeitura->usaItemListaServico) { 73 | $dadosEmpresa->itemListaServicoLC116 = '13.05'; 74 | } 75 | 76 | if($caracteristicasPrefeitura->tipoAutenticacao == tipoAutenticacao::UsuarioESenha) { 77 | $dadosEmpresa['configuracoesNFSeProducao']['usuarioAcessoProvedor'] = '[usuario]'; 78 | $dadosEmpresa['configuracoesNFSeProducao']['senhaAcessoProvedor'] = '[senha]'; 79 | 80 | //opcional, preencher apenas se for emitir em ambiente de homologação 81 | $dadosEmpresa['configuracoesNFSeHomologacao']['usuarioAcessoProvedor'] = '[usuario]'; 82 | $dadosEmpresa['configuracoesNFSeHomologacao']['senhaAcessoProvedor'] = '[senha]'; 83 | } 84 | else if($caracteristicasPrefeitura->tipoAutenticacao == tipoAutenticacao::Token) { 85 | $dadosEmpresa['configuracoesNFSeProducao']['tokenAcessoProvedor'] = '[token]'; 86 | 87 | //opcional, preencher apenas se for emitir em ambiente de homologação 88 | $dadosEmpresa['configuracoesNFSeHomologacao']['tokenAcessoProvedor'] = '[token]'; 89 | } 90 | 91 | $result = eNotasGW::$EmpresaApi->inserirAtualizar($dadosEmpresa); 92 | $empresaId = $result->empresaId; 93 | 94 | echo 'empresa inserida com sucesso!'; 95 | echo '
ID: ' . $empresaId; 96 | echo '
'; 97 | echo '
'; 98 | 99 | //Necessita de certificado digital para autenticação ou assinatura da nota? 100 | if($caracteristicasPrefeitura->assinaturaDigital == tipoAssinaturaDigital::Obrigatorio 101 | || $caracteristicasPrefeitura->tipoAutenticacao == tipoAutenticacao::Certificado) { 102 | 103 | echo 'inserindo certificado digital...

'; 104 | 105 | $arquivoPfxOuP12 = fileParameter::fromPath('{certificate file path}', 106 | 'application/x-pkcs12', '{file name}'); 107 | $senhaDoArquivo = '{senha do arquivo .pfx ou .p12}'; 108 | 109 | eNotasGW::$EmpresaApi->atualizarCertificado($empresaId, $arquivoPfxOuP12, $senhaDoArquivo); 110 | echo '
Certificado incluído com sucesso!'; 111 | } 112 | } 113 | catch(Exceptions\invalidApiKeyException $ex) { 114 | echo 'Erro de autenticação:

'; 115 | echo $ex->getMessage(); 116 | } 117 | catch(Exceptions\unauthorizedException $ex) { 118 | echo 'Acesso negado:

'; 119 | echo $ex->getMessage(); 120 | } 121 | catch(Exceptions\apiException $ex) { 122 | echo 'Erro de validação:

'; 123 | echo $ex->getMessage(); 124 | } 125 | catch(Exceptions\requestException $ex) { 126 | echo 'Erro na requisição web:

'; 127 | 128 | echo 'Requested url: ' . $ex->requestedUrl; 129 | echo '
'; 130 | echo 'Response Code: ' . $ex->getCode(); 131 | echo '
'; 132 | echo 'Message: ' . $ex->getMessage(); 133 | echo '
'; 134 | echo 'Response Body: ' . $ex->responseBody; 135 | } 136 | ?> 137 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # eNotas GW PHP client 2 | 3 | Client escrito na linguagem PHP da API do eNotas Gateway, plataforma de emissão automática de nota fiscal eletrônica de serviço (NFS-e), Produto (NF-e) e Consumidor (NFC-e). 4 | 5 | ***Atenção: Esta biblioteca deve ser utilizada para a emissão de NFS-e (Nota fiscal de Serviço), caso você deseje emitir NF-e (Nota Fiscal de Produto) ou NFC-e (Nota Fiscal ao Consumidor) utilize a [bilioteca php-client-v2](https://github.com/eNotasGW/php-client-v2)*** 6 | 7 | ## Documentação 8 | 9 | Abaixo disponibilizamos as documentações oficiais do eNotas Gateway para consulta: 10 | * [Documentação de conceitos para utilização da API do eNotas GW](https://docs.enotasgw.com.br/docs) 11 | * [Documentação referencial dos endpoints da API do eNotas GW](https://docs.enotasgw.com.br/v1/reference) 12 | * [Swagger dos endpoints da API V1 do eNotas GW](http://app.enotasgw.com.br/docs) 13 | 14 | Além disso também consideramos que seja muito importante que você entenda como é o fluxo geral para a emissão de uma nota fiscal, para isso leia a documentação a seguir: 15 | * [Fluxo Geral para a emissão de uma nota fiscal](https://docs.enotasgw.com.br/docs/fluxo-geral) 16 | 17 | ## Instalação eNotas GW PHP client 18 | 19 | Para instalar manualmente esta biblioteca, basta clonar o repositório GIT para a sua máquina, conforme imagem abaixo: 20 | ![Clonando um repositório Github](https://raw.githubusercontent.com/eNotasGW/images-repository/master/php-client/clonando-repositorio.jpg) 21 | 22 | Ou através do comando: 23 | 24 | $ git clone https://github.com/eNotasGW/php-client 25 | 26 | Para instalar através do composer, basta utilizar o comando: 27 | 28 | composer require enotas/php-client 29 | 30 | ## Para utilizar o nosso cliente é fácil, veja: 31 | 32 | Após baixar os arquivos disponibilizados aqui, basta que você copie estes arquivos para a pasta da sua aplicação e faça referência à classe eNotasGW.php e, além disso você também precisará de duas informações: 33 | 34 | * [API Key](https://docs.enotasgw.com.br/v1/docs/como-obter-a-sua-api-key) 35 | * [Id da Empresa](https://docs.enotasgw.com.br/v1/docs/como-obter-o-id-da-empresa) 36 | 37 | 38 | 39 | Abaixo um exemplo simples para a emissão de nota fiscal: 40 | ```php 41 | '' 48 | )); 49 | 50 | $idEmpresa = '484FB0C5-969E-46AD-A047-8A0DB54667B4'; 51 | 52 | eNotasGW::$NFeApi->emitir($idEmpresa, array( 53 | 'tipo' => 'NFS-e', 54 | 'idExterno' => '5', //id para mapeamento com sistema de origem (opcional) 55 | 'ambienteEmissao' => 'Homologacao', //'Homologacao' ou 'Producao' 56 | 'cliente' => array( 57 | 'nome' => 'Nome Cliente', 58 | 'email' => 'cliente@mail.com', 59 | 'cpfCnpj' => '23857396237', 60 | 'tipoPessoa' => 'F', 61 | 'endereco' => array( 62 | 'uf' => 'MG', 63 | 'cidade' => 'Belo Horizonte', 64 | 'logradouro' => 'Rua 01', 65 | 'numero' => '112', 66 | 'bairro' => 'Savassi', 67 | 'cep' => '32323111' 68 | ) 69 | ), 70 | 'servico' => array( 71 | 'descricao' => 'Discriminação do serviço prestado' 72 | ), 73 | 'valorTotal' => 10.05 74 | )); 75 | ?> 76 | ``` 77 | 78 | ### Precisa de mais exemplos? Sem problemas! ;) 79 | 80 | Todos os nossos exemplos podem ser encontrados na pasta "samples": 81 | * [Clique aqui para ir para a pasta de exemplos](samples/) 82 | 83 | Ou se preferir, você pode ir diretamente para o arquivo que desejar, também fornecemos a documentação oficial para cada um dos itens: 84 | 85 | #### Emissão de nota fiscal 86 | - Arquivo de Exemplo 87 | - [Emitindo uma nota fiscal](samples/emissao.php) 88 | 89 | - Documentação 90 | - [Saiba mais sobre os campos da emissão de uma nota fiscal - Documentação](https://docs.enotasgw.com.br/v1/reference#emissao-de-nota-fiscal) 91 | 92 | #### Cancelamento de uma nota fiscal emitida 93 | - Arquivo de Exemplo 94 | - [Cancelando uma nota fiscal emitida](samples/cancelamento.php) 95 | 96 | - Documentação 97 | - [Saiba mais sobre os campos de cancelamento de uma nota fiscal utilizando o Id Interno](https://docs.enotasgw.com.br/v1/reference#cancelar-nota-fiscal) 98 | - [Saiba mais sobre os campos de cancelamento de uma nota fiscal utilizando o Id Externo](https://docs.enotasgw.com.br/v1/reference#cancelar-nota-fiscal-por-id-externo) 99 | 100 | #### Consultar uma nota fiscal 101 | - Arquivo de Exemplo 102 | - [Consultando uma nota fiscal - Arquivo de exemplo](samples/consulta.php) 103 | 104 | - Documentação 105 | - [Saiba mais sobre os campos de consultar uma nota fiscal utilizando o Id Interno](https://docs.enotasgw.com.br/v1/reference#empresasempresaidnfesnfeid) 106 | - [Saiba mais sobre os campos de consultar uma nota fiscal utilizando o Id Externo](https://docs.enotasgw.com.br/v1/reference#consultar-nota-fiscal-por-id-externo-identificador-externo) 107 | 108 | #### Fazer o download de uma nota fiscal emitida 109 | - Arquivo de Exemplo 110 | - [Baixando o PDF de uma nota fiscal emitida - Arquivo de exemplo](samples/downloadPdf.php) 111 | 112 | - Documentação 113 | - [Saiba mais sobre os campos para baixar o PDF de uma nota fiscal utilizando o Id Interno](https://docs.enotasgw.com.br/v1/reference#download-do-pdf) 114 | - [Saiba mais sobre os campos para baixar o PDF de uma nota fiscal utilizando o Id Externo](https://docs.enotasgw.com.br/v1/reference#download-do-pdf-por-idexterno) 115 | 116 | #### Fazer o download do XML de uma nota fiscal emitida 117 | - Arquivo de Exemplo 118 | - [Baixando o XML uma nota fiscal emitida](samples/downloadXml.php) 119 | 120 | - Documentação 121 | - [Saiba mais sobre os campos para baixar o XML de uma nota fiscal utilizando o Id Interno](https://docs.enotasgw.com.br/v1/reference#download-do-xml-da-nota-fiscal) 122 | - [Saiba mais sobre os campos para baixar o XML de uma nota fiscal utilizando o Id Externo](https://docs.enotasgw.com.br/v1/reference#download-do-xml-por-id-externo) 123 | 124 | #### Inserir ou atualizar uma empresa 125 | - [Inserir ou Atualizar uma empresa](samples/inserirAtualizarEmpresa.php) 126 | - [Saiba mais sobre os campos para Inserir/Atualizar uma empresa](https://docs.enotasgw.com.br/v1/reference#incluir-empresa) 127 | 128 | #### Upload do certificado de uma empresa 129 | - Arquivo de Exemplo 130 | - [Enviar o certificado de uma empresa](samples/uploadCertificadoEmpresa.php) 131 | 132 | - Documentação 133 | - [Saiba mais sobre os campos para vincular o certificado de uma empresa](https://docs.enotasgw.com.br/v1/reference#vincular-certificado-empresa) 134 | 135 | #### Upload do logo de uma empresa 136 | - Arquivo de Exemplo 137 | - [Enviar o logo de uma empresa](samples/uploadLogoEmpresa.php) 138 | 139 | - Documentação 140 | - [Saiba mais sobre os campos para vincular o logo de uma empresa](https://docs.enotasgw.com.br/v1/reference#vincular-logotipo) 141 | -------------------------------------------------------------------------------- /src/nfeApi.php: -------------------------------------------------------------------------------- 1 | callOperation(array( 18 | 'method' => 'POST', 19 | 'path' => '/empresas/{empresaId}/nfes', 20 | 'parameters' => array( 21 | 'path' => array( 22 | 'empresaId' => $idEmpresa 23 | ), 24 | 'body' => $dadosNFe 25 | ) 26 | )); 27 | 28 | return $result->nfeId; 29 | } 30 | 31 | /** 32 | * Cancela uma determinada Nota Fiscal 33 | * @param string $nfeId Identificador Único da Nota Fiscal 34 | * @param string $idEmpresa id da empresa para a qual a nota será emitida 35 | * @return string $nfeId retorna o id único da NFe no eNotas GW 36 | */ 37 | public function cancelar($idEmpresa, $nfeId) { 38 | $result = $this->callOperation(array( 39 | 'method' => 'DELETE', 40 | 'path' => '/empresas/{empresaId}/nfes/{nfeId}', 41 | 'parameters' => array( 42 | 'path' => array( 43 | 'empresaId' => $idEmpresa, 44 | 'nfeId' => $nfeId 45 | ) 46 | ) 47 | )); 48 | 49 | return $result->nfeId; 50 | } 51 | 52 | /** 53 | * Cancela uma determinada Nota Fiscal 54 | * @param string $idExterno id externo (mapeamento com sistema de origem) 55 | * @param string $idEmpresa id da empresa para a qual a nota será emitida 56 | * @return string $nfeId retorna o id único da NFe no eNotas GW 57 | */ 58 | public function cancelarPorIdExterno($idEmpresa, $idExterno) { 59 | $result = $this->callOperation(array( 60 | 'method' => 'DELETE', 61 | 'path' => '/empresas/{empresaId}/nfes/porIdExterno/{idExterno}', 62 | 'parameters' => array( 63 | 'path' => array( 64 | 'empresaId' => $idEmpresa, 65 | 'idExterno' => $idExterno 66 | ) 67 | ) 68 | )); 69 | 70 | return $result->nfeId; 71 | } 72 | 73 | /** 74 | * Consulta uma Nota Fiscal pelo Identificador Único 75 | * 76 | * @param string $idEmpresa id da empresa para a qual a nota será emitida 77 | * @param string $nfeId Identificador Único da Nota Fiscal 78 | * @return mixed $dadosNFe retorna os dados da nota como um array 79 | */ 80 | public function consultar($idEmpresa, $nfeId) { 81 | return $this->callOperation(array( 82 | 'path' => '/empresas/{empresaId}/nfes/{nfeId}', 83 | 'parameters' => array( 84 | 'path' => array( 85 | 'empresaId' => $idEmpresa, 86 | 'nfeId' => $nfeId 87 | ) 88 | ) 89 | )); 90 | } 91 | 92 | /** 93 | * Consulta uma Nota Fiscal pelo seu id externo (id de mapeamento com sistema de origem) 94 | * 95 | * @param string $idEmpresa id da empresa para a qual a nota será emitida 96 | * @param string $idExterno id externo (mapeamento com sistema de origem) 97 | * @return mixed $dadosNFe retorna os dados da nota como um array 98 | */ 99 | public function consultarPorIdExterno($idEmpresa, $idExterno) { 100 | return $this->callOperation(array( 101 | 'path' => '/empresas/{empresaId}/nfes/porIdExterno/{idExterno}', 102 | 'parameters' => array( 103 | 'path' => array( 104 | 'empresaId' => $idEmpresa, 105 | 'idExterno' => $idExterno 106 | ) 107 | ) 108 | )); 109 | } 110 | 111 | /** 112 | * Consulta notas fiscais emitidas em um determinado período 113 | * 114 | * @param string $idEmpresa id da empresa para a qual a nota será emitida 115 | * @param int $pageNumber numero da página no qual a pesquisa será feita 116 | * @param int $pageSize quantidade de registros por página 117 | * @param string $dataInicial data inicial para pesquisa 118 | * @param string $dataFinal data final para pesquisa 119 | * @return searchResult $listaNFe retorna uma lista contendo os registros encontrados na pesquisa 120 | */ 121 | public function consultarPorPeriodo($idEmpresa, $pageNumber, $pageSize, $dataInicial, $dataFinal) { 122 | $dataInicial = eNotasGWHelper::formatDateTime($dataInicial); 123 | $dataFinal = eNotasGWHelper::formatDateTime($dataFinal); 124 | 125 | return $this->callOperation(array( 126 | 'path' => '/empresas/{empresaId}/nfes', 127 | 'parameters' => array( 128 | 'path' => array( 129 | 'empresaId' => $idEmpresa 130 | ), 131 | 'query' => array( 132 | 'pageNumber' => $pageNumber, 133 | 'pageSize' => $pageSize, 134 | 'filter' => "dataCriacao ge '{$dataInicial}' and dataCriacao le '{$dataFinal}'" 135 | ) 136 | ) 137 | )); 138 | } 139 | 140 | /** 141 | * Download do xml de uma Nota Fiscal identificada pelo seu Identificador Único 142 | * 143 | * @param string $idEmpresa id da empresa para a qual a nota será emitida 144 | * @param string $nfeId Identificador Único da Nota Fiscal 145 | * @return string xml da nota fiscal 146 | */ 147 | public function downloadXml($idEmpresa, $nfeId) { 148 | return $this->callOperation(array( 149 | 'path' => '/empresas/{empresaId}/nfes/{nfeId}/xml', 150 | 'parameters' => array( 151 | 'path' => array( 152 | 'empresaId' => $idEmpresa, 153 | 'nfeId' => $nfeId 154 | ) 155 | ) 156 | )); 157 | } 158 | 159 | /** 160 | * Download do pdf de uma Nota Fiscal identificada pelo seu id externo (mapeamento com sistema de origem) 161 | * 162 | * @param string $idEmpresa id da empresa para a qual a nota será emitida 163 | * @param string $nfeId Identificador Único da Nota Fiscal 164 | * @return os bytes do arquivo pdf 165 | */ 166 | public function downloadPdf($idEmpresa, $nfeId) { 167 | return $this->callOperation(array( 168 | 'path' => '/empresas/{empresaId}/nfes/{nfeId}/pdf', 169 | 'decodeResponse' => FALSE, 170 | 'parameters' => array( 171 | 'path' => array( 172 | 'empresaId' => $idEmpresa, 173 | 'nfeId' => $nfeId 174 | ) 175 | ) 176 | )); 177 | } 178 | 179 | /** 180 | * Download do xml de uma Nota Fiscal identificada pelo seu id externo (mapeamento com sistema de origem) 181 | * 182 | * @param string $idEmpresa id da empresa para a qual a nota será emitida 183 | * @param string $idExterno id externo (mapeamento com sistema de origem) 184 | * @return string xml da nota fiscal 185 | */ 186 | public function downloadXmlPorIdExterno($idEmpresa, $idExterno) { 187 | return $this->callOperation(array( 188 | 'path' => '/empresas/{empresaId}/nfes/porIdExterno/{idExterno}/xml', 189 | 'parameters' => array( 190 | 'path' => array( 191 | 'empresaId' => $idEmpresa, 192 | 'idExterno' => $idExterno 193 | ) 194 | ) 195 | )); 196 | } 197 | 198 | /** 199 | * Download do xml de uma Nota Fiscal identificada pelo seu id externo (mapeamento com sistema de origem) 200 | * 201 | * @param string $idEmpresa id da empresa para a qual a nota será emitida 202 | * @param string $idExterno id externo (mapeamento com sistema de origem) 203 | * @return os bytes do arquivo pdf 204 | */ 205 | public function downloadPdfPorIdExterno($idEmpresa, $idExterno) { 206 | return $this->callOperation(array( 207 | 'path' => '/empresas/{empresaId}/nfes/porIdExterno/{idExterno}/pdf', 208 | 'decodeResponse' => FALSE, 209 | 'parameters' => array( 210 | 'path' => array( 211 | 'empresaId' => $idEmpresa, 212 | 'idExterno' => $idExterno 213 | ) 214 | ) 215 | )); 216 | } 217 | } 218 | ?> 219 | --------------------------------------------------------------------------------