Skip to content

Add commands and jobs to import existing anystack data #138

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

Merged
merged 4 commits into from
May 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
6 changes: 6 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,18 @@ STRIPE_WEBHOOK_SECRET=
STRIPE_MINI_PRICE_ID=
STRIPE_PRO_PRICE_ID=
STRIPE_MAX_PRICE_ID=
STRIPE_FOREVER_PRICE_ID=
STRIPE_TRIAL_PRICE_ID=
STRIPE_MINI_PAYMENT_LINK=
STRIPE_PRO_PAYMENT_LINK=
STRIPE_MAX_PAYMENT_LINK=
STRIPE_FOREVER_PAYMENT_LINK=
STRIPE_TRIAL_PAYMENT_LINK=

ANYSTACK_API_KEY=
ANYSTACK_PRODUCT_ID=
ANYSTACK_MINI_POLICY_ID=
ANYSTACK_PRO_POLICY_ID=
ANYSTACK_MAX_POLICY_ID=
ANYSTACK_FOREVER_POLICY_ID=
ANYSTACK_TRIAL_POLICY_ID=
23 changes: 23 additions & 0 deletions app/Console/Commands/ImportAnystackContactsCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace App\Console\Commands;

use App\Jobs\ImportAnystackContacts;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Bus;

class ImportAnystackContactsCommand extends Command
{
protected $signature = 'app:import-anystack-contacts';

protected $description = 'Import existing contact data from Anystack.';

public function handle(): void
{
Bus::batch([
new ImportAnystackContacts(1),
])
->name('import-anystack-contacts')
->dispatch();
}
}
23 changes: 23 additions & 0 deletions app/Console/Commands/ImportAnystackLicensesCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace App\Console\Commands;

use App\Jobs\ImportAnystackLicenses;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Bus;

class ImportAnystackLicensesCommand extends Command
{
protected $signature = 'app:import-anystack-licenses';

protected $description = 'Import existing license data from Anystack.';

public function handle(): void
{
Bus::batch([
new ImportAnystackLicenses(1),
])
->name('import-anystack-licenses')
->dispatch();
}
}
14 changes: 14 additions & 0 deletions app/Enums/Subscription.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ enum Subscription: string
case Mini = 'mini';
case Pro = 'pro';
case Max = 'max';
case Forever = 'forever';
case Trial = 'trial';

public static function fromStripeSubscription(\Stripe\Subscription $subscription): self
{
Expand All @@ -31,6 +33,18 @@ public static function fromStripePriceId(string $priceId): self
};
}

public static function fromAnystackPolicy(string $policyId): self
{
return match ($policyId) {
config('subscriptions.plans.mini.anystack_policy_id') => self::Mini,
config('subscriptions.plans.pro.anystack_policy_id') => self::Pro,
config('subscriptions.plans.max.anystack_policy_id') => self::Max,
config('subscriptions.plans.forever.anystack_policy_id') => self::Forever,
config('subscriptions.plans.trial.anystack_policy_id') => self::Trial,
default => throw new RuntimeException("Unknown Anystack policy id: {$policyId}"),
};
}

public function name(): string
{
return config("subscriptions.plans.{$this->value}.name");
Expand Down
11 changes: 10 additions & 1 deletion app/Jobs/CreateUserFromStripeCustomer.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ public function handle(): void
return;
}

