ahmedessam/sub-sphere

A scalable, modular, and cleanly-structured Laravel package to manage subscription plans, pricing, features, and usage

v1.0.0 2025-07-01 05:47 UTC

This package is auto-updated.

Last update: 2025-07-01 05:49:13 UTC


README

Latest Version Total Downloads PHP Version Laravel Version

๐Ÿ”น About the Package

SubSphere is a powerful, headless, and backend-only Laravel package designed to manage subscription plans, pricing tiers, feature usage, and billing logic. Built with modularity and scalability in mind, it provides a complete subscription management solution without any built-in UI, giving you full control over the presentation layer.

๐Ÿง  Headless & Backend-Only

SubSphere focuses purely on business logic, providing a robust API that you can integrate with any frontend framework, admin panel, or custom UI.

๐Ÿงฉ Optional Filament v3 Integration

Seamlessly integrate with Filament v3 for a beautiful admin interface to manage plans, subscriptions, and analytics.

๐ŸŒ Built-in Spatie Laravel Translatable Support

Full multi-language support for plan names, descriptions, and all user-facing content using Spatie's Laravel Translatable package.

โœ… Requirements

  • PHP: ^8.1
  • Laravel: ^10.0 | ^11.0
  • Dependencies:
    • spatie/laravel-translatable: ^6.0
    • illuminate/support
    • nesbot/carbon

๐Ÿ’ก Features List

๐Ÿ“Š Subscription Management

  • โœ… Multi-tiered Plans & Pricing - Create complex pricing structures with multiple tiers
  • ๐Ÿงช Trial Subscriptions - Flexible trial periods with automatic conversion
  • ๐Ÿ” Subscription Lifecycle - Complete handling of start, cancel, resume, expire, and renewal
  • โฑ Grace Period Support - Configurable grace periods for expired subscriptions
  • ๐Ÿ’ฐ Multi-currency Support - Handle multiple currencies with configurable defaults

๐Ÿ“ˆ Feature Usage & Limits

  • ๐Ÿ“Š Usage Tracking - Track feature consumption with configurable limits
  • โฐ Reset Logic - Automatic usage resets (daily/monthly/yearly)
  • ๐Ÿ”„ Real-time Monitoring - Monitor feature usage in real-time
  • ๐Ÿšซ Limit Enforcement - Automatic enforcement of feature limits

๐Ÿš€ Automation & Events

  • ๐Ÿ” Laravel Scheduler Integration - Automated background tasks
  • โšก Event-driven Architecture - Comprehensive event system
  • ๐Ÿ“ง Email Notifications - Built-in notification system
  • ๐Ÿ›  Artisan Commands - Management commands for automation

๐Ÿงฉ Developer Experience

  • ๐ŸŽฏ Service-based Design - Clean, modular architecture
  • ๐Ÿงช Complete Test Coverage - Comprehensive test suite
  • ๐Ÿ“ Rich Documentation - Detailed documentation and examples
  • ๐Ÿ”ค Multi-language Ready - Full internationalization support

๐Ÿ“ฅ Installation

Install the package via Composer:

composer require ahmedessam/sub-sphere

โš™๏ธ Publishing Config & Migrations

Publish Configuration

php artisan vendor:publish --tag="sub-sphere-config"

Publish and Run Migrations

php artisan vendor:publish --tag="sub-sphere-migrations"
php artisan migrate

Publish Language Files (Optional)

php artisan vendor:publish --tag="sub-sphere-lang"

Publish All Assets

php artisan vendor:publish --provider="AhmedEssam\SubSphere\Providers\SubSphereServiceProvider"

๐Ÿš€ Getting Started

1. Create Your First Plan

use AhmedEssam\SubSphere\Models\Plan;
use AhmedEssam\SubSphere\Models\PlanPricing;

// Create a plan
$plan = Plan::create([
    'name' => ['en' => 'Professional Plan', 'ar' => 'ุงู„ุฎุทุฉ ุงู„ุงุญุชุฑุงููŠุฉ'],
    'slug' => 'professional',
    'description' => ['en' => 'Perfect for growing businesses'],
    'is_active' => true,
]);

