Configuración de URLs
Configuración de URLs
Section titled “Configuración de URLs”Dominio: https://test-api-factura.edw-dev.com
Dominio: https://api-financiero.e-dinky.com
Esta sección proporciona las URLs base para los diferentes entornos de la API de Facturación Electrónica.
Configuración por Tecnología
Section titled “Configuración por Tecnología”Laravel PHP
Section titled “Laravel PHP”Crea un archivo de configuración config/services.php
:
<?php
return [ 'base_url' => env('FINANCIEROBASE_URL', 'https://test-api-factura.edw-dev.com'), 'client_id' => env('FINANCIEROCLIENT_ID'), 'client_secret' => env('FINANCIEROCLIENT_SECRET'), 'username' => env('FINANCIEROUSERNAME'), 'password' => env('FINANCIEROPASSWORD'),];
En tu archivo .env
:
# Entorno de PruebasFINANCIEROBASE_URL=https://test-api-factura.edw-dev.comFINANCIEROCLIENT_ID=tu_client_idFINANCIEROCLIENT_SECRET=tu_client_secretFINANCIEROUSERNAME=tu_usernameFINANCIEROPASSWORD=tu_password
# Para Producción, cambia la URL:# FINANCIEROBASE_URL=https://api-financiero.e-dinky.com
Clase de servicio para Laravel:
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Cache;
class FinancieroApiService{ private $baseUrl; private $clientId; private $clientSecret; private $username; private $password;
public function __construct() { $this->baseUrl = config('services.base_url'); $this->clientId = config('services.client_id'); $this->clientSecret = config('services.client_secret'); $this->username = config('services.username'); $this->password = config('services.password'); }
public function getToken() { return Cache::remember('FINANCIEROtoken', 3600, function () { $response = Http::asForm()->post($this->baseUrl . '/oauth/token', [ 'grant_type' => 'password', 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret, 'username' => $this->username, 'password' => $this->password, ]);
if ($response->successful()) { return $response->json()['access_token']; }
throw new \Exception('Error al obtener token: ' . $response->body()); }); }
public function makeRequest($method, $endpoint, $data = []) { $token = $this->getToken();
return Http::withHeaders([ 'Authorization' => 'Bearer ' . $token, 'Accept' => 'application/json', 'Content-Type' => 'application/json' ])->{$method}($this->baseUrl . $endpoint, $data); }}
Node.js
Section titled “Node.js”Crea un archivo config/services.js
:
module.exports = { baseUrl: process.env.FINANCIEROBASE_URL || 'https://test-api-factura.edw-dev.com', clientId: process.env.FINANCIEROCLIENT_ID, clientSecret: process.env.FINANCIEROCLIENT_SECRET, username: process.env.FINANCIEROUSERNAME, password: process.env.FINANCIEROPASSWORD};
En tu archivo .env
:
# Entorno de PruebasFINANCIEROBASE_URL=https://test-api-factura.edw-dev.comFINANCIEROCLIENT_ID=tu_client_idFINANCIEROCLIENT_SECRET=tu_client_secretFINANCIEROUSERNAME=tu_usernameFINANCIEROPASSWORD=tu_password
# Para Producción, cambia la URL:# FINANCIEROBASE_URL=https://api-financiero.e-dinky.com
Clase de servicio para Node.js:
const axios = require('axios');const config = require('./config/services');
class FinancieroApiService { constructor() { this.baseUrl = config.baseUrl; this.clientId = config.clientId; this.clientSecret = config.clientSecret; this.username = config.username; this.password = config.password; this.token = null; this.tokenExpiry = null; }
async getToken() { // Verificar si el token aún es válido if (this.token && this.tokenExpiry && Date.now() < this.tokenExpiry) { return this.token; }
try { const response = await axios.post(`${this.baseUrl}/oauth/token`, { grant_type: 'password', client_id: this.clientId, client_secret: this.clientSecret, username: this.username, password: this.password }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
this.token = response.data.access_token; // Establecer expiración 5 minutos antes del tiempo real this.tokenExpiry = Date.now() + (response.data.expires_in - 300) * 1000;
return this.token; } catch (error) { throw new Error(`Error al obtener token: ${error.response?.data || error.message}`); } }
async makeRequest(method, endpoint, data = {}) { const token = await this.getToken();
const config = { method, url: `${this.baseUrl}${endpoint}`, headers: { 'Authorization': `Bearer ${token}`, 'Accept': 'application/json', 'Content-Type': 'application/json' } };
if (method.toLowerCase() !== 'get' && Object.keys(data).length > 0) { config.data = data; } else if (method.toLowerCase() === 'get' && Object.keys(data).length > 0) { config.params = data; }
try { const response = await axios(config); return response.data; } catch (error) { throw new Error(`Error en la solicitud: ${error.response?.data || error.message}`); } }}
module.exports = FinancieroApiService;
Variables de Entorno
Section titled “Variables de Entorno”Para cambiar entre entornos, simplemente modifica la variable FINANCIEROBASE_URL
en tu archivo .env
:
Entorno de Pruebas:
FINANCIEROBASE_URL=https://test-api-factura.edw-dev.com
Entorno de Producción:
FINANCIEROBASE_URL=https://api-financiero.e-dinky.com
Uso de los Servicios
Section titled “Uso de los Servicios”Laravel
Section titled “Laravel”// En tu controladoruse App\Services\FinancieroApiService;
class DocumentController extends Controller{ private $financieroApi;
public function __construct(FinancieroApiService $financieroApi) { $this->financieroApi = $financieroApi; }
public function getDocuments() { $response = $this->financieroApi->makeRequest('GET', '/api/v1/documents'); return response()->json($response->json()); }}
Node.js
Section titled “Node.js”const FinancieroApiService = require('./services/FinancieroApiService');
const financieroApi = new FinancieroApiService();
// Ejemplo de usoasync function getDocuments() { try { const documents = await financieroApi.makeRequest('GET', '/api/v1/documents'); console.log(documents); return documents; } catch (error) { console.error('Error:', error.message); }}
Notas Importantes
Section titled “Notas Importantes”-
Seguridad: Nunca hardcodees las credenciales en tu código. Siempre usa variables de entorno.
-
Tokens: Los tokens tienen una duración limitada (generalmente 1 hora). Los servicios proporcionados manejan automáticamente la renovación.
-
Rate Limiting: Respeta los límites de velocidad de la API para evitar bloqueos.
-
Logs: En producción, asegúrate de no loggear información sensible como tokens o credenciales.
-
Certificados SSL: En producción, verifica siempre los certificados SSL.