if ($user = User::query()->where('email', $this->customer->email)->first()) {
$user = User::query()->where('email', $this->customer->email)->first();

if ($user && filled($user->stripe_id)) {
// This could occur if a user performs/attempts multiple checkouts with the same email address.
// In the event all existing stripe customers for this email address do NOT have an active
// subscription, we could theoretically update the stripe_id for the existing user
Expand All @@ -40,6 +42,13 @@ public function handle(): void
return;
}

if ($user) {
$user->stripe_id = $this->customer->id;
$user->save();

return;
}

Validator::validate(['email' => $this->customer->email], [
'email' => 'required|email|max:255',
]);
Expand Down
54 changes: 54 additions & 0 deletions app/Jobs/ImportAnystackContacts.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

namespace App\Jobs;

use Illuminate\Bus\Batchable;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Middleware\RateLimited;
use Illuminate\Queue\Middleware\SkipIfBatchCancelled;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;

class ImportAnystackContacts implements ShouldQueue
{
use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

public int $maxExceptions = 1;

public function __construct(
public int $page,
) {}

public function middleware(): array
{
return [
new SkipIfBatchCancelled,
new RateLimited('anystack'),
];
}

public function retryUntil(): \DateTime
{
return now()->addMinutes(20);
}

public function handle(): void
{
$response = Http::acceptJson()
->withToken(config('services.anystack.key'))
->get("https://api.anystack.sh/v1/contacts?page={$this->page}")
->json();

collect($response['data'])
->each(function (array $contact) {
dispatch(new UpsertUserFromAnystackContact($contact));
});

if (filled($response['links']['next'])) {
$this->batch()?->add(new self($this->page + 1));
}
}
}
57 changes: 57 additions & 0 deletions app/Jobs/ImportAnystackLicenses.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

namespace App\Jobs;

use App\Enums\Subscription;
use Illuminate\Bus\Batchable;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Middleware\RateLimited;
use Illuminate\Queue\Middleware\SkipIfBatchCancelled;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;

class ImportAnystackLicenses implements ShouldQueue
{
use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

public int $maxExceptions = 1;

public function __construct(
public int $page,
) {}

public function middleware(): array
{
return [
new SkipIfBatchCancelled,
new RateLimited('anystack'),
];
}

public function retryUntil(): \DateTime
{
return now()->addMinutes(20);
}

public function handle(): void
{
$productId = Subscription::Max->anystackProductId();

$response = Http::acceptJson()
->withToken(config('services.anystack.key'))
->get("https://api.anystack.sh/v1/products/$productId/licenses?page={$this->page}")
->json();

collect($response['data'])
->each(function (array $license) {
dispatch(new UpsertLicenseFromAnystackLicense($license));
});

if (filled($response['links']['next'])) {
$this->batch()?->add(new self($this->page + 1));
}
}
}
53 changes: 53 additions & 0 deletions app/Jobs/UpsertLicenseFromAnystackLicense.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

namespace App\Jobs;

use App\Enums\Subscription;
use App\Models\License;
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;

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

public int $maxExceptions = 1;

public function __construct(
public array $licenseData
) {}

public function handle(): void
{
License::updateOrCreate(['key' => $this->licenseData['key']], $this->values());
}

protected function values(): array
{
$values = [
'anystack_id' => $this->licenseData['id'],
// subscription_item_id is not set here because we don't want to replace any existing values.
'policy_name' => Subscription::fromAnystackPolicy($this->licenseData['policy_id'])->value,
'expires_at' => $this->licenseData['expires_at'],
'created_at' => $this->licenseData['created_at'],
'updated_at' => $this->licenseData['updated_at'],
];

if ($user = $this->user()) {
$values['user_id'] = $user->id;
}

return $values;
}

protected function user(): User
{
return User::query()
->where('anystack_contact_id', $this->licenseData['contact_id'])
->firstOrFail();
}
}
75 changes: 75 additions & 0 deletions app/Jobs/UpsertUserFromAnystackContact.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<?php

namespace App\Jobs;

use App\Models\User;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

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

public int $maxExceptions = 1;

public function __construct(
public array $contactData
) {}

public function handle(): void
{
$users = $this->matchingUsers();

if ($users->count() > 1) {
$userIds = $users->pluck('id')->implode(', ');

throw new Exception("Multiple users [$userIds] found for contact by id [{$this->contactData['id']}] or email [{$this->contactData['email']}]");
}

$user = $users->first() ?? new User;

$this->assertUserAttributesAreValid($user);

Log::debug(($user->exists ? "Updating user [{$user->id}]" : 'Creating user')." from anystack contact [{$this->contactData['id']}].");

$user->anystack_contact_id ??= $this->contactData['id'];
$user->email ??= $this->contactData['email'];
$user->name ??= $this->contactData['full_name'];
$user->created_at ??= $this->contactData['created_at'];
$user->updated_at ??= $this->contactData['updated_at'];
$user->password ??= Hash::make(Str::random(72));

$user->save();
}

protected function matchingUsers(): Collection
{
return User::query()
->where('email', $this->contactData['email'])
->orWhere('anystack_contact_id', $this->contactData['id'])
->get();
}

protected function assertUserAttributesAreValid(User $user): void
{
if (! $user->exists) {
return;
}

if (filled($user->anystack_contact_id) && $user->anystack_contact_id !== $this->contactData['id']) {
throw new Exception("User [{$user->id}] already exists but the user's anystack_contact_id [{$user->anystack_contact_id}] does not match the id [{$this->contactData['id']}].");
}

if ($user->email !== $this->contactData['email']) {
throw new Exception("User [{$user->id}] already exists but the user's email [{$user->email}] does not match the email [{$this->contactData['email']}].");
}
}
}
6 changes: 6 additions & 0 deletions app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
namespace App\Providers;

use App\Support\GitHub;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Queue\Events\JobFailed;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
use Sentry\State\Scope;
Expand All @@ -30,6 +32,10 @@ public function boot(): void
$this->registerSharedViewVariables();

$this->sendFailingJobsToSentry();

RateLimiter::for('anystack', function () {
return Limit::perMinute(30);
});
}

private function registerSharedViewVariables(): void
Expand Down
Loading