// Add pricing
$pricing = $plan->pricings()->create([
    'price' => 29.99,
    'currency' => 'USD',
    'duration_in_days' => 30,
    'is_recurring' => true,
]);

// Add features
$plan->features()->create([
    'name' => ['en' => 'API Calls'],
    'key' => 'api_calls',
    'limit_value' => 10000,
    'limit_type' => 'limited',
    'reset_period' => 'monthly',
]);

2. Subscribe a User to a Plan

use AhmedEssam\SubSphere\Services\SubscriptionService;

$subscriptionService = app(SubscriptionService::class);

// Create subscription
$subscription = $subscriptionService->createSubscription(
    subscriber: $user,
    planId: $plan->id,
    pricingId: $pricing->id
);

// Or start a trial
$trialSubscription = $subscriptionService->startTrial(
    subscriber: $user,
    planId: $plan->id,
    pricingId: $pricing->id,
    trialDays: 14
);

3. Use Features & Track Usage

// Check if user can use a feature
if ($user->subscription->canConsumeFeature('api_calls', 100)) {
    // User can make 100 API calls
    $user->subscription->consumeFeature('api_calls', 100);

    // Your API logic here...
}

// Check remaining usage
$remaining = $user->subscription->getRemainingUsage('api_calls');
echo "API calls remaining: {$remaining}";

// Check if feature is unlimited
if ($user->subscription->hasUnlimitedUsage('api_calls')) {
    echo "Unlimited API calls available!";
}

๐Ÿ” Running Commands

SubSphere includes several Artisan commands for automation:

Reset Feature Usage

# Reset all usage counters based on their reset periods
php artisan sub-sphere:reset-usage

# Dry run to see what would be reset
php artisan sub-sphere:reset-usage --dry-run

# Reset specific period
php artisan sub-sphere:reset-usage --period=monthly

# Limit number of records processed
php artisan sub-sphere:reset-usage --limit=1000

Expire Subscriptions

# Expire subscriptions that have passed their grace period
php artisan sub-sphere:expire-subscriptions

# Dry run to see what would be expired
php artisan sub-sphere:expire-subscriptions --dry-run

# Limit number of subscriptions processed
php artisan sub-sphere:expire-subscriptions --limit=100

Renew Subscriptions

# Renew eligible subscriptions
php artisan sub-sphere:renew-subscriptions

# Dry run mode
php artisan sub-sphere:renew-subscriptions --dry-run

๐Ÿ”” Available Events

SubSphere dispatches several events that you can listen to:

// Subscription Events
AhmedEssam\SubSphere\Events\SubscriptionCreated::class
AhmedEssam\SubSphere\Events\SubscriptionStarted::class
AhmedEssam\SubSphere\Events\SubscriptionCanceled::class
AhmedEssam\SubSphere\Events\SubscriptionExpired::class
AhmedEssam\SubSphere\Events\SubscriptionRenewed::class
AhmedEssam\SubSphere\Events\SubscriptionChanged::class

// Trial Events
AhmedEssam\SubSphere\Events\TrialStarted::class

// Feature Events
AhmedEssam\SubSphere\Events\FeatureUsed::class
AhmedEssam\SubSphere\Events\FeatureUsageReset::class

// Renewal Events
AhmedEssam\SubSphere\Events\SubscriptionRenewalFailed::class

Example Event Listener

use AhmedEssam\SubSphere\Events\SubscriptionCreated;

class SendWelcomeEmail
{
    public function handle(SubscriptionCreated $event)
    {
        // Send welcome email
        Mail::to($event->subscriber->email)
            ->send(new WelcomeEmail($event->subscription));
    }
}

๐Ÿ“Š Feature Usage & Limits

Feature Types

  • Limited: Features with specific usage limits (e.g., 1000 API calls)
  • Unlimited: Features with no usage restrictions
  • Boolean: Simple on/off features

Reset Periods

  • Daily: Usage resets every day at midnight
  • Monthly: Usage resets on the first day of each month
  • Yearly: Usage resets on January 1st
  • Never: Usage never resets automatically

Usage Tracking Example

// Define a feature
$plan->features()->create([
    'name' => ['en' => 'Storage Space'],
    'key' => 'storage_gb',
    'limit_value' => 100, // 100 GB
    'limit_type' => 'limited',
    'reset_period' => 'monthly',
]);

