Skip to content

Configuración de URLs

Esta sección proporciona las URLs base para los diferentes entornos de la API de Facturación Electrónica.

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 Pruebas
FINANCIEROBASE_URL=https://test-api-factura.edw-dev.com
FINANCIEROCLIENT_ID=tu_client_id
FINANCIEROCLIENT_SECRET=tu_client_secret
FINANCIEROUSERNAME=tu_username
FINANCIEROPASSWORD=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);
}
}

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 Pruebas
FINANCIEROBASE_URL=https://test-api-factura.edw-dev.com
FINANCIEROCLIENT_ID=tu_client_id
FINANCIEROCLIENT_SECRET=tu_client_secret
FINANCIEROUSERNAME=tu_username
FINANCIEROPASSWORD=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;

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
// En tu controlador
use 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());
}
}
const FinancieroApiService = require('./services/FinancieroApiService');
const financieroApi = new FinancieroApiService();
// Ejemplo de uso
async function getDocuments() {
try {
const documents = await financieroApi.makeRequest('GET', '/api/v1/documents');
console.log(documents);
return documents;
} catch (error) {
console.error('Error:', error.message);
}
}
  1. Seguridad: Nunca hardcodees las credenciales en tu código. Siempre usa variables de entorno.

  2. Tokens: Los tokens tienen una duración limitada (generalmente 1 hora). Los servicios proporcionados manejan automáticamente la renovación.

  3. Rate Limiting: Respeta los límites de velocidad de la API para evitar bloqueos.

  4. Logs: En producción, asegúrate de no loggear información sensible como tokens o credenciales.

  5. Certificados SSL: En producción, verifica siempre los certificados SSL.