search
HomePHP FrameworkLaravelLaravel development: How to use Laravel Cashier to implement Stripe subscription payment?

Laravel开发:如何使用Laravel Cashier实现Stripe订阅付款?

Stripe是一家全球领先的在线支付处理公司,它提供了在全球范围内可靠的支付基础设施,让开发者和业务人员能够方便地实现在线付款功能。使用Stripe,开发者可以轻松地实现用户的支付流程,并且可以支持多种付款方式,包括信用卡、支付宝、微信等。

Laravel是一种非常流行的PHP框架,它具有简单、优雅、高效等特点,并提供了许多强大的功能。Laravel Cashier是Laravel的一个扩展包,它提供了一个简单而强大的方式来管理Stripe订阅付款,使得在Laravel应用中实现订阅和付款变得更加容易。

下面将会介绍如何在Laravel应用中使用Laravel Cashier扩展包来管理Stripe订阅付款。

第一步:安装Laravel Cashier扩展包

在Laravel应用中,安装Laravel Cashier扩展包非常简单。首先,通过Composer安装:

composer require laravel/cashier

然后,运行数据库迁移:

php artisan migrate

第二步:配置Stripe API密钥

在使用Laravel Cashier之前,需要在.env文件中配置Stripe API密钥。可以在Stripe Dashboard上找到你的密钥,并将其添加到.env文件中:

STRIPE_KEY=your-stripe-key
STRIPE_SECRET=your-stripe-secret

第三步:创建Stripe订阅计划

在使用Laravel Cashier之前,需要在Stripe Dashboard上创建订阅计划。可以在Stripe Dashboard上选择“Billing-Subscriptions-Plans”来创建订阅计划。

创建订阅计划需要指定计划的名称、价格、付款周期等信息。在创建完订阅计划后,需要记下订阅计划的ID,后面会用到。

第四步:创建自定义用户模型

Laravel Cashier在使用中需要使用自定义用户模型,因此需要在Laravel应用中创建一个自定义用户模型。可以通过运行以下命令来创建该模型:

php artisan make:model User

然后,在User模型中添加以下代码以使用Laravel Cashier:

use LaravelCashierBillable;

class User extends Authenticatable
{
    use Billable;
}

通过在User模型中使用Laravel Cashier的Billable trait,可以使该模型具有订阅计划和付款相关的功能。

第五步:创建订阅控制器

在Laravel应用中,需要创建一个控制器来处理订阅相关的操作,包括创建订阅、更新订阅、取消订阅等。

可以使用以下命令来创建订阅控制器:

php artisan make:controller SubscriptionController

然后,在SubscriptionController中添加以下代码以实现订阅功能:

use IlluminateHttpRequest;

class SubscriptionController extends Controller
{
    public function create(Request $request)
    {
        $user = $request->user();
        $plan = $request->input('plan');
        $user->newSubscription('main', $plan)->create($request->stripeToken);
        return redirect('/home')->with('success', 'Subscription created successfully.');
    }

    public function edit(Request $request)
    {
        $user = $request->user();
        $subscription = $user->subscription('main');
        $subscription->swap($request->input('plan'));
        return redirect('/home')->with('success', 'Subscription updated successfully.');
    }

    public function destroy(Request $request)
    {
        $user = $request->user();
        $subscription = $user->subscription('main');
        $subscription->cancel();
        return redirect('/home')->with('success', 'Subscription cancelled successfully.');
    }
}

在上述代码中,create()方法用于创建新的订阅,edit()方法用于更新订阅计划,destroy()方法用于取消订阅。

第六步:创建订阅视图

最后,在Laravel应用中创建一个订阅视图,并在该视图中包含订阅表单。可以使用以下命令来创建订阅视图:

php artisan make:view subscribe

然后,在创建的subscribe.blade.php视图中添加以下表单:

<form action="{{ route('subscription.create') }}" method="post">
    @csrf
    <label for="plan">Subscription Plan</label>
    <select name="plan">
        <option value="basic">Basic ($10/month)</option>
        <option value="pro">Pro ($20/month)</option>
    </select>
    <script
        src="https://checkout.stripe.com/checkout.js" class="stripe-button"
        data-key="{{ env('STRIPE_KEY') }}"
        data-amount="1000"
        data-name="My Site"
        data-description="Monthly Subscription"
        data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
        data-locale="auto"
        data-currency="usd"
    >
    </script>
</form>

通过在上述表单中使用Stripe Checkout,可以使用户直接从应用中进行支付。

然后,在Laravel应用中添加订阅路由,以便在视图中使用该路由:

Route::post('/subscription', [SubscriptionController::class, 'create'])->name('subscription.create');
Route::put('/subscription', [SubscriptionController::class, 'edit'])->name('subscription.edit');
Route::delete('/subscription', [SubscriptionController::class, 'destroy'])->name('subscription.destroy');

最后,在应用中添加相关的页面来显示订阅和取消订阅的状态,以及其他相关信息。

总结

使用Laravel Cashier和Stripe,可以让开发者轻松地实现订阅和付款功能。在本文中,介绍了如何在Laravel应用中使用Laravel Cashier来管理Stripe订阅付款,包括安装Laravel Cashier、配置Stripe API密钥、创建Stripe订阅计划、创建自定义用户模型、创建订阅控制器和订阅视图等。

当然,在实现订阅和付款功能时,还需要遵守相关的法律、规定和标准,确保用户的隐私和支付安全。希望这篇文章对Laravel开发者有所帮助,让他们更加轻松地实现Stripe支付功能。

The above is the detailed content of Laravel development: How to use Laravel Cashier to implement Stripe subscription payment?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Last Laravel version: Migration TutorialLast Laravel version: Migration TutorialMay 14, 2025 am 12:17 AM

What new features and best practices does Laravel's migration system offer in the latest version? 1. Added nullableMorphs() for polymorphic relationships. 2. The after() method is introduced to specify the column order. 3. Emphasize handling of foreign key constraints to avoid orphaned records. 4. It is recommended to optimize performance, such as adding indexes appropriately. 5. Advocate the idempotence of migration and the use of descriptive names.

What is the Latest LTS Version of Laravel?What is the Latest LTS Version of Laravel?May 14, 2025 am 12:14 AM

Laravel10,releasedinFebruary2023,isthelatestLTSversion,supportedforthreeyears.ItrequiresPHP8.1 ,enhancesLaravelPennantforfeatureflags,improveserrorhandling,refinesdocumentation,andoptimizesperformance,particularlyinEloquentORM.

Stay Updated: The Newest Features in the Latest Laravel VersionStay Updated: The Newest Features in the Latest Laravel VersionMay 14, 2025 am 12:10 AM

Laravel's latest version introduces multiple new features: 1. LaravelPennant is used to manage function flags, allowing new features to be released in stages; 2. LaravelReverb simplifies the implementation of real-time functions, such as real-time comments; 3. LaravelVite accelerates the front-end construction process; 4. The new model factory system enhances the creation of test data; 5. Improves the error handling mechanism and provides more flexible error page customization options.

Implementing Soft Delete in Laravel: A Step-by-Step TutorialImplementing Soft Delete in Laravel: A Step-by-Step TutorialMay 14, 2025 am 12:02 AM

Softleteinelelavelisling -Memptry-braceChortsDevetus -TeedeecetovedinglyDeveledTeecetteecedelave

Current Laravel Version: Check the Latest Release and UpdatesCurrent Laravel Version: Check the Latest Release and UpdatesMay 14, 2025 am 12:01 AM

Laravel10.xisthecurrentversion,offeringnewfeatureslikeenumsupportinEloquentmodelsandimprovedroutemodelbindingwithenums.Theseupdatesenhancecodereadabilityandsecurity,butrequirecarefulplanningandincrementalimplementationforasuccessfulupgrade.

How to Use Laravel Migrations: A Step-by-Step TutorialHow to Use Laravel Migrations: A Step-by-Step TutorialMay 13, 2025 am 12:15 AM

LaravelmigrationsstreamlinedatabasemanagementbyallowingschemachangestobedefinedinPHPcode,whichcanbeversion-controlledandshared.Here'showtousethem:1)Createmigrationclassestodefineoperationslikecreatingormodifyingtables.2)Usethe'phpartisanmigrate'comma

Finding the Latest Laravel Version: A Quick and Easy GuideFinding the Latest Laravel Version: A Quick and Easy GuideMay 13, 2025 am 12:13 AM

To find the latest version of Laravel, you can visit the official website laravel.com and click the "Docs" button in the upper right corner, or use the Composer command "composershowlaravel/framework|grepversions". Staying updated can help improve project security and performance, but the impact on existing projects needs to be considered.

Staying Updated with Laravel: Benefits of Using the Latest VersionStaying Updated with Laravel: Benefits of Using the Latest VersionMay 13, 2025 am 12:08 AM

YoushouldupdatetothelatestLaravelversionforperformanceimprovements,enhancedsecurity,newfeatures,bettercommunitysupport,andlong-termmaintenance.1)Performance:Laravel9'sEloquentORMoptimizationsenhanceapplicationspeed.2)Security:Laravel8introducedbetter

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.