Skip to content

Feature: new billing flow #109

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 41 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
ac25b35
add stripe packages and install
steven-fox Apr 18, 2025
ff0bd51
add subscription.created webhook handling
steven-fox Apr 18, 2025
24985ac
add order success page
steven-fox Apr 18, 2025
9396484
fix nullable name components in CreateAnystackLicenseJob
steven-fox Apr 18, 2025
9041c47
fix margin of "view installation guide" button
steven-fox Apr 18, 2025
e88b4cb
remove local testing code
steven-fox Apr 18, 2025
7cb732b
send license key email notification upon creation
steven-fox Apr 18, 2025
e973c95
pinting
steven-fox Apr 18, 2025
6bc35b3
prettier
steven-fox Apr 18, 2025
e6b8507
optimize email and license key handling in OrderSuccessController
steven-fox Apr 19, 2025
8520289
fix copyToClipboard from duplicate class usage
steven-fox Apr 19, 2025
a9e8d71
add /mobile route test for stripe payment links
steven-fox Apr 19, 2025
845e987
add StripeWebhookRouteTest
steven-fox Apr 19, 2025
bd34858
add StripeWebhookConfigurationTest
steven-fox Apr 19, 2025
1123958
add HandleCustomerSubscriptionCreatedJobTest
steven-fox Apr 19, 2025
18441c4
add CreateAnystackLicenseJobTest
steven-fox Apr 19, 2025
f8df375
remove ExampleTest
steven-fox Apr 19, 2025
0c8b6a8
make dataprovider method static
steven-fox Apr 19, 2025
1a22699
install livewire/livewire and reconfigure alpine
steven-fox Apr 23, 2025
3f4a6e3
change order success to polling livewire component page
steven-fox Apr 23, 2025
d14321f
add OrderSuccessTest
steven-fox Apr 23, 2025
f469a4a
small fixes in order-success.blade.php
steven-fox Apr 23, 2025
bd8543c
only poll when we don't have a license key
steven-fox Apr 23, 2025
9e66a57
Merge branch 'main' into feature/new-billing-flow
simonhamp Apr 29, 2025
3ba0209
show repo access instructions for Max subscribers
steven-fox Apr 29, 2025
afe5ae9
update tests
steven-fox Apr 29, 2025
e1fc573
change "beta" to "Early Access"
steven-fox Apr 29, 2025
842bffa
convert to cashier with user creation upon purchase
steven-fox Apr 30, 2025
0029a2f
Merge branch 'main' into feature/new-billing-flow
steven-fox Apr 30, 2025
f680ef5
alter todo comment based on new knowledge
steven-fox Apr 30, 2025
a0606fb
update anystack references in installation.md
steven-fox Apr 30, 2025
6caa99b
Merge branch 'main' into feature/new-billing-flow
steven-fox May 1, 2025
e0d9afc
handle merge conflict for composer.lock
steven-fox May 1, 2025
2f5106a
refactor to 1 anystack product for .env
steven-fox May 1, 2025
9b1610c
refactor session handling
steven-fox May 1, 2025
f27f0b8
update .env.example
steven-fox May 1, 2025
dee3e09
use Subscription enum in view
steven-fox May 1, 2025
2152d53
remove unnecessary stripe service config & binding
steven-fox May 1, 2025
dc02f92
fix down method
steven-fox May 1, 2025
1848663
use Cashier::stripe() to resolve StripeClient
steven-fox May 1, 2025
883eace
Merge branch 'main' into feature/new-billing-flow
steven-fox May 1, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,19 @@ VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

TORCHLIGHT_TOKEN=

STRIPE_KEY=
STRIPE_SECRET=
STRIPE_WEBHOOK_SECRET=
STRIPE_MINI_PRICE_ID=
STRIPE_PRO_PRICE_ID=
STRIPE_MAX_PRICE_ID=
STRIPE_MINI_PAYMENT_LINK=
STRIPE_PRO_PAYMENT_LINK=
STRIPE_MAX_PAYMENT_LINK=

ANYSTACK_API_KEY=
ANYSTACK_PRODUCT_ID=
ANYSTACK_MINI_POLICY_ID=
ANYSTACK_PRO_POLICY_ID=
ANYSTACK_MAX_POLICY_ID=
58 changes: 58 additions & 0 deletions app/Enums/Subscription.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

namespace App\Enums;

use RuntimeException;

enum Subscription: string
{
case Mini = 'mini';
case Pro = 'pro';
case Max = 'max';

public static function fromStripeSubscription(\Stripe\Subscription $subscription): self
{
$priceId = $subscription->items->first()?->price->id;

if (! $priceId) {
throw new RuntimeException('Could not resolve Stripe price id from subscription object.');
}

return self::fromStripePriceId($priceId);
}

public static function fromStripePriceId(string $priceId): self
{
return match ($priceId) {
config('subscriptions.plans.mini.stripe_price_id') => self::Mini,
config('subscriptions.plans.pro.stripe_price_id') => self::Pro,
config('subscriptions.plans.max.stripe_price_id') => self::Max,
default => throw new RuntimeException("Unknown Stripe price id: {$priceId}"),
};
}

public function name(): string
{
return config("subscriptions.plans.{$this->value}.name");
}

public function stripePriceId(): string
{
return config("subscriptions.plans.{$this->value}.stripe_price_id");
}

public function stripePaymentLink(): string
{
return config("subscriptions.plans.{$this->value}.stripe_payment_link");
}

public function anystackProductId(): string
{
return config("subscriptions.plans.{$this->value}.anystack_product_id");
}

public function anystackPolicyId(): string
{
return config("subscriptions.plans.{$this->value}.anystack_policy_id");
}
}
2 changes: 1 addition & 1 deletion app/Http/Middleware/VerifyCsrfToken.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@ class VerifyCsrfToken extends Middleware
* @var array<int, string>
*/
protected $except = [
//
'stripe/webhook',
];
}
81 changes: 81 additions & 0 deletions app/Jobs/CreateAnystackLicenseJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?php

