定制 masterix21/laravel-subscriptions 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

masterix21/laravel-subscriptions

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.

masterix21/laravel-subscriptions 适用场景与选型建议

masterix21/laravel-subscriptions 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2 次下载、GitHub Stars 达 1, 最近一次更新时间为 2026 年 04 月 08 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「laravel」 「laravel-subscriptions」 「masterix21」 「Luca Longo」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 masterix21/laravel-subscriptions 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 masterix21/laravel-subscriptions 我们能提供哪些服务?
定制开发 / 二次开发

基于 masterix21/laravel-subscriptions 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

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

GitHub 信息

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

其他信息

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