Laravel Cashier

Laravel Cashier for Mollie is a first-party Cashier package—created and maintained by Sander van Hooft—which provides an expressive, fluent interface to subscriptions using Mollie’s billing services. This package is good news for the European Laravel community where Stripe might not be able to fulfill all of their needs. In this 55 minute video, I'll show you how to create a basic e-commerce site powered by a Vue SPA and Laravel API, which takes payments through Stripe thanks.

1 day ago  I am following Laravel's Cashier on SCA and can see that Striple handles '3D Secure' payment verifications for you. The issue I have is that the payment works fine, however, the Laravel user is never updated to be on that subscription because of the redirect back to Stripe. Laravel Cashier provides an expressive, fluent interface to Stripe's (and Paddle's) subscription billing services. What is Laravel Cashier? Laravel Cashier is a module to handle stripe’s and Braintree’s subscription billing services. It handles basic subscription billing code you are dreading writing. In addition to basic subscription management like swapping subscription, cancellation grace periods, and even generate invoice PDFs.

Stripe is one of the most popular payment processing platform with access to 120+ countries. Laravel provides direct integration with Stripe through Laravel Cashier.

Laravel Cashier provides easy and fast integration in Stripe's subscription billing services. It handles almost all Stripe subscription request handling coupons, swapping subscription, subscription 'quantities', cancellation grace periods, and even generate invoice PDFs.

In this article, we will integrate Laravel's Cashier package to receive payments from users directly from your website. We will also create other methods.

Laravel installation and Integration setup

We will integrate Cashier from the scratch so first, create new Laravel project using bellow command.

This will create fresh Laravel project in your system. Make sure you have already installed LAMP and Composer.

Now first install Laravel Cashier package by the Composer.

Also create an authentication scaffold with bellow command.

Database Setup

We have configured Cashier, now we are going to setup database migration. First check .env file in the root folder and setup your database details.

Remember to run migrate command after package install. It will add required field in users table and also add another subscriptions table.

If you want to change in migration, run the bellow command. It will copy migration files to /database/migrations.

Cashier Model

Now add the Billable trait in your model. This trait provides different methods of Stripe information.

If you have used different model other than User, define it in your .env file.

Stripe API Keys

If you already have account in Stripe, you can get Stripe Key and Secret Key from the developer tab[https://dashboard.stripe.com/apikeys] from the menu. Else you can create your Stripe account [https://dashboard.stripe.com/register]. Now set your Stripe Publishable key and Secret key in .env file.

Create Payment methods

There are two types of payment methods, Subscriptions or Single charge methods. It depends upon which methods you want to implement in your project.

Subscription based payment methods

First create new route or update route /home for Stripe payment view. For that, add this route in routes/web.php file.

Now create new controller to handle Stripe routes. run the bellow command.

Add the index() method in the controller class

After create routes, now create blade file resources/views/stripe.blade.php and add pass intent variable in the form. Put bellow html code in the <body> tag.

Then add Stripe.js library bellow the code above the closing </body> tag.

Laravel Cashier

Then add the event listner.

After the card has been verified by Stripe, return to controller method to charge the card. So first create new controller method.

Now add new method charge() in the StripeController where user is created new subscription.

Single charge

If you only want single charge and don't have subscription plans, you can also make single charge.

Laravel

You can also pass third parameter of array to describe charge details.

Refund

You can refund the Stripe charges.

Invoice

You can also get array of invoices.

Or also get including pending transactions.

Then you can display invoices in the blade table with following foreach loop.

And on click Download button, just call downloadInvoice method to download invoice.

Conclusion

This way, you can integrate and charge from Stripe through Laravel Cashier. This is just basic subscription services covered in this article. You can add many services offered by Laravel Cashier. Check this official Documentation for more services.

For latest articles follow HackTheStuff on Twitter and like us our Facebook page.

Was this article helpful?

0 out of 0 person found this article helpful.

We developer always find our selfs to roll some sort of subscription system for web apps running on SaaS (Software as a service) model, it can be simple as subscription for a music store, for mailing app etc. and everyone is offering some sort of coupon to boost their sale, in order to achieve these functionalities we are going to use Strip and Laravel Cashier which make handling subscription a breeze.

Here is little sneak peek what we are going to build, check out the demo for more.

Setup Stripe

If you don’t have an account on stripe please create one, it’s free for testing, it will take one minute, visit https://dashboard.stripe.com/register and sign up.

Create Stripe Plan

Now login into stripe and click Plans under Subscriptions, add some plans, I am adding a Small, Medium and Large plan.

Let’s have a look at the plan options:

  • ID: As its sounds, it’s a unique plan identifier, you can create any name like silver, gold, platinum etc.
  • Name: A user-friendly name for the plan, two plan can have the same name, generally, we keep both id and name same.
  • Amount: Amount in selected currency for this plan.
  • Interval: Plan can be billed monthly, yearly weekly etc.
  • Trial period days: If you enter some number here plan will offer a Free trial option for specified days.

Add Stripe Coupons

Now we have plans let’s also add some coupons, click on Coupons to add some coupons.

Let’s have a look at some fields:

  • Percent Off and Amount Off: Enter in only one of this field, two fields allow you to define a discount according to a specific dollar amount or percentage.
  • Duration: This setting allows you to define how the coupon lasts, once applied. The options are once, multi-month, or forever.
  • ID Code: This is the code the user will enter to take advantage of the discount.
  • Max Redemptions: How many time coupon can be redeemed.
  • Redeem By: For short term offer you can set a date here, for example till New Year.

Laravel Cashier One Time Payment

Stripe API Key

We will need API keys to configure stripe in Laravel, go to your account at the top right and click account settings. Switch tab to API keys and copy the test keys.

Laravel

Now we have all the things needed for subscription added in Stripe control panel, let’s create our app in Laravel 5.3, I am going to make a TrailRider web app where you can subscribe to any of Small, Medium or Large plan to access keep your train running. After subscribing to a plan you can visit the dashboard and you can see what’s plan you are currently on, invoices, option to cancel your subscription or upgrade/downgrade plans.

We have a lot to cover so let’s get started by creating the app and setting it up with Stripe API keys.

If you don’t have Laravel installed you can use Composer to create project composer create-project --prefer-dist laravel/laravel TrainRider

Once composer pulls all the dependencies, go to .env file and update the database credentials, add Stripe Keys.

Now install the laravel cashier, open composer.json and add “laravel/cashier': '~7.0' in required block, run composer update to pull it. Next, register the LaravelCashierCashierServiceProvider service provider in your config/app.php configuration file.

Cashier Migrations

Let’s add migration so cashier can work its magic, run php artisan make:migration add_cashiers_migrations and add below schema in generated migration file.

Migrate the db by running php artisan migrate command. Now we just need to add Billable Trait on our User model. Open the app/User.php and use Billable Trait.

Laravel Auth

Laravel comes with authentication out of the box, to scaffold basic login and registration views and routes we need to run php artisan make:auth. Now we can serve app and visit http://localhost:8000/register and register to see authentication is working. If everything is working now we can get into the fun and main part of this application.

Dashboard

Once user logged in let’s show the subscription status on the dashboard with plans to activate the train, for this lets first get the status in app/Http/Controllers/HomeController.php index method.

I am fetching all the Stripe plans using Stripe’s official php library stripe/stripe-php which is a dependency of Cashier, so it’s already installed. I have one Plan class which has only one method to fetch the plans from stripe API and cache it for one day since plans are not going to change that frequently.

Next, update the resources/views/home.blade.php and add some conditional to show an appropriate message for subscribed & no subscribed user.

Below this greetings screen, I am listing all the plans fetched from Stripe with a button to subscribe.

Subscribe to a Plan

Subscribing to a plan is very easy with the help of stripe.js we will be posting our credit card info to the stripe, then stripe will send us back a stripeToken which will be required by our laravel backend to charge the card.

Stripe needs cards number, exp_month, exp_year & cvc fields in order to return a token against which we can charge the card.

When the user clicks on any plans subscribe button, we will show plan detail and credit card form to process the subscription request. let’s create our PlanController and add below code in it.

Now we need plan view plan.blade.php, create the file and add below code.

It’s credit card form with hidden input for chosen plan by the user. If you noticed there are no name attribute on input associated with the card, instead data-stripe is used so that when we submit this form to our app, no card data will touch our server, that’s what make it secure. Form processing is done using jQuery.

Now when you submit the form stripe.js will make a request to API and get us a token back, which we send to our application to charge the card and start a subscription for currently logged user.

Stripe.js should be loaded directly from https://js.stripe.com/v2/.

Let’s add our subscription handling code in our PlanController, thanks to Cashier its pretty easy to do, we have already used Billable Trait on the User model, which gives us many methods to deal with subscription handling.

This subscribe method does two things, if the user already has a subscription it allows to change it, and it can also subscribe new with Coupon or without a coupon.

Always wrap your stripe api related code in try {} catch {} blocks, its very possible something can go wrong in connection to Stripe api, you can always show error message to user.

I have called newSubscription method one currently logged in user to start a subscription with the plan selected by user. I have also passed email to Stripe since Cashier will create a Stripe customer with it and associate the subscription. You can pass additional data also.

Once user Subscribed we will redirect him/her to the dashboard with the train running.

Apply Coupon

We have already covered this in above code snippet but here’s how it works, we just need to chain the withCoupon() before calling create() to newSubscription method while subscribing the user.

Canceling a Subscription

Cancellation is very simple, you just get the user and call cancel() on it $me->subscription('main')->cancel(); Cashier will set the user as canceled but user can still access if some time is left as grace period. But user will be not charged on next billing period.

Resume a Subscription

User can always resume subscription while he is on grace period. you just need to call you guessed it $me->subscription('main')->resume();.

One off Charge

If some reason you want to make a “one off” charge on the customer for the given amount you can do it by using cashiers $me->charge($amount) method.

Refund

Cashier also provides a way to issue a refund by using cashiers $me->refund($charge_id) method, this method takes the second argument with $options array, if you want a partial refund you need to pass amount in options array to refund, by default complete refund will be granted.

Stripe Invoices

Now we just need to list invoices for user. Create a InvoiceController and add below code.

View is simple table with invoice list.

Handling Stripe Webhooks

Stripe notify your application of a variety of events via webhooks, to handle Stripe webhooks, define a route that points to Cashier’s webhook controller. This controller will handle all incoming webhook requests and dispatch them to the proper controller method.

Laravel

Now configure the webhook URL in your Stripe control panel under your account settings.

Laravel Cashier Paypal

Now all the events will be sent to you using a post call from stripe, but wait we have cross-site request forgery ( CSRF ) protection on, we need to allow stripe/* to do that open the app/Http/Middleware/VerifyCsrfToken.php and add this end-point in except array.

This will not run CSRF middleware on stripe webhook calls, Cashier automatically handles subscription cancellation on failed charges events, but you can handle other events also by extending Webhook controller, methods should be prefixed with handle and the “camel case” name of the Stripe webhook you wish to handle. For example, if you wish to handle the invoice.payment_succeeded webhook, you should add a handleInvoicePaymentSucceeded method to the controller:

Laravel Cashier Tutorial

For brevity I haven’t shared all of the code in the article, you can always check our source code on GitHub repo. I hope you enjoyed this post and learned something. Please check out the demo. I will be happy to hear from you in comments.