feat: update products on stripe
This commit is contained in:
parent
1fdb5f4cda
commit
548100af74
|
|
@ -8,4 +8,9 @@ use Filament\Resources\Pages\CreateRecord;
|
|||
class CreateCreditProduct extends CreateRecord
|
||||
{
|
||||
protected static string $resource = CreditProductResource::class;
|
||||
|
||||
protected function afterCreate(): void
|
||||
{
|
||||
app(\App\Services\StripeCreditProductSyncer::class)->sync($this->record);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,4 +17,9 @@ class EditCreditProduct extends EditRecord
|
|||
DeleteAction::make(),
|
||||
];
|
||||
}
|
||||
|
||||
protected function afterSave(): void
|
||||
{
|
||||
app(\App\Services\StripeCreditProductSyncer::class)->sync($this->record);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,9 +25,30 @@ class StripeCreditProductSyncer
|
|||
]);
|
||||
|
||||
$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) {
|
||||
$needsNewPrice = true;
|
||||
} elseif ($product->wasChanged(['amount', 'currency', 'type', 'credits'])) {
|
||||
$needsNewPrice = true;
|
||||
}
|
||||
|
||||
$stripePriceId = $product->stripe_price_id;
|
||||
|
||||
if ($needsNewPrice) {
|
||||
$priceData = [
|
||||
'product' => $stripeProductId,
|
||||
'unit_amount' => $product->amount,
|
||||
|
|
@ -46,12 +67,26 @@ class StripeCreditProductSyncer
|
|||
}
|
||||
|
||||
$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([
|
||||
'stripe_product_id' => $stripeProductId,
|
||||
'stripe_price_id' => $product->stripe_price_id ?: $stripePrice->id,
|
||||
])->save();
|
||||
if ($product->stripe_product_id !== $stripeProductId || $product->stripe_price_id !== $stripePriceId) {
|
||||
$product->forceFill([
|
||||
'stripe_product_id' => $stripeProductId,
|
||||
'stripe_price_id' => $stripePriceId,
|
||||
])->saveQuietly();
|
||||
}
|
||||
|
||||
return $product;
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue