Intégration fonctionnalites V1
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Booking;
|
||||
use App\Models\Establishment;
|
||||
use App\Models\Machine;
|
||||
use App\Models\MachineEvent;
|
||||
use App\Models\Supervisor;
|
||||
@@ -15,14 +16,14 @@ class DashboardService
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function getKpis(Supervisor $supervisor): array
|
||||
public function getKpis(Supervisor $supervisor, ?int $establishmentFilter = null): array
|
||||
{
|
||||
$offlineThresholdMinutes = (int) config('laverie.machine.offline_threshold_minutes', 10);
|
||||
$today = Carbon::today();
|
||||
|
||||
$washQuery = $this->washQuery($supervisor)->whereDate('started_at', $today);
|
||||
$bookingQuery = $this->bookingQuery($supervisor)->whereDate('slot_start', $today);
|
||||
$machineQuery = $this->machineQuery($supervisor);
|
||||
$washQuery = $this->washQuery($supervisor, $establishmentFilter)->whereDate('started_at', $today);
|
||||
$bookingQuery = $this->bookingQuery($supervisor, $establishmentFilter)->whereDate('slot_start', $today);
|
||||
$machineQuery = $this->machineQuery($supervisor, $establishmentFilter);
|
||||
|
||||
$offlineThreshold = now()->subMinutes($offlineThresholdMinutes);
|
||||
|
||||
@@ -36,6 +37,8 @@ class DashboardService
|
||||
})
|
||||
->count();
|
||||
|
||||
$machinesTotal = (clone $machineQuery)->count();
|
||||
|
||||
return [
|
||||
'revenue_today' => (float) (clone $washQuery)
|
||||
->where('status', 'completed')
|
||||
@@ -43,16 +46,85 @@ class DashboardService
|
||||
'washes_today' => (clone $washQuery)->count(),
|
||||
'bookings_today' => (clone $bookingQuery)->count(),
|
||||
'offline_machines' => $offlineCount,
|
||||
'machines_total' => (clone $machineQuery)->count(),
|
||||
'machines_total' => $machinesTotal,
|
||||
'running_machines' => (clone $machineQuery)->where('status', 'running')->count(),
|
||||
'available_machines' => (clone $machineQuery)->where('status', 'available')->count(),
|
||||
'active_bookings' => $this->bookingQuery($supervisor, $establishmentFilter)
|
||||
->whereIn('status', ['confirmed', 'active'])
|
||||
->where('slot_end', '>=', now())
|
||||
->count(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, int>
|
||||
*/
|
||||
public function getMachineStatusBreakdown(Supervisor $supervisor, ?int $establishmentFilter = null): array
|
||||
{
|
||||
$statuses = ['available', 'reserved', 'running', 'maintenance', 'offline', 'error'];
|
||||
$counts = $this->machineQuery($supervisor, $establishmentFilter)
|
||||
->selectRaw('status, COUNT(*) as count')
|
||||
->groupBy('status')
|
||||
->pluck('count', 'status');
|
||||
|
||||
$breakdown = [];
|
||||
foreach ($statuses as $status) {
|
||||
$breakdown[$status] = (int) ($counts[$status] ?? 0);
|
||||
}
|
||||
|
||||
return $breakdown;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, array<string, mixed>>
|
||||
*/
|
||||
public function getRecentWashes(Supervisor $supervisor, ?int $establishmentFilter = null, int $limit = 5): Collection
|
||||
{
|
||||
return $this->washQuery($supervisor, $establishmentFilter)
|
||||
->with(['machine:id,name,uuid', 'machine.establishment:id,name'])
|
||||
->orderByDesc('started_at')
|
||||
->limit($limit)
|
||||
->get()
|
||||
->map(fn (Wash $wash) => [
|
||||
'uuid' => $wash->uuid,
|
||||
'machine_name' => $wash->machine?->name ?? '—',
|
||||
'establishment_name' => $wash->machine?->establishment?->name,
|
||||
'status' => $wash->status,
|
||||
'status_label' => $this->washStatusLabel($wash->status),
|
||||
'cost' => (float) $wash->cost,
|
||||
'started_at' => $wash->started_at?->toIso8601String(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string|null>
|
||||
*/
|
||||
public function getContext(Supervisor $supervisor, ?int $establishmentFilter = null): array
|
||||
{
|
||||
$supervisor->loadMissing(['organization:id,name', 'establishment:id,name']);
|
||||
|
||||
$establishmentName = $supervisor->establishment?->name;
|
||||
|
||||
if ($establishmentName === null && $establishmentFilter !== null) {
|
||||
$establishmentName = Establishment::query()
|
||||
->where('id', $establishmentFilter)
|
||||
->where('organization_id', $supervisor->organization_id)
|
||||
->value('name');
|
||||
}
|
||||
|
||||
return [
|
||||
'organization_name' => $supervisor->organization?->name,
|
||||
'establishment_name' => $establishmentName,
|
||||
'is_all_establishments' => $supervisor->establishment_id === null && $establishmentFilter === null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, array<string, mixed>>
|
||||
*/
|
||||
public function getAlerts(Supervisor $supervisor, int $limit = 10): Collection
|
||||
public function getAlerts(Supervisor $supervisor, ?int $establishmentFilter = null, int $limit = 10): Collection
|
||||
{
|
||||
$machineIds = $this->machineQuery($supervisor)->pluck('id');
|
||||
$machineIds = $this->machineQuery($supervisor, $establishmentFilter)->pluck('id');
|
||||
|
||||
if ($machineIds->isEmpty()) {
|
||||
return collect();
|
||||
@@ -104,9 +176,9 @@ class DashboardService
|
||||
/**
|
||||
* @return Collection<int, array<string, mixed>>
|
||||
*/
|
||||
public function getMachinesOverview(Supervisor $supervisor): Collection
|
||||
public function getMachinesOverview(Supervisor $supervisor, ?int $establishmentFilter = null): Collection
|
||||
{
|
||||
return $this->machineQuery($supervisor)
|
||||
return $this->machineQuery($supervisor, $establishmentFilter)
|
||||
->with('establishment:id,name')
|
||||
->orderBy('name')
|
||||
->limit(12)
|
||||
@@ -123,41 +195,47 @@ class DashboardService
|
||||
]);
|
||||
}
|
||||
|
||||
private function machineQuery(Supervisor $supervisor)
|
||||
private function machineQuery(Supervisor $supervisor, ?int $establishmentFilter = null)
|
||||
{
|
||||
$query = Machine::query()->whereHas('establishment', function ($query) use ($supervisor) {
|
||||
$establishmentId = $supervisor->establishment_id ?? $establishmentFilter;
|
||||
|
||||
$query = Machine::query()->whereHas('establishment', function ($query) use ($supervisor, $establishmentId) {
|
||||
$query->where('organization_id', $supervisor->organization_id);
|
||||
|
||||
if ($supervisor->establishment_id !== null) {
|
||||
$query->where('id', $supervisor->establishment_id);
|
||||
if ($establishmentId !== null) {
|
||||
$query->where('id', $establishmentId);
|
||||
}
|
||||
});
|
||||
|
||||
if ($supervisor->establishment_id !== null) {
|
||||
$query->where('establishment_id', $supervisor->establishment_id);
|
||||
if ($establishmentId !== null) {
|
||||
$query->where('establishment_id', $establishmentId);
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
private function washQuery(Supervisor $supervisor)
|
||||
private function washQuery(Supervisor $supervisor, ?int $establishmentFilter = null)
|
||||
{
|
||||
return Wash::query()->whereHas('machine.establishment', function ($query) use ($supervisor) {
|
||||
$establishmentId = $supervisor->establishment_id ?? $establishmentFilter;
|
||||
|
||||
return Wash::query()->whereHas('machine.establishment', function ($query) use ($supervisor, $establishmentId) {
|
||||
$query->where('organization_id', $supervisor->organization_id);
|
||||
|
||||
if ($supervisor->establishment_id !== null) {
|
||||
$query->where('id', $supervisor->establishment_id);
|
||||
if ($establishmentId !== null) {
|
||||
$query->where('id', $establishmentId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private function bookingQuery(Supervisor $supervisor)
|
||||
private function bookingQuery(Supervisor $supervisor, ?int $establishmentFilter = null)
|
||||
{
|
||||
return Booking::query()->whereHas('machine.establishment', function ($query) use ($supervisor) {
|
||||
$establishmentId = $supervisor->establishment_id ?? $establishmentFilter;
|
||||
|
||||
return Booking::query()->whereHas('machine.establishment', function ($query) use ($supervisor, $establishmentId) {
|
||||
$query->where('organization_id', $supervisor->organization_id);
|
||||
|
||||
if ($supervisor->establishment_id !== null) {
|
||||
$query->where('id', $supervisor->establishment_id);
|
||||
if ($establishmentId !== null) {
|
||||
$query->where('id', $establishmentId);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -195,4 +273,16 @@ class DashboardService
|
||||
default => $type,
|
||||
};
|
||||
}
|
||||
|
||||
private function washStatusLabel(string $status): string
|
||||
{
|
||||
return match ($status) {
|
||||
'pending_start' => 'En attente',
|
||||
'running' => 'En cours',
|
||||
'completed' => 'Terminé',
|
||||
'cancelled' => 'Annulé',
|
||||
'failed' => 'Échoué',
|
||||
default => $status,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Http\Client\RequestException;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class GeocodingService
|
||||
{
|
||||
/**
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public function search(string $query): array
|
||||
{
|
||||
$query = trim($query);
|
||||
|
||||
if (strlen($query) < 3) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
$response = $this->client()->get(config('services.nominatim.url').'/search', [
|
||||
'q' => $query,
|
||||
'format' => 'json',
|
||||
'addressdetails' => 1,
|
||||
'limit' => 5,
|
||||
'countrycodes' => 'fr',
|
||||
]);
|
||||
} catch (ConnectionException|RequestException $exception) {
|
||||
Log::warning('Geocoding search failed.', [
|
||||
'query' => $query,
|
||||
'message' => $exception->getMessage(),
|
||||
]);
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
if (! $response->successful()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return collect($response->json())
|
||||
->map(fn (array $item) => $this->formatResult($item))
|
||||
->filter(fn (array $item) => $item['address'] !== '')
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{latitude: float, longitude: float}|null
|
||||
*/
|
||||
public function geocode(string $address, ?string $city = null, ?string $zipCode = null): ?array
|
||||
{
|
||||
$query = collect([$address, $zipCode, $city, 'France'])
|
||||
->filter(fn (?string $part) => $part !== null && trim($part) !== '')
|
||||
->implode(', ');
|
||||
|
||||
$results = $this->search($query);
|
||||
|
||||
if ($results === [] || $results[0]['latitude'] === null || $results[0]['longitude'] === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [
|
||||
'latitude' => $results[0]['latitude'],
|
||||
'longitude' => $results[0]['longitude'],
|
||||
];
|
||||
}
|
||||
|
||||
private function client(): PendingRequest
|
||||
{
|
||||
return Http::withHeaders([
|
||||
'User-Agent' => config('services.nominatim.user_agent'),
|
||||
'Accept-Language' => 'fr',
|
||||
])
|
||||
->withOptions([
|
||||
'verify' => (bool) config('services.nominatim.verify_ssl', true),
|
||||
])
|
||||
->timeout(8)
|
||||
->connectTimeout(4);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $item
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function formatResult(array $item): array
|
||||
{
|
||||
$addressParts = $item['address'] ?? [];
|
||||
$street = trim(($addressParts['house_number'] ?? '').' '.($addressParts['road'] ?? ''));
|
||||
|
||||
if ($street === '') {
|
||||
$street = trim((string) ($item['name'] ?? ''));
|
||||
}
|
||||
|
||||
return [
|
||||
'label' => (string) ($item['display_name'] ?? $street),
|
||||
'address' => $street,
|
||||
'city' => $addressParts['city']
|
||||
?? $addressParts['town']
|
||||
?? $addressParts['village']
|
||||
?? $addressParts['municipality']
|
||||
?? '',
|
||||
'zip_code' => (string) ($addressParts['postcode'] ?? ''),
|
||||
'latitude' => isset($item['lat']) ? (float) $item['lat'] : null,
|
||||
'longitude' => isset($item['lon']) ? (float) $item['lon'] : null,
|
||||
];
|
||||
}
|
||||
}
|
||||
+152
-34
@@ -6,12 +6,14 @@ use App\Models\PaymentTransaction;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Stripe\Exception\ApiErrorException;
|
||||
|
||||
class PaymentService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly WalletService $walletService,
|
||||
private readonly AuditService $auditService,
|
||||
private readonly StripePaymentService $stripePaymentService,
|
||||
) {}
|
||||
|
||||
public function initiateTopUp(
|
||||
@@ -20,8 +22,13 @@ class PaymentService
|
||||
string $idempotencyKey,
|
||||
?string $returnUrl = null,
|
||||
): PaymentTransaction {
|
||||
if ($amount <= 0) {
|
||||
throw new \InvalidArgumentException('Le montant doit être strictement positif.');
|
||||
$minAmount = (float) config('laverie.payment.top_up_min', 5);
|
||||
$maxAmount = (float) config('laverie.payment.top_up_max', 150);
|
||||
|
||||
if ($amount < $minAmount || $amount > $maxAmount) {
|
||||
throw new \InvalidArgumentException(
|
||||
"Le montant doit être compris entre {$minAmount} et {$maxAmount} EUR.",
|
||||
);
|
||||
}
|
||||
|
||||
$existing = PaymentTransaction::query()
|
||||
@@ -32,21 +39,49 @@ class PaymentService
|
||||
return $existing;
|
||||
}
|
||||
|
||||
$payment = PaymentTransaction::query()->create([
|
||||
'uuid' => (string) Str::uuid(),
|
||||
'user_id' => $user->id,
|
||||
'provider' => config('laverie.payment.default_provider', 'simulated'),
|
||||
'provider_payment_id' => 'sim-'.Str::random(16),
|
||||
'amount' => $amount,
|
||||
'currency' => 'EUR',
|
||||
'status' => 'initiated',
|
||||
'idempotency_key' => $idempotencyKey,
|
||||
'return_url' => $returnUrl,
|
||||
]);
|
||||
$provider = config('laverie.payment.default_provider', 'simulated');
|
||||
|
||||
$this->auditService->log($user, 'payment.initiated', $payment, null, $payment->toArray());
|
||||
if ($provider === 'stripe' && ! $this->stripePaymentService->isEnabled()) {
|
||||
throw new \RuntimeException('Stripe n\'est pas configuré.');
|
||||
}
|
||||
|
||||
return $payment;
|
||||
return DB::transaction(function () use ($user, $amount, $idempotencyKey, $returnUrl, $provider) {
|
||||
$payment = PaymentTransaction::query()->create([
|
||||
'uuid' => (string) Str::uuid(),
|
||||
'user_id' => $user->id,
|
||||
'provider' => $provider,
|
||||
'provider_payment_id' => null,
|
||||
'amount' => $amount,
|
||||
'currency' => 'EUR',
|
||||
'status' => 'initiated',
|
||||
'idempotency_key' => $idempotencyKey,
|
||||
'return_url' => $returnUrl,
|
||||
]);
|
||||
|
||||
if ($provider === 'stripe') {
|
||||
try {
|
||||
$intent = $this->stripePaymentService->createPaymentIntent($user, $payment, $amount);
|
||||
} catch (ApiErrorException $e) {
|
||||
throw new \RuntimeException('Impossible de créer le paiement Stripe.', 0, $e);
|
||||
}
|
||||
|
||||
$payment->update([
|
||||
'provider_payment_id' => $intent->id,
|
||||
'status' => 'pending',
|
||||
'raw_payload' => [
|
||||
'client_secret' => $intent->client_secret,
|
||||
],
|
||||
]);
|
||||
} else {
|
||||
$payment->update([
|
||||
'provider_payment_id' => 'sim-'.Str::random(16),
|
||||
]);
|
||||
}
|
||||
|
||||
$this->auditService->log($user, 'payment.initiated', $payment, null, $payment->fresh()->toArray());
|
||||
|
||||
return $payment->fresh();
|
||||
});
|
||||
}
|
||||
|
||||
public function confirmTopUp(string $paymentUuid): PaymentTransaction
|
||||
@@ -65,26 +100,29 @@ class PaymentService
|
||||
throw new \RuntimeException("Paiement non confirmable (statut : {$payment->status}).");
|
||||
}
|
||||
|
||||
$payment->update(['status' => 'succeeded']);
|
||||
if ($payment->provider === 'stripe') {
|
||||
if (blank($payment->provider_payment_id)) {
|
||||
throw new \RuntimeException('Paiement Stripe introuvable.');
|
||||
}
|
||||
|
||||
$this->walletService->credit(
|
||||
$payment->user,
|
||||
(float) $payment->amount,
|
||||
PaymentTransaction::class,
|
||||
$payment->id,
|
||||
"payment-credit:{$payment->uuid}",
|
||||
['provider' => $payment->provider],
|
||||
);
|
||||
try {
|
||||
$intent = $this->stripePaymentService->retrievePaymentIntent($payment->provider_payment_id);
|
||||
} catch (ApiErrorException $e) {
|
||||
throw new \RuntimeException('Impossible de vérifier le paiement Stripe.', 0, $e);
|
||||
}
|
||||
|
||||
$this->auditService->log(
|
||||
$payment->user,
|
||||
'payment.confirmed',
|
||||
$payment,
|
||||
null,
|
||||
$payment->fresh()->toArray(),
|
||||
);
|
||||
if (! $this->stripePaymentService->isPaymentSucceeded($intent)) {
|
||||
throw new \RuntimeException('Le paiement Stripe n\'est pas encore confirmé.');
|
||||
}
|
||||
|
||||
return $payment->fresh();
|
||||
$payment->update([
|
||||
'raw_payload' => array_merge($payment->raw_payload ?? [], [
|
||||
'stripe' => $this->stripePaymentService->summarizePaymentIntent($intent),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
return $this->markPaymentSucceeded($payment->fresh());
|
||||
});
|
||||
}
|
||||
|
||||
@@ -98,6 +136,10 @@ class PaymentService
|
||||
throw new \InvalidArgumentException('Webhook paiement invalide.');
|
||||
}
|
||||
|
||||
if ($status === 'ignored') {
|
||||
return;
|
||||
}
|
||||
|
||||
DB::transaction(function () use ($provider, $payload, $providerPaymentId, $idempotencyKey, $status) {
|
||||
$query = PaymentTransaction::query()->lockForUpdate();
|
||||
|
||||
@@ -119,14 +161,90 @@ class PaymentService
|
||||
}
|
||||
|
||||
$payment->update([
|
||||
'raw_payload' => $payload,
|
||||
'raw_payload' => array_merge($payment->raw_payload ?? [], [
|
||||
'webhook' => $payload,
|
||||
]),
|
||||
]);
|
||||
|
||||
if ($status === 'succeeded') {
|
||||
$this->confirmTopUp($payment->uuid);
|
||||
$this->markPaymentSucceeded($payment);
|
||||
} elseif (in_array($status, ['failed', 'cancelled', 'refunded'], true)) {
|
||||
$payment->update(['status' => $status]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function handleStripeWebhook(string $payload, string $signature): void
|
||||
{
|
||||
$parsed = $this->stripePaymentService->parseWebhook($payload, $signature);
|
||||
|
||||
if ($parsed['status'] === 'ignored') {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->handleWebhook('stripe', [
|
||||
'provider_payment_id' => $parsed['provider_payment_id'],
|
||||
'status' => $parsed['status'],
|
||||
'payload' => $parsed['payload'],
|
||||
]);
|
||||
}
|
||||
|
||||
private function markPaymentSucceeded(PaymentTransaction $payment): PaymentTransaction
|
||||
{
|
||||
if ($payment->status === 'succeeded') {
|
||||
return $payment;
|
||||
}
|
||||
|
||||
$payment->update(['status' => 'succeeded']);
|
||||
|
||||
$this->walletService->credit(
|
||||
$payment->user,
|
||||
(float) $payment->amount,
|
||||
PaymentTransaction::class,
|
||||
$payment->id,
|
||||
"payment-credit:{$payment->uuid}",
|
||||
$this->buildWalletCreditMetadata($payment),
|
||||
);
|
||||
|
||||
$this->auditService->log(
|
||||
$payment->user,
|
||||
'payment.confirmed',
|
||||
$payment,
|
||||
null,
|
||||
$payment->fresh()->toArray(),
|
||||
);
|
||||
|
||||
return $payment->fresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function buildWalletCreditMetadata(PaymentTransaction $payment): array
|
||||
{
|
||||
$metadata = [
|
||||
'operation' => 'top_up',
|
||||
'provider' => $payment->provider,
|
||||
'label' => match ($payment->provider) {
|
||||
'stripe' => 'Rechargement par carte',
|
||||
'simulated' => 'Rechargement (simulation)',
|
||||
default => 'Rechargement portefeuille',
|
||||
},
|
||||
'payment_uuid' => $payment->uuid,
|
||||
'provider_payment_id' => $payment->provider_payment_id,
|
||||
'currency' => $payment->currency,
|
||||
'amount' => (float) $payment->amount,
|
||||
];
|
||||
|
||||
$raw = $payment->raw_payload ?? [];
|
||||
|
||||
if ($payment->provider === 'stripe') {
|
||||
$metadata['stripe'] = $raw['stripe'] ?? [
|
||||
'payment_intent_id' => $payment->provider_payment_id,
|
||||
'status' => 'succeeded',
|
||||
];
|
||||
}
|
||||
|
||||
return $metadata;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\PaymentTransaction;
|
||||
use App\Models\User;
|
||||
use Stripe\Exception\SignatureVerificationException;
|
||||
use Stripe\PaymentIntent;
|
||||
use Stripe\Stripe;
|
||||
use Stripe\Webhook;
|
||||
use UnexpectedValueException;
|
||||
|
||||
class StripePaymentService
|
||||
{
|
||||
private bool $configured = false;
|
||||
|
||||
private function ensureConfigured(): void
|
||||
{
|
||||
if ($this->configured) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (! class_exists(Stripe::class)) {
|
||||
throw new \RuntimeException(
|
||||
'SDK Stripe manquant. Exécutez : composer require stripe/stripe-php',
|
||||
);
|
||||
}
|
||||
|
||||
Stripe::setApiKey(config('services.stripe.secret'));
|
||||
$this->configured = true;
|
||||
}
|
||||
|
||||
public function isEnabled(): bool
|
||||
{
|
||||
return class_exists(Stripe::class)
|
||||
&& filled(config('services.stripe.secret'))
|
||||
&& filled(config('services.stripe.key'));
|
||||
}
|
||||
|
||||
public function publishableKey(): string
|
||||
{
|
||||
return (string) config('services.stripe.key');
|
||||
}
|
||||
|
||||
public function createPaymentIntent(
|
||||
User $user,
|
||||
PaymentTransaction $payment,
|
||||
float $amount,
|
||||
): PaymentIntent {
|
||||
$this->ensureConfigured();
|
||||
|
||||
return PaymentIntent::create([
|
||||
'amount' => (int) round($amount * 100),
|
||||
'currency' => strtolower($payment->currency),
|
||||
'metadata' => [
|
||||
'payment_uuid' => $payment->uuid,
|
||||
'user_id' => (string) $user->id,
|
||||
'idempotency_key' => $payment->idempotency_key,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public function retrievePaymentIntent(string $paymentIntentId): PaymentIntent
|
||||
{
|
||||
$this->ensureConfigured();
|
||||
|
||||
return PaymentIntent::retrieve($paymentIntentId, [
|
||||
'expand' => ['payment_method'],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function summarizePaymentIntent(PaymentIntent $intent): array
|
||||
{
|
||||
$summary = [
|
||||
'payment_intent_id' => $intent->id,
|
||||
'status' => $intent->status,
|
||||
'amount' => $intent->amount / 100,
|
||||
'currency' => strtoupper($intent->currency),
|
||||
];
|
||||
|
||||
$paymentMethod = $intent->payment_method;
|
||||
if (is_object($paymentMethod)) {
|
||||
$summary['payment_method_type'] = $paymentMethod->type ?? null;
|
||||
|
||||
if (isset($paymentMethod->card)) {
|
||||
$summary['card_brand'] = $paymentMethod->card->brand ?? null;
|
||||
$summary['card_last4'] = $paymentMethod->card->last4 ?? null;
|
||||
$summary['card_exp_month'] = $paymentMethod->card->exp_month ?? null;
|
||||
$summary['card_exp_year'] = $paymentMethod->card->exp_year ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
return $summary;
|
||||
}
|
||||
|
||||
public function isPaymentSucceeded(PaymentIntent $paymentIntent): bool
|
||||
{
|
||||
return $paymentIntent->status === 'succeeded';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{provider_payment_id: string, status: string, payload: array<string, mixed>}
|
||||
*/
|
||||
public function parseWebhook(string $payload, string $signature): array
|
||||
{
|
||||
$this->ensureConfigured();
|
||||
|
||||
$secret = config('services.stripe.webhook_secret');
|
||||
|
||||
if (blank($secret)) {
|
||||
throw new \RuntimeException('Webhook Stripe non configuré.');
|
||||
}
|
||||
|
||||
try {
|
||||
$event = Webhook::constructEvent($payload, $signature, $secret);
|
||||
} catch (UnexpectedValueException|SignatureVerificationException $e) {
|
||||
throw new \InvalidArgumentException('Signature webhook Stripe invalide.', 0, $e);
|
||||
}
|
||||
|
||||
$type = $event->type;
|
||||
$object = $event->data->object;
|
||||
|
||||
if (! in_array($type, [
|
||||
'payment_intent.succeeded',
|
||||
'payment_intent.payment_failed',
|
||||
'payment_intent.canceled',
|
||||
], true)) {
|
||||
return [
|
||||
'provider_payment_id' => $object->id ?? '',
|
||||
'status' => 'ignored',
|
||||
'payload' => $event->toArray(),
|
||||
];
|
||||
}
|
||||
|
||||
$status = match ($type) {
|
||||
'payment_intent.succeeded' => 'succeeded',
|
||||
'payment_intent.payment_failed' => 'failed',
|
||||
'payment_intent.canceled' => 'cancelled',
|
||||
default => 'ignored',
|
||||
};
|
||||
|
||||
return [
|
||||
'provider_payment_id' => $object->id,
|
||||
'status' => $status,
|
||||
'payload' => $event->toArray(),
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user