// Track usage
$subscription = $user->subscription;

// Use 5 GB of storage
$subscription->consumeFeature('storage_gb', 5);

// Check usage
$used = $subscription->getUsedAmount('storage_gb'); // 5
$remaining = $subscription->getRemainingUsage('storage_gb'); // 95
$percentage = $subscription->getUsagePercentage('storage_gb'); // 5%

// Check if can use more
if ($subscription->canConsumeFeature('storage_gb', 50)) {
    // User can use 50 more GB
}

๐ŸŒ Multi-language Support (Spatie Translatable)

SubSphere fully supports multiple languages using Spatie's Laravel Translatable:

Configure Supported Locales

// config/sub-sphere.php
return [
    'locales' => ['en', 'ar', 'es', 'fr'],
    'fallback_locale' => 'en',
];

Create Multilingual Plans

$plan = Plan::create([
    'name' => [
        'en' => 'Professional Plan',
        'ar' => 'ุงู„ุฎุทุฉ ุงู„ุงุญุชุฑุงููŠุฉ',
        'es' => 'Plan Profesional',
        'fr' => 'Plan Professionnel',
    ],
    'description' => [
        'en' => 'Perfect for growing businesses',
        'ar' => 'ู…ุซุงู„ูŠุฉ ู„ู„ุดุฑูƒุงุช ุงู„ู†ุงู…ูŠุฉ',
        'es' => 'Perfecto para empresas en crecimiento',
        'fr' => 'Parfait pour les entreprises en croissance',
    ],
    'slug' => 'professional',
]);

// Get localized name
echo $plan->getLocalizedName('ar'); // ุงู„ุฎุทุฉ ุงู„ุงุญุชุฑุงููŠุฉ
echo $plan->name; // Uses current app locale

Email Translations

All email templates support RTL/LTR layouts and use Laravel's translation system:

// Email subject will be translated based on user's locale
$subject = __('sub-sphere::subscription.subjects.subscription_created', [
    'plan_name' => $plan->getLocalizedName()
]);

๐Ÿงฉ Optional Filament Integration

SubSphere provides optional integration with Filament v3 for a beautiful admin interface.

Installation

composer require filament/filament
php artisan vendor:publish --tag="sub-sphere-filament"

Features

  • ๐Ÿ“Š Dashboard Widgets - Subscription analytics and metrics
  • ๐Ÿ— Resource Management - Full CRUD for plans, subscriptions, and features
  • ๐Ÿ“ˆ Usage Analytics - Visual charts and reports
  • ๐Ÿ”” Real-time Notifications - Live subscription updates
  • ๐ŸŽจ Customizable Interface - Tailored for subscription management

Configuration

The package configuration is located at config/sub-sphere.php:

return [
    // Grace period in days for expired subscriptions
    'grace_period_days' => 3,

    // Auto-renewal settings
    'auto_renewal_default' => true,

    // Currency settings
    'currency' => [
        'default' => 'USD',
        'supported_currencies' => ['USD', 'EUR', 'GBP', 'EGP'],
    ],

    // Trial settings
    'trial' => [
        'default_days' => 14,
        'max_days' => 90,
        'min_days' => 1,
    ],

    // Plan change settings
    'plan_changes' => [
        'allow_downgrades' => true,
        'allow_plan_change_during_trial' => true,
        'prevent_downgrade_with_excess_usage' => true,
    ],

    // Supported locales
    'locales' => ['en', 'ar'],
    'fallback_locale' => 'en',
];

Testing

Run the test suite:

composer test

Run tests with coverage:

composer test-coverage

Format code:

composer format

๐Ÿชช License

SubSphere is open-sourced software licensed under the MIT license.

๐Ÿ™‹ Author

Ahmed Essam

๐Ÿค Contributing

Thank you for considering contributing to SubSphere! Please see CONTRIBUTING.md for details.

Development Setup

  1. Clone the repository
  2. Install dependencies: composer install
  3. Run tests: composer test
  4. Follow PSR-12 coding standards

Reporting Issues

Please use the GitHub issue tracker to report bugs or request features.

Built with โค๏ธ for the Laravel community