Simplify Your Online Payments With Laravel Stripe Payment Gateway Integration

 Simplify Your Online Payments With Laravel Stripe Payment Gateway Integration



Payment gateways are an essential operational component of any ecommerce store. It completes the payment mechanism of any ecommerce store and allows users to make hassle-free online payments. In this regard, store owners really haven’t got much choice as the top tier of payment gateways is populated by a handful of names including Stripe and PayPal. Both of these platforms provide easy, secure & fast payment services, and are mostly recommended by the majority of the store owners.

Laravel Stripe has built a reputation of being easy-to-use for both developers and store owners. Because of great compatibility with Laravel, Stripe has become the go-to payment gateway for Laravel ecommerce stores. With a host of features and simple Stripe payment gateway integration in Laravel, many development agencies have opted for Stripe as the default payment gateway option for all ecommerce stores they develop for their clients.

Another important reason for the popularity of Stripe is that it accepts all globally accepted credit and debit cards, thus facilitating payment collections from all over the world. In short, Stripe provides a complete solution for online payment processing requirements for Laravel powered ecommerce stores.

Is Stripe Better than PayPal?

For many ecommerce developers, PayPal is the standard against which they evaluate all other payment gateways. Thus, “ Is Stripe better than PayPal?”, is a common question in many Laravel discussion forums.

To settle this debate, I have decided to compare both the options on five key parameters and make the case in Stripe’s favor.

Transaction and Service Fees

Stripe charges a low fee of 2.9% + 30¢ per successful transaction as long as the overall store turnover remains under $1 million. While this rate varies from country to country, there are no major differences.

While PayPal also charges the same base fee of 2.9% + 30¢ per successful transaction, but it deducts some extra fees that add to the overall cost of doing business.

Security

Watertight security of the overall payment process is among the core reasons of the success of both Stripe and PayPal. Both payment processors ensure easy-to-implement security measures that enhance the overall store security. Stripe offers Stripe.JS, a highly optimized security-focused program that is designed to allow users to collect credit card information without storing anything on the servers.

Payment Processor API

At the moment, Stripe offers one of the finest APIs in the payment processor niche. In fact, the recent PayPal API has borrowed several elements from the Stripe’s API in order to remain competitive. The strengths of Stripe’s API include a simple interface, great documentation and overall ease-of-use. The best part – Stripe offers libraries in all popular languages including PHP, Python, Java and C# to ensure that the users do not have to switch dev infrastructure to use the API. Most of the times, Laravel Stripe payments are not handled on the store’s servers.

Migration and Data Portability

The real test of portability is when you try to migrate away from the payment processor. In the case of PayPal, you run the risk of losing a significant number of your customers. On the other hand, Stripe offers a zero-risk migration to any PCI-compliant platform, without any restrictions on data portability. PayPal doesn’t allow migration of customer credit card data, adding a significant burden to your migration efforts.

Customer Service Issues

While PayPal has greatly improved its customer services (and the days of infrequent email replies and slow phone support are mainly over), it still has a lot of ground to cover before it could be compared with Stripe’s prompt customer support experience. In fact, a large number of users who move away from PayPal mention customer services to be inadequate for their purposes.

Stripe’s success on this front is mainly the result of its roots in entrepreneurship where the customer always comes first and the service offerings are tailored to meet market demands. A good example of the diversity in Stripe’s support is the IRC channels dedicated to Laravel Stripe connection where engineers and expert users help solve user issues.

In this article, I will demonstrate Stripe payment gateway integration in Laravel. The idea is to cover the process in sufficient details so that anyone looking to integrate Stripe with Laravel powered ecommerce stores can easily follow along.

Prerequisites

To begin this Laravel Stripe tutorial, I assume that you have a Laravel application installed on a web server. My setup is:

  • Laravel
  • PHP 7.x

I have used a Cloudways managed Laravel server to host my application because of the optimized dev stack. In addition, I don’t have to worry about server management hassles and thus could dedicatedly focus on my project.

Start by Setting up Stripe

The first step involves the setting up of the payment gateway. Begin by completing the registration process at the Stripe’s website and you will get access to the trial version of Stripe API. Once your account is live, you will see the following page in the browser:

Verify your email and you will get access of your Stripe dashboard. Here you can check the API and Secret keys in the Developers tab. In the tab, click the API Keys and you could see the private, secret key credentials and other related information.

Stripe Configuration with Laravel

The next step is the integration of Stripe with your Laravel app. For this, launch the SSH terminal and enter the following command:

  1. composer require stripe/stripe-php

Here’s the output of the command:

Once the installation of Stripe finishes, update the package.json with the following command:

  1. "cartalyst/stripe-laravel": "7.0.*"

Setup App Service Provider For Laravel Stripe Integration

Next, edit the following two lines in the config/app.php file.

  1. ‘providers’ => [
  2. ….
  3. Cartalyst\Stripe\Laravel\StripeServiceProvider::class,
  4. ],
  5. ‘aliases’ => [
  6. ….
  7. ‘Stripe’ => Cartalyst\Stripe\Laravel\Facades\Stripe::class,
  8. ],

Set up Private and Secret Credentials

Now that everything has been updated, it is time to setup the credentials. Open the .env file and paste the following two variables. Remember to get the values for both the variables from your Stripe dashboard (see the first step):

  1. STRIPE_KEY=pk_test_xxxxxxxxxxxxxxxxxxx
  2. STRIPE_SECRET=sk_test_xxxxxxxxxxxxxx

Setup Stripe Payment Controller

Now set up the Stripe payment controller through the following command:

  1. php artisan make:controller MoneySetupController

Note that I have created the controller with the name MoneySetup controller. You are free to pick the name of your controller.

  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Http\Requests;
  4. use Illuminate\Http\Request;
  5. use Validator;
  6. use URL;
  7. use Session;
  8. use Redirect;
  9. use Input;
  10. use App\User;
  11. use Stripe\Error\Card;
  12. use Cartalyst\Stripe\Stripe;
  13. class MoneySetupController extends Controller
  14. {
  15. public function paymentStripe()
  16. {
  17. return view('paymentstripe');
  18. }
  19. public function postPaymentStripe(Request $request)
  20. {
  21. $validator = Validator::make($request->all(), [
  22. 'card_no' => 'required',
  23. 'ccExpiryMonth' => 'required',
  24. 'ccExpiryYear' => 'required',
  25. 'cvvNumber' => 'required',
  26. //'amount' => 'required',
  27. ]);
  28. $input = $request->all();
  29. if ($validator->passes()) {
  30. $input = array_except($input,array('_token'));
  31. $stripe = Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
  32. try {
  33. $token = $stripe->tokens()->create([
  34. 'card' => [
  35. 'number' => $request->get('card_no'),
  36. 'exp_month' => $request->get('ccExpiryMonth'),
  37. 'exp_year' => $request->get('ccExpiryYear'),
  38. 'cvc' => $request->get('cvvNumber'),
  39. ],
  40. ]);
  41. if (!isset($token['id'])) {
  42. return redirect()->route('addmoney.paymentstripe');
  43. }
  44. $charge = $stripe->charges()->create([
  45. 'card' => $token['id'],
  46. 'currency' => 'USD',
  47. 'amount' => 20.49,
  48. 'description' => 'wallet',
  49. ]);
  50. if($charge['status'] == 'succeeded') {
  51. echo "<pre>";
  52. print_r($charge);exit();
  53. return redirect()->route('addmoney.paymentstripe');
  54. } else {
  55. \Session::put('error','Money not add in wallet!!');
  56. return redirect()->route('addmoney.paymentstripe');
  57. }
  58. } catch (Exception $e) {
  59. \Session::put('error',$e->getMessage());
  60. return redirect()->route('addmoney.paymentstripe');
  61. } catch(\Cartalyst\Stripe\Exception\CardErrorException $e) {
  62. \Session::put('error',$e->getMessage());
  63. return redirect()->route('addmoney.paywithstripe');
  64. } catch(\Cartalyst\Stripe\Exception\MissingParameterException $e) {
  65. \Session::put('error',$e->getMessage());
  66. return redirect()->route('addmoney.paymentstripe');
  67. }
  68. }
  69. }
  70. }

Set up the Route