namespace App\Jobs;

use App\Enums\Subscription;
use App\Notifications\LicenseKeyGenerated;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Notification;

class CreateAnystackLicenseJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

public function __construct(
public string $email,
public Subscription $subscription,
public ?string $firstName = null,
public ?string $lastName = null,
) {}

public function handle(): void
{
$contact = $this->createContact();

$license = $this->createLicense($contact['id']);

Cache::put($this->email.'.license_key', $license['key'], now()->addDay());

Notification::route('mail', $this->email)
->notify(new LicenseKeyGenerated(
$license['key'],
$this->subscription,
$this->firstName
));
}

private function createContact(): array
{
$data = collect([
'first_name' => $this->firstName,
'last_name' => $this->lastName,
'email' => $this->email,
])
->filter()
->all();

// TODO: If an existing contact with the same email address already exists,
// anystack will return a 422 validation error response.
return $this->anystackClient()
->post('https://api.anystack.sh/v1/contacts', $data)
->throw()
->json('data');
}

private function createLicense(string $contactId): ?array
{
$data = [
'policy_id' => $this->subscription->anystackPolicyId(),
'contact_id' => $contactId,
];

return $this->anystackClient()
->post("https://api.anystack.sh/v1/products/{$this->subscription->anystackProductId()}/licenses", $data)
->throw()
->json('data');
}

private function anystackClient(): PendingRequest
{
return Http::withToken(config('services.anystack.key'))
->acceptJson()
->asJson();
}
}
45 changes: 45 additions & 0 deletions app/Jobs/CreateUserFromStripeCustomer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

namespace App\Jobs;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Laravel\Cashier\Cashier;
use Stripe\Customer;

class CreateUserFromStripeCustomer implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

public function __construct(public Customer $customer) {}

public function handle(): void
{
if (Cashier::findBillable($this->customer)) {
$this->fail("A user already exists for Stripe customer [{$this->customer->id}].");

return;
}

if (User::query()->where('email', $this->customer->email)->exists()) {
$this->fail("A user already exists for email [{$this->customer->email}].");

return;
}

$user = new User;
$user->name = $this->customer->name;
$user->email = $this->customer->email;
$user->stripe_id = $this->customer->id;
// We will create a random password for the user and expect them to reset it.
$user->password = Hash::make(Str::random(72));

$user->save();
}
}
56 changes: 56 additions & 0 deletions app/Jobs/HandleCustomerSubscriptionCreatedJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Laravel\Cashier\Cashier;
use Laravel\Cashier\Events\WebhookHandled;
use Stripe\Subscription;

class HandleCustomerSubscriptionCreatedJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

public function __construct(public WebhookHandled $webhook) {}

public function handle(): void
{
$stripeSubscription = $this->constructStripeSubscription();

if (! $stripeSubscription) {
$this->fail('The Stripe webhook payload could not be constructed into a Stripe Subscription object.');

return;
}

$user = Cashier::findBillable($stripeSubscription->customer);

if (! $user || ! ($email = $user->email)) {
$this->fail('Failed to find user from Stripe subscription customer.');

return;
}

$subscriptionPlan = \App\Enums\Subscription::fromStripeSubscription($stripeSubscription);

$nameParts = explode(' ', $user->name ?? '', 2);
$firstName = $nameParts[0] ?: null;
$lastName = $nameParts[1] ?? null;

dispatch(new CreateAnystackLicenseJob(
$email,
$subscriptionPlan,
$firstName,
$lastName,
));
}

protected function constructStripeSubscription(): ?Subscription
{
return Subscription::constructFrom($this->webhook->payload['data']['object']);
}
}
20 changes: 20 additions & 0 deletions app/Listeners/StripeWebhookHandledListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace App\Listeners;

use App\Jobs\HandleCustomerSubscriptionCreatedJob;
use Illuminate\Support\Facades\Log;
use Laravel\Cashier\Events\WebhookHandled;

class StripeWebhookHandledListener
{
public function handle(WebhookHandled $event): void
{
Log::debug('Webhook handled', $event->payload);

match ($event->payload['type']) {
'customer.subscription.created' => dispatch(new HandleCustomerSubscriptionCreatedJob($event)),
default => null,
};
}
}
25 changes: 25 additions & 0 deletions app/Listeners/StripeWebhookReceivedListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace App\Listeners;

use App\Jobs\CreateUserFromStripeCustomer;
use Illuminate\Support\Facades\Log;
use Laravel\Cashier\Events\WebhookReceived;
use Stripe\Customer;

class StripeWebhookReceivedListener
{
public function handle(WebhookReceived $event): void
{
Log::debug('Webhook received', $event->payload);

match ($event->payload['type']) {
// 'customer.created' must be dispatched sync so the user is
// created before the cashier webhook handling is executed.
'customer.created' => dispatch_sync(new CreateUserFromStripeCustomer(
Customer::constructFrom($event->payload['data']['object'])
)),
default => null,
};
}
}
Loading