feat: update products on stripe
Laravel CI-CD / Tests Unitaires (push) Successful in 1m30s Details
Laravel CI-CD / Deploy with Kamal (push) Successful in 2m15s Details

This commit is contained in:
Leon Morival 2026-05-27 17:22:19 +02:00
parent 1fdb5f4cda
commit 548100af74
3 changed files with 49 additions and 4 deletions

View File

@ -8,4 +8,9 @@ use Filament\Resources\Pages\CreateRecord;
class CreateCreditProduct extends CreateRecord class CreateCreditProduct extends CreateRecord
{ {
protected static string $resource = CreditProductResource::class; protected static string $resource = CreditProductResource::class;
protected function afterCreate(): void
{
app(\App\Services\StripeCreditProductSyncer::class)->sync($this->record);
}
} }

View File

@ -17,4 +17,9 @@ class EditCreditProduct extends EditRecord
DeleteAction::make(), DeleteAction::make(),
]; ];
} }
protected function afterSave(): void
{
app(\App\Services\StripeCreditProductSyncer::class)->sync($this->record);
}
} }

View File

@ -25,9 +25,30 @@ class StripeCreditProductSyncer
]); ]);
$stripeProductId = $stripeProduct->id; $stripeProductId = $stripeProduct->id;
} else {
$stripe->products->update($stripeProductId, [
'name' => $product->name,
'description' => $product->description,
'active' => (bool) $product->is_active,
'metadata' => [
'credit_product_id' => $product->getKey(),
'credits' => (string) $product->credits,
'type' => $product->type->value,
],
]);
} }
$needsNewPrice = false;
if (! $product->stripe_price_id) { if (! $product->stripe_price_id) {
$needsNewPrice = true;
} elseif ($product->wasChanged(['amount', 'currency', 'type', 'credits'])) {
$needsNewPrice = true;
}
$stripePriceId = $product->stripe_price_id;
if ($needsNewPrice) {
$priceData = [ $priceData = [
'product' => $stripeProductId, 'product' => $stripeProductId,
'unit_amount' => $product->amount, 'unit_amount' => $product->amount,
@ -46,12 +67,26 @@ class StripeCreditProductSyncer
} }
$stripePrice = $stripe->prices->create($priceData); $stripePrice = $stripe->prices->create($priceData);
$stripePriceId = $stripePrice->id;
// Archive the old price if it exists
if ($product->stripe_price_id && $product->stripe_price_id !== $stripePriceId) {
try {
$stripe->prices->update($product->stripe_price_id, [
'active' => false,
]);
} catch (\Exception $e) {
// Ignore error if price not found
}
}
} }
$product->forceFill([ if ($product->stripe_product_id !== $stripeProductId || $product->stripe_price_id !== $stripePriceId) {
'stripe_product_id' => $stripeProductId, $product->forceFill([
'stripe_price_id' => $product->stripe_price_id ?: $stripePrice->id, 'stripe_product_id' => $stripeProductId,
])->save(); 'stripe_price_id' => $stripePriceId,
])->saveQuietly();
}
return $product; return $product;
} }