masterix21/laravel-subscriptions 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

masterix21/laravel-subscriptions

最新稳定版本:1.2.4

Composer 安装命令:

composer require masterix21/laravel-subscriptions

包简介

Laravel subscriptions for an unopinionated payment system

README 文档

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

A flexible, payment-agnostic subscription system for Laravel. Manage plans, features, trials, grace periods, and recurring billing with built-in Stripe support and Livewire admin views.

Requirements

  • PHP 8.2+
  • Laravel 12 or 13

Installation

composer require masterix21/laravel-subscriptions

Publish and run the migrations:

php artisan vendor:publish --tag="laravel-subscriptions-migrations"
php artisan migrate

Publish the config file:

php artisan vendor:publish --tag="laravel-subscriptions-config"

Setup

Prepare your Subscriber model

Your subscriber model (typically User) must implement SubscriberContract and use the HasSubscriptions trait.

The model also needs a meta JSON field for storing payment gateway data:

// Migration
$table->json('meta')->nullable();
use Illuminate\Database\Eloquent\Casts\AsArrayObject;
use LucaLongo\Subscriptions\Models\Concerns\HasSubscriptions;
use LucaLongo\Subscriptions\Models\Contracts\SubscriberContract;

class User extends Authenticatable implements SubscriberContract
{
    use HasSubscriptions;

    protected $fillable = [
        // ...
        'meta',
    ];

    protected function casts(): array
    {
        return [
            'meta' => AsArrayObject::class,
        ];
    }

    public function customerName(): string
    {
        return $this->name;
    }

    public function customerEmail(): string
    {
        return $this->email;
    }

    public function customerUniqueIdentifierKey(): string
    {
        return $this->getKeyName();
    }

    public function customerUniqueIdentifier(): string
    {
        return (string) $this->getKey();
    }
}

Configuration

The config file (config/subscriptions.php) allows you to customize the subscriber model, payment gateway, and all model classes:

return [
    'subscriber' => \App\Models\User::class,
    'payment_gateway' => \LucaLongo\Subscriptions\Payments\Gateways\StripeGateway::class,

    'models' => [
        'plan' => \LucaLongo\Subscriptions\Models\Plan::class,
        'feature' => \LucaLongo\Subscriptions\Models\Feature::class,
        'plan_feature' => \LucaLongo\Subscriptions\Models\PlanFeature::class,
        'subscription' => \LucaLongo\Subscriptions\Models\Subscription::class,
    ],
];

Usage

Creating Plans

use LucaLongo\Subscriptions\Models\Plan;
use LucaLongo\Subscriptions\Enums\DurationInterval;

$plan = Plan::create([
    'name' => 'Pro Monthly',
    'description' => 'Pro plan, billed monthly',
    'duration_period' => 1,
    'duration_interval' => DurationInterval::MONTH,
    'price' => 9.99,
    'trial_period' => 14,
    'trial_interval' => DurationInterval::DAY,
    'grace_period' => 3,
    'grace_interval' => DurationInterval::DAY,
]);

The code field is auto-generated from the name (e.g. pro-monthly).

Plan scopes

Plan::active()->get();    // enabled = true
Plan::inactive()->get();  // enabled = false
Plan::visible()->get();   // hidden = false
Plan::invisible()->get(); // hidden = true

Managing Features

use LucaLongo\Subscriptions\Models\Feature;

$feature = Feature::create(['name' => 'API Access']);

// Attach features to a plan (with optional max usage)
$plan->features()->attach($feature, ['max_usage' => 1000]);

Subscribing

// From the plan
$subscription = $plan->subscribe($user);

// From the user
$subscription = $user->subscribe($plan);

// With options
$subscription = $plan->subscribe(
    subscriber: $user,
    status: SubscriptionStatus::TRIALING,
    autoRenew: false,
    data: [
        'next_billing_at' => now()->addMonths(2),
        'payment_provider' => 'stripe',
        'payment_provider_reference' => 'sub_xxx',
    ]
);

Checking Subscription State