Finally, it is time to set up the routes. For this, open the routes/web.php file and paste the following code in it:

  1. Route::get('/', function () {
  2. return view('welcome');
  3. });
  4. Route::get('addmoney/stripe', array('as' => 'addmoney.paystripe','uses' => 'MoneySetupController@PaymentStripe'));
  5. Route::post('addmoney/stripe', array('as' => 'addmoney.stripe','uses' => 'MoneySetupController@postPaymentStripe'));

Set up Form View

It is time to create the view based on the Bootstrap classes. This allows building creative frontend forms and buttons.

Create a blade file and name it PaymentStripe.blade.php. Next copy the following code into this file:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1">
  7. <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
  8. <title>Bootstrap 101 Template</title>
  9. <!-- Bootstrap -->
  10. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  11. <!-- Optional theme -->
  12. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
  13. <!-- Latest compiled and minified JavaScript -->
  14. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  15. <style>
  16. .submit-button {
  17. margin-top: 10px;
  18. }
  19. </style>
  20. </head>
  21. <body>
  22. <div class="container">
  23. <div class='row'>
  24. <div class='col-md-4'></div>
  25. <div class='col-md-4'>
  26. <form class="form-horizontal" method="POST" id="payment-form" role="form" action="{!!route('addmoney.stripe')!!}" >
  27. {{ csrf_field() }}
  28. <div class='form-row'>
  29. <div class='col-xs-12 form-group card required'>
  30. <label class='control-label'>Card Number</label>
  31. <input autocomplete='off' class='form-control card-number' size='20' type='text' name="card_no">
  32. </div>
  33. </div>
  34. <div class='form-row'>
  35. <div class='col-xs-4 form-group cvc required'>
  36. <label class='control-label'>CVV</label>
  37. <input autocomplete='off' class='form-control card-cvc' placeholder='ex. 311' size='4' type='text' name="cvvNumber">
  38. </div>
  39. <div class='col-xs-4 form-group expiration required'>
  40. <label class='control-label'>Expiration</label>
  41. <input class='form-control card-expiry-month' placeholder='MM' size='4' type='text' name="ccExpiryMonth">
  42. </div>
  43. <div class='col-xs-4 form-group expiration required'>
  44. <label class='control-label'> </label>
  45. <input class='form-control card-expiry-year' placeholder='YYYY' size='4' type='text' name="ccExpiryYear">
  46. <input class='form-control card-expiry-year' placeholder='YYYY' size='4' type='hidden' name="amount" value="300">
  47. </div>
  48. </div>
  49. <div class='form-row'>
  50. <div class='col-md-12' style="margin-left:-10px;">
  51. <div class='form-control total btn btn-primary' >
  52. Total:
  53. <span class='amount'>$300</span>
  54. </div>
  55. </div>
  56. </div>
  57. <div class='form-row'>
  58. <div class='col-md-12 form-group'>
  59. <button class='form-control btn btn-success submit-button' type='submit'>Pay »</button>
  60. </div>
  61. </div>
  62. <div class='form-row'>
  63. <div class='col-md-12 error form-group hide'>
  64. <div class='alert-danger alert'>
  65. Please correct the errors and try again.
  66. </div>
  67. </div>
  68. </div>
  69. </form>
  70. </div>
  71. <div class='col-md-4'></div>
  72. </div>
  73. </div>
  74. </body>

Once you have added the above view code successfully, you can see the form output in browser as how it looks in real time. In the above view form, i have used some bootstrap classes for desired form customization, you can use your preferred bootstrap classes for styling the form as per way you want. You could also use prebuilt bootstrap form templates in the above code which are particularly made to enhance the front-end creativity of the forms.

Stripe Payment Dashboard

You can see all the payment details and customer credentials in the Stripe payment dashboard. A panel creatively built to show you complete customer details including name, card number, amount details, date and other related information. The dashboard also has the export option given on top right corner, through which you can export all the records of the payments into a separate file. While the search option enables you to search the desired customer record in case of personalized record search.

Conclusion

In this tutorial, I briefly offered an overview of Stripe and how to integrate it in any Laravel application. The article also covered several important features that make Stripe a much better payment gateway than PayPal.

If you have any queries about the Laravel Stripe integration, feel free to ask your questions below in the comments section.

Comments

  1. This comment has been removed by a blog administrator.

    ReplyDelete

Post a Comment