Compare commits
3 Commits
0cb1c37566
...
387e136707
| Author | SHA1 | Date | |
|---|---|---|---|
| 387e136707 | |||
| 9a1e36337d | |||
| 0c28302f84 |
@@ -1,7 +1,7 @@
|
||||
APP_NAME=Laravel
|
||||
APP_ENV=local
|
||||
APP_ENV=production
|
||||
APP_KEY=
|
||||
APP_DEBUG=true
|
||||
APP_DEBUG=false
|
||||
APP_URL=http://localhost
|
||||
FRONTEND_URL=http://localhost:4200
|
||||
INTEGRATION_SECRET=
|
||||
|
||||
141
app/Domains/Integration/Services/BaseIntegrationService.php
Normal file
141
app/Domains/Integration/Services/BaseIntegrationService.php
Normal file
@@ -0,0 +1,141 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use App\Domains\Integration\Models\TenantIntegration;
|
||||
use Exception;
|
||||
|
||||
abstract class BaseIntegrationService
|
||||
{
|
||||
/**
|
||||
* The unique code of the integration.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $integrationCode;
|
||||
|
||||
/**
|
||||
* The current tenant code.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $tenantCode;
|
||||
|
||||
/**
|
||||
* The integration model instance.
|
||||
*
|
||||
* @var Integration|null
|
||||
*/
|
||||
protected ?Integration $integration = null;
|
||||
|
||||
/**
|
||||
* The tenant-specific integration model instance.
|
||||
*
|
||||
* @var TenantIntegration|null
|
||||
*/
|
||||
protected ?TenantIntegration $tenantIntegration = null;
|
||||
|
||||
/**
|
||||
* Set the integration code.
|
||||
*
|
||||
* @param string $integrationCode
|
||||
* @return $this
|
||||
*/
|
||||
public function setIntegrationCode(string $integrationCode): self
|
||||
{
|
||||
$this->integrationCode = $integrationCode;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the integration code.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getIntegrationCode(): string
|
||||
{
|
||||
return $this->integrationCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the tenant code and load the integration models.
|
||||
*
|
||||
* @param string $tenantCode
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
*/
|
||||
public function forTenant(string $tenantCode): self
|
||||
{
|
||||
$this->tenantCode = $tenantCode;
|
||||
$this->loadIntegration();
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the Integration and TenantIntegration models.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
protected function loadIntegration(): void
|
||||
{
|
||||
if (empty($this->integrationCode)) {
|
||||
throw new Exception("Integration code is not set.");
|
||||
}
|
||||
|
||||
$this->integration = Integration::where('integration_code', $this->integrationCode)->first();
|
||||
if (!$this->integration) {
|
||||
throw new Exception("Integration with code '{$this->integrationCode}' not found.");
|
||||
}
|
||||
|
||||
$this->tenantIntegration = TenantIntegration::where('tenant_code', $this->tenantCode)
|
||||
->where('integration_code', $this->integrationCode)
|
||||
->first();
|
||||
|
||||
if (!$this->tenantIntegration) {
|
||||
throw new Exception("Tenant '{$this->tenantCode}' does not have integration '{$this->integrationCode}' configured.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the request URL.
|
||||
*
|
||||
* @param string $path
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getUrl(string $path = ''): string
|
||||
{
|
||||
if (!$this->integration) {
|
||||
throw new Exception("Integration is not loaded. Call forTenant() first.");
|
||||
}
|
||||
|
||||
$baseUrl = rtrim($this->integration->url, '/');
|
||||
$path = ltrim($path, '/');
|
||||
|
||||
return $path !== '' ? "{$baseUrl}/{$path}" : $baseUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get integration setting by key from tenant's integration data.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $default
|
||||
* @return mixed
|
||||
*/
|
||||
protected function getIntegrationSetting(string $key, mixed $default = null): mixed
|
||||
{
|
||||
if (!$this->tenantIntegration || !$this->tenantIntegration->integration_data) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
return $this->tenantIntegration->integration_data[$key] ?? $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the headers for the integration.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
abstract public function getHeaders(): array;
|
||||
}
|
||||
118
app/Domains/Integration/Services/TelepagosIntegrationService.php
Normal file
118
app/Domains/Integration/Services/TelepagosIntegrationService.php
Normal file
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use Exception;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class TelepagosIntegrationService extends BaseIntegrationService
|
||||
{
|
||||
/**
|
||||
* TelepagosIntegrationService constructor.
|
||||
*
|
||||
* @param string $integrationCode
|
||||
*/
|
||||
public function __construct(string $integrationCode = 'telepagos')
|
||||
{
|
||||
// Force homologation code if not in production and using default
|
||||
if ($integrationCode === 'telepagos' && !app()->environment('production')) {
|
||||
$integrationCode = 'telepagos_homo';
|
||||
}
|
||||
|
||||
$this->integrationCode = $integrationCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the headers for Telepagos integration.
|
||||
*
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getHeaders(): array
|
||||
{
|
||||
return [
|
||||
'Authorization' => 'Bearer ' . $this->getToken(),
|
||||
'Content-Type' => 'application/json',
|
||||
'Accept' => 'application/json',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a valid token, either from cache or by performing a login.
|
||||
*
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getToken(): string
|
||||
{
|
||||
if (!$this->tenantIntegration) {
|
||||
throw new Exception("Tenant integration is not loaded. Call forTenant() first.");
|
||||
}
|
||||
|
||||
$cacheKey = "integration_token:{$this->tenantCode}:{$this->integrationCode}";
|
||||
|
||||
$token = Cache::get($cacheKey);
|
||||
|
||||
if ($token) {
|
||||
return $token;
|
||||
}
|
||||
|
||||
return $this->login();
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate with Telepagos and cache the returned token.
|
||||
*
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function login(): string
|
||||
{
|
||||
$username = $this->getIntegrationSetting('username');
|
||||
$password = $this->getIntegrationSetting('password');
|
||||
|
||||
if (empty($username) || empty($password)) {
|
||||
throw new Exception("Missing username or password in Telepagos integration settings.");
|
||||
}
|
||||
|
||||
$url = $this->getUrl('/v2/auth/token');
|
||||
|
||||
$response = Http::post($url, [
|
||||
'username' => $username,
|
||||
'password' => $password,
|
||||
]);
|
||||
|
||||
if ($response->failed() || $response->json('status') !== 'ok') {
|
||||
throw new Exception("Telepagos authentication failed: " . ($response->json('message') ?? $response->body()));
|
||||
}
|
||||
|
||||
$token = $response->json('token');
|
||||
$expiresAtStr = $response->json('expires_at');
|
||||
|
||||
if (!$token || !$expiresAtStr) {
|
||||
throw new Exception("Telepagos authentication response is missing token or expires_at.");
|
||||
}
|
||||
|
||||
$expiresAt = Carbon::parse($expiresAtStr);
|
||||
// Calculate TTL and subtract a buffer of 60 seconds
|
||||
$ttlSeconds = max(1, $expiresAt->diffInSeconds(now()) - 60);
|
||||
|
||||
$cacheKey = "integration_token:{$this->tenantCode}:{$this->integrationCode}";
|
||||
Cache::put($cacheKey, $token, $ttlSeconds);
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the cached token.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function clearToken(): void
|
||||
{
|
||||
$cacheKey = "integration_token:{$this->tenantCode}:{$this->integrationCode}";
|
||||
Cache::forget($cacheKey);
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,6 @@ class StorePurchaseRequest extends FormRequest
|
||||
{
|
||||
return [
|
||||
'status' => ['sometimes', 'string', Rule::in(['pending', 'paid', 'cancelled'])],
|
||||
'payment_status' => ['sometimes', 'string', Rule::in(['pending', 'approved', 'rejected'])],
|
||||
'payment_method' => ['required', 'string'],
|
||||
'dni' => ['required', 'string'],
|
||||
'telefono' => ['required', 'string'],
|
||||
|
||||
250
tests/Feature/Integration/IntegrationServiceTest.php
Normal file
250
tests/Feature/Integration/IntegrationServiceTest.php
Normal file
@@ -0,0 +1,250 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Integration;
|
||||
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use App\Domains\Integration\Models\TenantIntegration;
|
||||
use App\Domains\Integration\Services\TelepagosIntegrationService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Tests\TestCase;
|
||||
use Exception;
|
||||
|
||||
class IntegrationServiceTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private Tenant $tenant;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
// Set the integrations secret for tests
|
||||
config(['services.integrations.secret' => 'base64:' . base64_encode(random_bytes(32))]);
|
||||
|
||||
// Clear cache to prevent test pollution
|
||||
Cache::flush();
|
||||
|
||||
$hdrKey = (string) \Illuminate\Support\Str::uuid();
|
||||
$ftrKey = (string) \Illuminate\Support\Str::uuid();
|
||||
|
||||
$headerAttachment = \App\Domains\Attachable\Models\Attachment::create([
|
||||
'key' => $hdrKey,
|
||||
'path' => 'tenants/' . $hdrKey . '.png',
|
||||
'filename' => 'logo_header.png',
|
||||
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
|
||||
'mime_type' => 'image/png',
|
||||
]);
|
||||
$footerAttachment = \App\Domains\Attachable\Models\Attachment::create([
|
||||
'key' => $ftrKey,
|
||||
'path' => 'tenants/' . $ftrKey . '.png',
|
||||
'filename' => 'logo_footer.png',
|
||||
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
|
||||
'mime_type' => 'image/png',
|
||||
]);
|
||||
|
||||
// Create a test tenant
|
||||
$this->tenant = Tenant::create([
|
||||
'codigo' => 'test-tenant',
|
||||
'nombre' => 'Test Tenant',
|
||||
'dominio' => 'test.com',
|
||||
'primary_color' => '#ffffff',
|
||||
'secondary_color' => '#ffffff',
|
||||
'danger_color' => '#ffffff',
|
||||
'success_color' => '#ffffff',
|
||||
'header_bg_color' => '#ffffff',
|
||||
'footer_bg_color' => '#ffffff',
|
||||
'header_logo_id' => $headerAttachment->id,
|
||||
'footer_logo_id' => $footerAttachment->id,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_throws_exception_if_integration_code_is_invalid(): void
|
||||
{
|
||||
$service = new TelepagosIntegrationService('invalid_code');
|
||||
|
||||
$this->expectException(Exception::class);
|
||||
$this->expectExceptionMessage("Integration with code 'invalid_code' not found.");
|
||||
|
||||
$service->forTenant($this->tenant->codigo);
|
||||
}
|
||||
|
||||
public function test_it_throws_exception_if_tenant_integration_is_not_configured(): void
|
||||
{
|
||||
// Seed integration but don't configure for tenant
|
||||
Integration::create([
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'name' => 'Telepagos',
|
||||
'url' => 'https://api.telepagos.com.ar',
|
||||
'integration_data_schema' => [
|
||||
'username' => 'required|string',
|
||||
'password' => 'required|string',
|
||||
]
|
||||
]);
|
||||
|
||||
$service = new TelepagosIntegrationService('telepagos');
|
||||
|
||||
$this->expectException(Exception::class);
|
||||
$this->expectExceptionMessage("Tenant 'test-tenant' does not have integration 'telepagos_homo' configured.");
|
||||
|
||||
$service->forTenant($this->tenant->codigo);
|
||||
}
|
||||
|
||||
public function test_it_resolves_base_url_and_paths(): void
|
||||
{
|
||||
Integration::create([
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'name' => 'Telepagos',
|
||||
'url' => 'https://api.telepagos.com.ar/', // Trailing slash to test trimming
|
||||
'integration_data_schema' => [
|
||||
'username' => 'required|string',
|
||||
'password' => 'required|string',
|
||||
]
|
||||
]);
|
||||
|
||||
TenantIntegration::create([
|
||||
'tenant_code' => $this->tenant->codigo,
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'integration_data' => [
|
||||
'username' => 'user123',
|
||||
'password' => 'pass123',
|
||||
]
|
||||
]);
|
||||
|
||||
$service = new TelepagosIntegrationService('telepagos');
|
||||
$service->forTenant($this->tenant->codigo);
|
||||
|
||||
$this->assertEquals('https://api.telepagos.com.ar', $service->getUrl());
|
||||
$this->assertEquals('https://api.telepagos.com.ar/v1/payments', $service->getUrl('v1/payments'));
|
||||
$this->assertEquals('https://api.telepagos.com.ar/v1/payments', $service->getUrl('/v1/payments'));
|
||||
}
|
||||
|
||||
public function test_it_generates_correct_headers_for_telepagos_using_cached_token(): void
|
||||
{
|
||||
Integration::create([
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'name' => 'Telepagos',
|
||||
'url' => 'https://api.telepagos.com.ar',
|
||||
'integration_data_schema' => [
|
||||
'username' => 'required|string',
|
||||
'password' => 'required|string',
|
||||
]
|
||||
]);
|
||||
|
||||
TenantIntegration::create([
|
||||
'tenant_code' => $this->tenant->codigo,
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'integration_data' => [
|
||||
'username' => 'tele_user',
|
||||
'password' => 'tele_pass',
|
||||
]
|
||||
]);
|
||||
|
||||
// Mock HTTP response sequence for authentication
|
||||
Http::fake([
|
||||
'https://api.telepagos.com.ar/v2/auth/token' => Http::sequence()
|
||||
->push([
|
||||
'status' => 'ok',
|
||||
'token' => 'mock-jwt-token-123',
|
||||
'expires_at' => now()->addHour()->toDateTimeString()
|
||||
], 200)
|
||||
->push([
|
||||
'status' => 'ok',
|
||||
'token' => 'new-mock-jwt-token',
|
||||
'expires_at' => now()->addHour()->toDateTimeString()
|
||||
], 200)
|
||||
]);
|
||||
|
||||
$service = new TelepagosIntegrationService('telepagos');
|
||||
$service->forTenant($this->tenant->codigo);
|
||||
|
||||
// Fetch headers first time (triggers API login)
|
||||
$headers = $service->getHeaders();
|
||||
|
||||
$this->assertEquals('Bearer mock-jwt-token-123', $headers['Authorization']);
|
||||
$this->assertEquals('application/json', $headers['Content-Type']);
|
||||
$this->assertEquals('application/json', $headers['Accept']);
|
||||
|
||||
// Assert HTTP call was made once
|
||||
Http::assertSentCount(1);
|
||||
|
||||
// Retrieve token again, should be same (cached)
|
||||
$this->assertEquals('mock-jwt-token-123', $service->getToken());
|
||||
Http::assertSentCount(1); // Still 1 since it's cached!
|
||||
|
||||
// Clear token, should trigger another API login (sequence returns second token)
|
||||
$service->clearToken();
|
||||
$this->assertEquals('new-mock-jwt-token', $service->getToken());
|
||||
Http::assertSentCount(2);
|
||||
}
|
||||
|
||||
public function test_it_throws_exception_if_credentials_are_missing(): void
|
||||
{
|
||||
Integration::create([
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'name' => 'Telepagos',
|
||||
'url' => 'https://api.telepagos.com.ar',
|
||||
'integration_data_schema' => [
|
||||
'username' => 'required|string',
|
||||
'password' => 'required|string',
|
||||
]
|
||||
]);
|
||||
|
||||
TenantIntegration::create([
|
||||
'tenant_code' => $this->tenant->codigo,
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'integration_data' => [
|
||||
'username' => '',
|
||||
'password' => 'tele_pass',
|
||||
]
|
||||
]);
|
||||
|
||||
$service = new TelepagosIntegrationService('telepagos');
|
||||
$service->forTenant($this->tenant->codigo);
|
||||
|
||||
$this->expectException(Exception::class);
|
||||
$this->expectExceptionMessage("Missing username or password in Telepagos integration settings.");
|
||||
|
||||
$service->getToken();
|
||||
}
|
||||
|
||||
public function test_it_throws_exception_if_api_fails(): void
|
||||
{
|
||||
Integration::create([
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'name' => 'Telepagos',
|
||||
'url' => 'https://api.telepagos.com.ar',
|
||||
'integration_data_schema' => [
|
||||
'username' => 'required|string',
|
||||
'password' => 'required|string',
|
||||
]
|
||||
]);
|
||||
|
||||
TenantIntegration::create([
|
||||
'tenant_code' => $this->tenant->codigo,
|
||||
'integration_code' => 'telepagos_homo',
|
||||
'integration_data' => [
|
||||
'username' => 'tele_user',
|
||||
'password' => 'tele_pass',
|
||||
]
|
||||
]);
|
||||
|
||||
Http::fake([
|
||||
'https://api.telepagos.com.ar/v2/auth/token' => Http::response([
|
||||
'status' => 'error',
|
||||
'message' => 'Invalid credentials'
|
||||
], 401)
|
||||
]);
|
||||
|
||||
$service = new TelepagosIntegrationService('telepagos');
|
||||
$service->forTenant($this->tenant->codigo);
|
||||
|
||||
$this->expectException(Exception::class);
|
||||
$this->expectExceptionMessage("Telepagos authentication failed: Invalid credentials");
|
||||
|
||||
$service->getToken();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user