Laravel 7 Cashier (Stripe) Tutorial with Cartalyst

- Advertisement -
- Advertisement -

The Cashier is an official package of Laravel. Laravel 7 brought a big change in this package. There has much difference between Laravel6 to Laravel7 on this package. So in this article, I’ll show you how you can Cashier with Laravel 7 by using the library Cartalyst. It’s so easy to process. At first, see how it’ll work.

We’ll make a payment with Laravel 7 official package Cashier and Stripe.

You can go to Laravel Cashier Official Documentation and read the article. Then run these command from your terminal or command prompt:

composer require laravel/cashier

The Cashier service provider registers its own database migration directory, so run the command to migrate your database after installing the package.

php artisan migrate

If you need to overwrite the migrations that ship with the Cashier package, you can publish them using the vendor:publish Artisan command:

php artisan vendor:publish --tag="cashier-migrations"

Now you need to create a Controller to process the payment. So run the command-

php artisan make:controller PaymentController

And create a route on web.php.

Route::post('stripe-payment', 'PaymentController@store')->name('stripe.store');

In this step, we have to install the Cartalyst library. It’s an easy process. Open your composer.json file and add the following to the require array:

"cartalyst/stripe": "~2.0"

Now run the command.

php composer update

It’ll take sometimes and add the Cartalyst into your project.

Now you need a Stripe account to get API and Secret Key. You may need to verify your business address to make the API working. You can use the address.

TED Conferences LLC
330 Hudson Street
New York, NY 10013

Then go to API Test Page. Here you will see your API keys.

Stripe API Keys
Now go to the Stripe UI Form Element page. We’ll use this form.

Stripe UI Form

Now open welcome.blade.php, we’ll apply the payment system here. Cope HTML code from the Stripe UI Form and paste welcome.blade.php:

<div class="links" style="margin-top:20px">
    <script src="https://js.stripe.com/v3/"></script>
    
    <form action="{{route('stripe.store')}}" method="post" id="payment-form">
        @csrf
        <div class="form-row">
            <label for="card-element">Credit or debit card</label>
            <div id="card-element">
                <!-- A Stripe Element will be inserted here. -->
            </div>
    
            <!-- Used to display form errors. -->
            <div id="card-errors" role="alert"></div>
        </div>
    
        <button id="st-btn">Submit Payment</button>
    </form>
</div>

Then copy CSS and paste into welcome.blade.php.

/* Stripe CSS */
.StripeElement {
  box-sizing: border-box;
  height: 40px;
  padding: 10px 12px;
  border: 1px solid transparent;
  border-radius: 4px;
  background-color: white;
  box-shadow: 0 1px 3px 0 #e6ebf1;
  -webkit-transition: box-shadow 150ms ease;
  transition: box-shadow 150ms ease;
}

.StripeElement--focus {
  box-shadow: 0 1px 3px 0 #cfd7df;
}

.StripeElement--invalid {
  border-color: #fa755a;
}

.StripeElement--webkit-autofill {
  background-color: #fefde5 !important;
}
.form-row {
  width: 65%;
  float: left;
}
form#payment-form {
  background: #f7f8f9;
  padding: 50px;
}
button#st-btn {
  width: 32%;
  padding: 11px;
  margin-left: 10px;
  margin-top: 21px;
  background: #43458b;
  border: none;
  color: #fff;
  height: 42px;
  line-height: 40px;
  padding: 0 14px;
  box-shadow: 0 4px 6px rgba(50, 50, 93, 0.11), 0 1px 3px rgba(0, 0, 0, 0.08);
  border-radius: 4px;
  font-size: 15px;
  font-weight: 600;
  letter-spacing: 0.025em;
  cursor: pointer;
}
div#card-errors {
  padding: 6px 0;
  color: #fa755a;
  font-weight: 600;
}

At last copy JS and paste into welcome.blade.php.

// Create a Stripe client.
var stripe = Stripe('pk_test_bo*****************************');

// Create an instance of Elements.
var elements = stripe.elements();

// Custom styling can be passed to options when creating an Element.
// (Note that this demo uses a wider set of styles than the guide below.)
var style = {
    base: {
        color: '#32325d',
        fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
        fontSmoothing: 'antialiased',
        fontSize: '16px',
        '::placeholder': {
            color: '#aab7c4'
        }
    },
    invalid: {
        color: '#fa755a',
        iconColor: '#fa755a'
    }
};

// Create an instance of the card Element.
var card = elements.create('card', {style: style});

// Add an instance of the card Element into the `card-element` <div>.
card.mount('#card-element');

// Handle real-time validation errors from the card Element.
card.addEventListener('change', function(event) {
    var displayError = document.getElementById('card-errors');
    if (event.error) {
        displayError.textContent = event.error.message;
    } else {
        displayError.textContent = '';
    }
});

// Handle form submission.
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
    event.preventDefault();

    stripe.createToken(card).then(function(result) {
        if (result.error) {
            // Inform the user if there was an error.
            var errorElement = document.getElementById('card-errors');
            errorElement.textContent = result.error.message;
        } else {
            // Send the token to your server.
            stripeTokenHandler(result.token);
        }
    });
});

// Submit the form with the token ID.
function stripeTokenHandler(token) {
    // Insert the token ID into the form so it gets submitted to the server
    var form = document.getElementById('payment-form');
    var hiddenInput = document.createElement('input');
    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'stripeToken');
    hiddenInput.setAttribute('value', token.id);
    form.appendChild(hiddenInput);

    // Submit the form
    form.submit();
}

At last, the welcome.blade.php will look like this file. Now open the PaymentController.php from ‘/app/Http/Controller’ directory and paste the code.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Cartalyst\Stripe\Stripe;

class PaymentController extends Controller
{
    public function store(Request $request){
        $stripe = Stripe::make('sk_test_O5*****************************', '2020-03-02'); // used Stripe secret key, not Publishable key
        $charge = $stripe->charges()->create([
            'amount'   => 200,
            'currency' => 'USD',
            'source' => $request->stripeToken,
            'receipt_email' => "admin@email.com",
        ]);

        return "Payment Created";
    }
}

The Controller code working with Cartalyst Stripe which we’ve installed before. Here have lots of parameters and features. Use and customize it as you like. Now open the terminal and run the command.

php artisan serve

On the homepage http://localhost:8000 you’ll see the form. Keep press 4242 again and again. When the form will fillup then press the button. It’s should display “Payment Created”. Now go to the Stripe Payment Page. You’ll see the payment.

If it does not work, check the error instruction, try yourself to solve the problem, check the code again from start. If the problem still, put a comment below.

Share the article on your social profiles. The next tutorial will come on to expand the payment system with user management, social login with Laravel Socialite, etc. Stay close and happy to learn.

- Advertisement -
Mofizulhttp://mofizul.com
Web Developer & Front-end Expert

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay Connected

35,800FansLike
75,435FollowersFollow
6,048,675SubscribersSubscribe
- Advertisement -