1. Introduction
Laravelcashier provides an elegant and smooth interface for subscribing to payment services via stripe. It encapsulates almost all of the boilerplate subscription payment codes you're afraid to write. In addition to basic subscription management, cashier also supports processing coupons, subscribing to upgrades/replacements, subscribing to "quantities", canceling grace periods, and even generating pdf invoices.
1.1 Installation & Configuration
Composer
First, add the cashier package to the Composer.json file and run the composer Update command:
"Laravel/cashier": "~6.0"
Service Provider
Next, register the service provider in the config/app.php configuration file: Laravel\cashier\cashierserviceprovider.
Migration
Before using cashier, we need to prepare the database. We need to add a field to the Users table and create a new subscriptions table to handle all user subscriptions:
Schema::table (' Users ', function ($table) { $table->string (' stripe_id ')->nullable (); $table->string (' Card_brand ')->nullable (); $table->string (' Card_last_four ')->nullable ();}); Schema::create (' Subscriptions ', function ($table) { $table->increments (' id '); $table->integer (' user_id '); $table->string (' name '); $table->string (' stripe_id '); $table->string (' Stripe_plan '); $table->integer (' quantity '); $table->timestamp (' Trial_ends_at ')->nullable (); $table->timestamp (' Ends_at ')->nullable (); $table->timestamps ();});
Once the migration is created, simply run the migrate command and the changes will be updated to the database.
Setting up the Model
Next, add the billabletrait to the user model class:
Use Laravel\cashier\billable;class User extends authenticatable{use billable;}
Stripe key
Finally, set the Stripe key in the configuration file config/services.php:
' Stripe ' = [ ' model ' = ' User ', ' secret ' = ' env ' (' Stripe_api_secret '),],
2. Subscription implementation
2.1 Creating a Subscription
To create a subscription, you first get an instance of the billing model, typically an instance of App\user. After you get to the model instance, you can use the Newsubscription method to create a subscription to the model:
$user = User::find (1), $user->newsubscription (' main ', ' monthly ')->create ($creditCardToken);
The first argument passed to the Newsubscription method is the name of the subscription, and if the app has only one subscription, it can be called main or primary, and the second parameter specifies the Stripe schedule that the user subscribes to, which corresponds to the ID of the corresponding plan in Stripe.
The Create method automatically creates this Stripe subscription, updating the customer ID of Stripe in the database (that is, stripe_id in the Users table) and other related billing information. If your subscription plan has a trial period, the end of the trial period is automatically set to the corresponding field in the database.
Additional User Information
If you want to specify additional customer information, you can pass it as a second parameter to the Create method:
$user->newsubscription (' main ', ' monthly ')->create ($creditCardToken, [ ' email ' + = $email, ' Description ' = + ' Our first Customer ']);
To learn more about the fields supported by Stripe, you can view Stripe's documentation on creating a consumer.
Discount Coupon
If you want to use coupons when creating a subscription, you can use the Withcoupon method:
$user->newsubscription (' main ', ' monthly ') ->withcoupon (' code ') ->create ($creditCardToken);
2.2 Checking subscription status
Once a user subscribes to your app, you can easily check the status of your subscription using a variety of convenient methods. First, if the user has a valid subscription, the subscribed method returns true even if the subscription is now out of probation:
if ($user->subscribed (' main ')) { //}
The subscribed method can also be used for routing middleware, which allows you to filter routing and Controller access based on the user subscription State:
Public function handle ($request, Closure $next) { if ($request->user () &&! $request->user () Subscribed (' main ')) { //This user was not a paying customer ... Return redirect (' billing '); } Return $next ($request);}
If you want to determine whether a user is still on probation, you can use the Ontrial method, which is useful for displaying warning messages for users who are still in the trial period:
if ($user->->subscription (' main ')->ontrial ()) { //}
The Onplan method can be used to determine whether a user subscribes to a given schedule based on the Stripe ID:
if ($user->onplan (' monthly ')) { //}
Canceled subscription status
To determine if the user was a valid subscriber, but now cancels the subscription, you can use the cancelled method:
if ($user->subscription (' main ')->cancelled ()) { //}
You can also tell if a user has ever canceled a subscription, but are still in the "grace period" until it completely expires. For example, if a user cancels a subscription on March 5 that is actually valid until March 10, the user is in the grace period until March 10. Note The subscribed method still returns true during this period.
if ($user->subscription (' main ')->ongraceperiod ()) { //}
2.3 Modifying a subscription
After the user subscribes to the app, occasionally wants to change to a new subscription plan, to switch users to a new subscription, using the Swap method. For example, we can easily switch users to premium subscriptions:
$user = App\user::find (1); $user->subscription (' main ')->swap (' Stripe-plan-id ');
If the user is on trial, the trial period will be maintained. Also, if the number of subscriptions exists, the quantity can also be maintained. After you switch the subscription plan,
You can use the invoice method to immediately invoice the user:
$user->subscription (' main ')->swap (' Stripe-plan-id '); $user->invoice ();
2.4 Number of subscriptions
Sometimes subscriptions can also be affected by quantity, for example, each account in the app needs to pay $ $ per month, to simply increase or decrease the number of subscriptions, using the Incrementquantity and Decrementquantity methods:
$user = User::find (1); $user->subscription (' main ')->incrementquantity ();//ADD five to the subscription's current Quantity. $user->subscription (' main ')->incrementquantity (5); $user->subscription (' main ') Decrementquantity ()///Subtract five to the subscription's current quantity ... $user->subscription (' main ') Decrementquantity (5);
You can also specify the number using the Updatequantity method:
$user->subscription (' main ')->updatequantity (10);
To find out more about the number of subscriptions, check out the relevant stripe documentation.
2.5 Subscription Tax
In cashier, it is simple to provide tax_percent values to send to Stripe. To specify the tax rate for a user's paid subscription, implement the Gettaxpercent method for the billing model and return a value between 0 and 100, not more than two decimal places:
Public Function gettaxpercent () { return 20;}
This will allow you to use tax rates on a model basis, which is useful for users across different countries.
2.6 Unsubscribe
To unsubscribe, you can call the Cancel method on the user's subscription:
$user->subscription (' main ')->cancel ();
When a subscription is canceled, cashier automatically sets the Subscription_ends_at field in the database. This field is used to understand when the subscribed method begins to return false. For example, if the customer cancels the subscription on March 1, but the subscription does not end until March 5, the subscribed method continues to return true until March 5.
You can use the Ongraceperiod method to determine whether a user has unsubscribed but still in the grace period:
if ($user->subscription (' main ')->ongraceperiod ()) { //}
2.7 Resuming subscriptions
If a user has unsubscribed but wants to recover the subscription, you can use the Resume method, provided that the user has a grace period:
$user->subscription (' main ')->resume ();
If the user cancels a subscription and then resumes the subscription before it expires, the bill is not paid immediately, and instead, their subscription is reactivated and returned to the normal payment cycle.
3. Handling Stripewebhook
3.1 Subscription failure handling
What if the customer's credit card is invalid? Don't worry--cashier comes with a Webhook controller that can easily cancel a customer subscription for you. You only need to define the following controller routes:
Route::p ost (' Stripe/webhook ', ' Laravel\cashier\webhookcontroller@handlewebhook ');
That's it! Failed payments will be captured and processed by the controller. The controller cancels a customer's subscription when Stripe determines that the subscription failed (under normal circumstances, after three attempts to pay failed). Don't forget: You need to configure the appropriate Webhook URI in the Stripe Control Panel settings, otherwise it will not work correctly.
Since Stripe webhooks needs to be verified by Laravel CSRF, we place the URI in the Verifycsrftoken middleware exclusion list:
protected $except = [ ' stripe/* ',];
3.2 Other Webhooks
If you have an extra Stripe Webhook event you want to handle, simply inherit the Webhook controller, your method name should be the same as cashier expected, especially the method should start with "handle" and be named after the hump. For example, if you want to handle Invoice.payment_succeededwebhook, you should add the Handleinvoicepaymentsucceeded method to the controller:
4. Lump -sum payment
If you want to settle your bill one time with a subscriber's credit card, you can use the charge method on the billing model instance, which receives the payment amount (the value of the amount that corresponds to the smallest unit of currency used by the app) as an argument, for example, the following example uses a credit card to pay 100 cents, or $1:
$user->charge (100);
The charge method receives an array as the second parameter, allowing you to pass any underlying Stripe bill creation parameters that you want to pass:
$user->charge ([ ' source ' = ' $token, ' receipt_email ' + $user->email,]);
If the payment fails, the charge method returns false, which usually indicates that the payment was rejected:
if (! $user->charge) { //The charge was denied ...}
If the payment succeeds, the method returns a full Stripe response.
5. Invoice
You can easily get an array of invoices for the billing model using the Invoices method:
$invoices = $user->invoices ();
When a customer invoice is listed, you can use the auxiliary function of the invoice to display the relevant invoice information. For example, you might want to list each invoice in a table, which makes it easier for users to download them:
@foreach ($invoices as $invoice)
{{$invoice->datestring ()}}} |
{{$invoice->dollars ()}}} |
ID}} ">download |
@endforeach
Generate a PDF invoice
Before you generate a PDF ticket, you need to install the PHP library dompdf:
Composer require dompdf/dompdf
In a route or controller, using the Downloadinvoice method to generate a PDF download of the invoice, the method will automatically generate an appropriate HTTP response to send the download to the browser:
Route::get (' User/invoice/{invoice} ', function ($invoiceId) { return Auth::user ()->downloadinvoice ($ Invoiceid, [ ' vendor ' = ' Your company ', ' product ' = ' Your product ', ];});