$subscription->isActive();    // Currently active (or in grace period)
$subscription->onTrial();     // In trial period
$subscription->onGrace();     // In grace period
$subscription->isRevoked();   // Permanently revoked
$subscription->isRevokable(); // Can be revoked

Checking Features

// On the subscriber
$user->hasActiveFeature('api-access');
$user->hasAnyActiveFeatures(['api-access', 'export']);
$user->hasAllActiveFeatures(['api-access', 'export']);
$user->subscribedTo('pro-monthly'); // by code
$user->subscribedTo($plan);        // by model

// On the subscription
$subscription->hasFeature('api-access');
$subscription->hasAnyFeature(collect(['api-access', 'export']));
$subscription->hasAllFeature(collect(['api-access', 'export']));

Managing Subscriptions

// Cancel (ends at next billing date by default)
$subscription->cancel();
$subscription->cancel(now()->addDays(7)); // custom end date

// Renew
$subscription->renew();
$subscription->renew(now()->addMonths(3)); // custom next billing date

// Revoke (permanent, cannot be renewed)
$subscription->revoke();

// Auto-renewal
app(DisableAutoRenewSubscription::class)->execute($subscription);
app(EnableAutoRenewSubscription::class)->execute($subscription);

Middleware

Three middleware are available to protect routes based on subscription features:

use LucaLongo\Subscriptions\Http\Middleware\RequiresFeatureMiddleware;
use LucaLongo\Subscriptions\Http\Middleware\RequiresAnyFeaturesMiddleware;
use LucaLongo\Subscriptions\Http\Middleware\RequiresAllFeaturesMiddleware;

// Single feature
Route::middleware(RequiresFeatureMiddleware::class . ':api-access')
    ->get('/api/data', DataController::class);

// Any of multiple features (comma, pipe, or space separated)
Route::middleware(RequiresAnyFeaturesMiddleware::class . ':export,api-access')
    ->get('/tools', ToolsController::class);

// All features required
Route::middleware(RequiresAllFeaturesMiddleware::class . ':export,api-access')
    ->get('/advanced', AdvancedController::class);

All middleware return a 403 response if the user doesn't meet the requirements.

Stripe Integration

Setup

Add your Stripe credentials to config/services.php:

'stripe' => [
    'secret' => env('STRIPE_SECRET'),
    'webhook_secret' => env('STRIPE_WEBHOOK_SECRET'),
],

Store the Stripe Price ID in the plan's meta field:

$plan->meta['stripe_id'] = 'price_xxx';
$plan->save();

Creating a Checkout Session

use LucaLongo\Subscriptions\Payments\Gateways\StripeGateway;

return app(StripeGateway::class)->subscribe(
    plan: $plan,
    subscriber: $user,
    successUrl: route('subscription.success'),
    cancelUrl: route('subscription.cancel'),
);

This redirects the user to Stripe Checkout. The webhook handler automatically syncs subscription state back to your database.

Webhook

The package registers a webhook route at POST /hooks/payments/stripe. The handler processes these Stripe events:

  • customer.subscription.created
  • customer.subscription.updated
  • customer.subscription.deleted
  • customer.deleted

Livewire Admin Views

The package includes optional Livewire components for managing plans, features, and subscriptions using Filament Table Builder.

Install the required dependencies:

composer require livewire/volt filament/tables guava/filament-clusters

Publish the views:

php artisan vendor:publish --tag="laravel-subscriptions-views"

Available components:

<livewire:subscriptions::manage-plans />
<livewire:subscriptions::manage-features />
<livewire:subscriptions::manage-subscriptions :subscriber="$user" />

Extending Models

You can extend any model by creating your own class and updating the config:

// app/Models/Plan.php
class Plan extends \LucaLongo\Subscriptions\Models\Plan
{
    // Your customizations
}

// config/subscriptions.php
'models' => [
    'plan' => \App\Models\Plan::class,
    // ...
],

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

统计信息

  • 总下载量: 2
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 5
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-04-08

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固