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

Open
wants to merge 27 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 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
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
18 changes: 18 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,21 @@ 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_MINI_PRODUCT_ID=
ANYSTACK_PRO_PRODUCT_ID=
ANYSTACK_MAX_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: It's unknown what will happen if an existing contact with
// the same email address already exists.
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();
}
}
60 changes: 60 additions & 0 deletions app/Jobs/StripeWebhooks/HandleCustomerSubscriptionCreatedJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

namespace App\Jobs\StripeWebhooks;

use App\Jobs\CreateAnystackLicenseJob;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Spatie\WebhookClient\Models\WebhookCall;
use Stripe\Event;
use Stripe\StripeClient;
use Stripe\Subscription;

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

public function __construct(public WebhookCall $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;
}

$customer = app(StripeClient::class)
->customers
->retrieve($stripeSubscription->customer);

if (! $customer || ! ($email = $customer->email)) {
$this->fail('Failed to retrieve customer information or customer has no email.');

return;
}

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

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

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

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

namespace App\Livewire;

use App\Enums\Subscription;
use Illuminate\Support\Facades\Cache;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;
use Stripe\StripeClient;

#[Layout('components.layout')]
#[Title('Thank You for Your Purchase')]
class OrderSuccess extends Component
{
public ?string $email = null;

public ?string $licenseKey = null;

public ?Subscription $subscription = null;

public string $checkoutSessionId;

public function mount(string $checkoutSessionId): void
{
$this->checkoutSessionId = $checkoutSessionId;

$this->loadData();
}

public function loadData(): void
{
$this->email = $this->loadEmail();
$this->licenseKey = $this->loadLicenseKey();
$this->subscription = $this->loadSubscription();
}

private function loadEmail(): ?string
{
if ($email = session('customer_email')) {
return $email;
}

$stripe = app(StripeClient::class);
$checkoutSession = $stripe->checkout->sessions->retrieve($this->checkoutSessionId);

if (! ($email = $checkoutSession?->customer_details?->email)) {
return null;
}

session()->put('customer_email', $email);

return $email;
}

private function loadLicenseKey(): ?string
{
if ($licenseKey = session('license_key')) {
return $licenseKey;
}

if (! $this->email) {
return null;
}

if ($licenseKey = Cache::get($this->email.'.license_key')) {
session()->put('license_key', $licenseKey);
}

return $licenseKey;
}

private function loadSubscription(): ?Subscription
{
if ($subscription = session('subscription')) {
return Subscription::tryFrom($subscription);
}

$stripe = app(StripeClient::class);
$priceId = $stripe->checkout->sessions->allLineItems($this->checkoutSessionId)->first()?->price->id;

if (! $priceId) {
return null;
}

$subscription = Subscription::fromStripePriceId($priceId);

session()->put('subscription', $subscription->value);

return $subscription;
}
}
63 changes: 63 additions & 0 deletions app/Notifications/LicenseKeyGenerated.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php

namespace App\Notifications;

use App\Enums\Subscription;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class LicenseKeyGenerated extends Notification implements ShouldQueue
{
use Queueable;

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

/**
* Get the notification's delivery channels.
*
* @return array<int, string>
*/
public function via(object $notifiable): array
{
return ['mail'];
}

public function toMail(object $notifiable): MailMessage
{
$greeting = $this->firstName
? "{$this->firstName}, your license is ready!"
: 'Your license is ready!';

return (new MailMessage)
->subject('Your NativePHP License Key')
->greeting($greeting)
->line('Thank you for purchasing a license for the early access program of mobile NativePHP.')
->line('Your license key is:')
->line("**{$this->licenseKey}**")
->line('When prompted by Composer, use your email address as the username and this license key as the password.')
->action('View Installation Guide', url('/docs/mobile/1/getting-started/installation'))
->line("If you have any questions, please don't hesitate to reach out to our support team.")
->lineIf($this->subscription === Subscription::Max, 'As a Max subscriber, you also have access to the NativePHP/mobile repository. To access it, please log in to [Anystack.sh](https://auth.anystack.sh/?accountType=customer) using the same email address you used for your purchase.')
->salutation("Happy coding!\n\nThe NativePHP Team")
->success();
}

/**
* Get the array representation of the notification.
*
* @return array<string, mixed>
*/
public function toArray(object $notifiable): array
{
return [
'license_key' => $this->licenseKey,
'firstName' => $this->firstName,
];
}
}
Loading