Example of Laravel Cashier: paying members, installment payment, and invoice generation

Source: Internet
Author: User
Tags foreach button type current time

1. Create a billing plan in Stripe

As we call it, we have to go to the Personal Center of Stripe to create a subscription plan before writing the business logic code. Navigate to https://dashboard.stripe.com/test/planspage to create two paying member levels: Silver (Silver member) and Gold (Gold member ):

Note the TEST in the upper-left corner of the page. We are currently operating in the Stripe TEST environment.

2. Define a route

After creating the subscription plan, we define the relevant routes for the business logic in routes. php:

// User's personal homepage
Route: get ('Profile ', 'usercontroller @ profile ');
// User membership level
Route: get ('service', 'usercontroller @ service ');
// Paid member page
Route: get ('subauthorization', 'usercontroller @ subauthorization ');
// Process the payment logic
Route: post ('subscribe', 'usercontroller @ subscribe ');
// Upgrade to a higher level
Route: get ('upgrade', 'usercontroller @ upload ');


3. Paid membership implementation


The next step is to write the business logic code in the controller UserController. As we have already talked about how to implement logon authentication, here we use GitHub for logon authentication. After the authentication is complete, go to the/profile page, and then start our business logic.

User Center

First, you can directly go to the member level page on the profile page:

Public function profile (Request $ request)
{
$ User = $ request-> user ();
Return redirect ('service ');
}


Member level

Then, on the service page, write the controller code as follows:

Public function service (Request $ request ){
$ User = $ request-> user ();

If (! $ User-> subscribed ()){
Return redirect ('subauthorization ');
    }
If ($ user-> onPlan ('silver ')){
$ Service = ['type' => 1, 'name' => 'Silver member '];
} Else {
$ Service = ['type' => 2, 'name' => 'gold member '];
    }
Return view ('user. Service', ['service' => $ service]);
}
First, we retrieve the authenticated user instance from the request, and then call the subscribed method on the instance to determine whether the user is a paid member. If not, the user will jump to the payment page, otherwise, the onPlan method is used to determine whether a user is a silver or gold member, and the corresponding View resources/views/user/service is rendered. blade. php:

You are already {$ service ['name'] }}< br>
@ If ($ service ['type'] = 1)
<A href = "/upgrade"> upgrade to a gold member </a>
@ Endif


Buy paid members

For the upgrade, we will first press "no table" to see the implementation logic of purchasing paid members. The code for subscribe in UserController is as follows:

Public function subqueries (Request $ request)
{
$ User = $ request-> user ();
If ($ user-> subscribed ()){
Return redirect ('service ');
    }
Return view ('user. Subobject ');
}

The logic of this page is very simple. First, determine whether it is a paid member. If yes, the page will jump to the membership level page. Otherwise, the paid page will be rendered, next, we will define the corresponding view file resources/views/user/submodules. blade. php is as follows:

<Form action = "/subscribe" method = "post" id = "subscribe-form">
<Span class = "payment-errors"> </span>
{!! Csrf_field ()!!}
<Div>
Payment Plan:
<Select name = "plan">
<Option value = "silver"> silver Member </option>
<Option value = "gold"> gold Member </option>
</Select>
</Div>
<Div>
Credit card No:
<Input type = "text" name = "number" id = "number">
</Div>
<Div>
Expiration Time:
Month: <input type = "text" name = "exp_month" id = "exp_month">
Year: <input type = "text" name = "exp_year" id = "exp_year">
</Div>

<Button type = "submit"> subscription service </button>
</Form>
<Script type = "text/javascript" src = "http://libs.baidu.com/jquery/1.9.1/jquery.min.js"> </script>
<Script type = "text/javascript" src = "https://js.stripe.com/v2/"> </script>
<Script>
Stripe. setPublishableKey ('{{ config ("services. stripe. key ")}}');
JQuery (function ($ ){
$ ('# Subscribe-form'). submit (function (event ){
Var form = $ (this );
Form. find ('Button '). prop ('disabled', true );
Stripe. card. createToken ({
Number: $ ('# number'). val (),
Exp_month: $ ('# exp_month'). val (),
Exp_year: $ ('# exp_year'). val ()
}, StripeResponseHandler );

Return false;
});
});

Var stripeResponseHandler = function (status, response ){
Var form = $ ('# subform-form ');

If (response. error ){
Form. find ('. payment-errors'). text (response. error. message );
Form. find ('Button '). prop ('disabled', false );
} Else {
Var token = response. id;
Form. append ($ ('<input type = "hidden" name = "stripeToken"/>'). val (token ));
Form. get (0). submit ();
        }
};
</Script>

This view file is relatively complex. In this view, we need to select the membership level, enter the credit card number, and the expiration time of the credit card. The value corresponding to the member level is the plan ID corresponding to when we create the order plan in Stripe. The credit card number and expiration time are used to generate the stripeToken, this stripeToken is the value we need to input when calling create to create a subscription plan. Stripe also provides us with a series of available credit card test accounts:

Card number type
4242424242424242 Visa
4012888888881881 Visa
4000056655665556 Visa (debit)
5555555555554444 MasterCard
5200828282828210 MasterCard (debit)
5105105105105100 MasterCard (prepaid)
378282246310005 American Express
371449635398431 American Express
6011111111111117 Discover
6011000990139424 Discover
30569309025904 Diners Club
38520000023237 Diners Club
3530111333300000 JCB
3566002020360505 JCB

As for the expiration time, it only takes longer than the current time. You may also see that you need to enter CVC elsewhere. This is an optional parameter for generating stripeToken. Since it is optional, we will not pay for it here.

This page looks like this in the browser:

Before clicking "subscribe service", let's write the corresponding code for subscribe:

Public function subscribe (Request $ request)
{
$ Plan = $ request-> input ('plan ');
$ CreditCardToken = $ request-> input ('stripetoken ');

$ User = $ request-> user ();
$ User-> Subscribe ($ plan)-> create ($ creditCardToken );
If ($ user-> save ()){
Return redirect ('service ');
} Else {
Return back ()-> withInput ();
    }
}

We can see that we call:

$ User-> Subscribe ($ plan)-> create ($ creditCardToken );
Complete the payment operation to order.

Return to the subscribe view page and click "subscribe to service". After the subscription is successful, the previous service page is displayed as follows:

Upgrade paid members

Finally, we will handle the upgrade logic and write the corresponding business logic code of upgrade as follows:

Public function upgrade (Request $ request ){
$ User = $ request-> user ();
If (! $ User-> subscribed ()){
Return redirect ('subauthorization ');
    }
If ($ user-> onPlan ('gold ')){
Exit ('you are already a gold member ');
    }
Try {
$ User-> Subscribe ('gold')-> swap ();
} Catch (Exception $ ex ){
Exit ('Upgrade failed! ');
    }
Return redirect ('service ');

}

Pass

$ User-> Subscribe ('gold')-> swap ();

You can perform the upgrade operation.

Return to the service page and click "upgrade to gold Member". After successful, the page jumps back to the service page and displays the following information:

You are already a gold member

Now, we have completed the general logic of the paid membership function. In the future, we will discuss how to support more payment methods besides credit cards, such as UnionPay, Alipay, and WeChat payment.

4. Implementation of installment payment

After completing all the above procedures, you will find that the implementation logic is very similar to another application scenario, that is, installment payment. We can divide the total price of goods/services + interest into several periods, calculate the monthly payable amount, and create the corresponding installment payment plan in Stripe. The remaining business logic implementation and paid membership are no different. You can change the membership level to the product type or corresponding service level. For the remaining payment and upgrade, refer to the implementation. I will not go into details here.

Lump sum payment

For items that need to be paid in installments in one lump sum, for example, if the remaining amount is USD 100, you can call the following method:

$ User-& gt; charge (100 );

This method returns a value. If the payment is successful, true is returned. Otherwise, false is returned.

Generate and download the invoice

Laravel Cashier also supports invoice information after payment.

First, obtain all valid invoice information of the user by calling the invoices method on the user instance:

$ Invoices = $ user ()-> invoices ();

Then, the obtained $ invoices loop is displayed in the view:

<Table>
@ Foreach ($ invoices as $ invoice)
<Tr>
<Td >{{$ invoice-> dateString () }}</td>
<Td >{{$ invoice-> dollars () }}</td>
<Td> <a href = "/order/invoice/{{$ invoice-> id }}"> Download invoice </a> </td>
</Tr>
@ Endforeach
</Table>

We will put this code after the above resources/views/user/service. blade. php:

You are already {$ service ['name'] }}< br>
@ If ($ service ['type'] = 1)
<A href = "/upgrade"> upgrade to a gold member </a>
@ Endif
<Div>
Invoice information:
<Table>
@ Foreach ($ invoices as $ invoice)
<Tr>
<Td >{{$ invoice-> dateString () }}</td>
<Td >{{$ invoice-> dollars () }}</td>
<Td> <a href = "/user/invoice/{{$ invoice-> id }}"> Download invoice </a> </td>
</Tr>
@ Endforeach
</Table>
</Div>

After the payment is successful, the page is displayed as follows:

Finally, we can click "Download invoice" in the routing process:

Route: get ('user/invoice/{invoice} ', function ($ invoiceId ){
Return Auth: user ()-> downloadInvoice ($ invoiceId ,[
'Vendor' => 'laravel Emy ',
'Product' => 'gold Member ',
]);
});
This code generates and downloads a PDF file of the corresponding Invoice. Click the "download invoice" button above. The screenshot of the downloaded PDF invoice is as follows:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.