coolify/app/Livewire/Subscription/Index.php

91 lines
2.9 KiB
PHP
Raw Permalink Normal View History

<?php
2023-12-07 18:06:32 +00:00
namespace App\Livewire\Subscription;
use App\Models\InstanceSettings;
2023-12-27 15:45:01 +00:00
use App\Providers\RouteServiceProvider;
use Livewire\Component;
2024-01-07 15:23:41 +00:00
class Index extends Component
{
public InstanceSettings $settings;
2024-06-10 20:43:34 +00:00
public bool $alreadySubscribed = false;
2024-06-10 20:43:34 +00:00
public bool $isUnpaid = false;
public bool $isCancelled = false;
public bool $isMember = false;
public bool $loading = true;
2024-02-23 11:59:14 +00:00
public function mount()
{
2024-06-10 20:43:34 +00:00
if (! isCloud()) {
2023-12-27 15:45:01 +00:00
return redirect(RouteServiceProvider::HOME);
}
2024-04-05 16:47:07 +00:00
if (auth()->user()?->isMember()) {
$this->isMember = true;
}
2024-03-29 23:23:48 +00:00
if (data_get(currentTeam(), 'subscription') && isSubscriptionActive()) {
2024-02-23 11:59:14 +00:00
return redirect()->route('subscription.show');
}
$this->settings = instanceSettings();
$this->alreadySubscribed = currentTeam()->subscription()->exists();
if (! $this->alreadySubscribed) {
$this->loading = false;
}
}
2024-06-10 20:43:34 +00:00
2024-02-23 11:59:14 +00:00
public function stripeCustomerPortal()
{
$session = getStripeCustomerPortalSession(currentTeam());
if (is_null($session)) {
return;
}
2024-06-10 20:43:34 +00:00
return redirect($session->url);
}
2024-06-10 20:43:34 +00:00
public function getStripeStatus()
{
try {
$subscription = currentTeam()->subscription;
$stripe = new \Stripe\StripeClient(config('subscription.stripe_api_key'));
$customer = $stripe->customers->retrieve(currentTeam()->subscription->stripe_customer_id);
if ($customer) {
$subscriptions = $stripe->subscriptions->all(['customer' => $customer->id]);
$currentTeam = currentTeam()->id ?? null;
if (count($subscriptions->data) > 0 && $currentTeam) {
$foundSubscription = collect($subscriptions->data)->firstWhere('metadata.team_id', $currentTeam);
if ($foundSubscription) {
$status = data_get($foundSubscription, 'status');
$subscription->update([
'stripe_subscription_id' => $foundSubscription->id,
]);
if ($status === 'unpaid') {
$this->isUnpaid = true;
}
}
}
if (count($subscriptions->data) === 0) {
$this->isCancelled = true;
}
}
} catch (\Exception $e) {
// Log the error
logger()->error('Stripe API error: '.$e->getMessage());
// Set a flag to show an error message to the user
$this->addError('stripe', 'Could not retrieve subscription information. Please try again later.');
} finally {
$this->loading = false;
}
}
public function render()
{
2024-03-21 13:30:35 +00:00
return view('livewire.subscription.index');
}
}