Laravel

Laravel 8 Stripe card management

Share your learning

Laravel stripe card management is the process to manage stripe payment methods from laravel dashboard only.

Today we will learn how we can manage stripe cards for customers with Laravel. I am using laravel 8. 

We will be able to manage stripe cards from laravel dashboard

  1. Add new card
  2. Delete card
  3. Set default card
  4. Retrieve all cards

I assume that you have already set up a laravel project, I am not going to show that process. So, let’s dive into it.
We need a laravel cashier package for stripe card management. Follow the installation steps from the laravel cashier documentation.

composer require laravel/cashier

After successfully setup the cashier with laravel. I hope you already set up the stripe keys in the env file.

STRIPE_KEY=pk_test_DFSLAFDLAFLDSLFDSLFASL
STRIPE_SECRET=sk_test_LOREMIPSUMEFDSJFDSJ

Let’s create the payment methods table in our database.

Payment methods table migration

We need a database table called payment_methods to store stripe cards to our database. It will provide us with a fast response.

Schema::create('payment_methods', function (Blueprint $table) {
            $table->id();
            $table->string('pm_id');
            $table->foreignId('user_id');
            $table->string('card_number');
            $table->string('brand')->nullable();
            $table->string('exp_month');
            $table->string('exp_year');
            $table->string('type')->default('card');
            $table->tinyInteger('default_method')->default(0);
            $table->timestamps();
        });

Create a Payment Methods Controller

Create the payment method controller to manage all activities related to stripe card management with laravel. We can make it a laravel resource controller.

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class PaymentMethodsController extends Controller
{
    /*  GET
/payment-methods */public function index(Request $request) {}

/*  GET
/payment-methods/create */public function create(Request $request) {}

/*  POST
/payment-methods */public function store(Request $request) {}

/*  GET
/payment-methods/{id}/edit */public function edit(Request $request) {}

/*  PUT
/payment-methods/{id} */public function update(Request $request) {}

/*  GET
/payment-methods/{id} */public function show(Request $request) {}

/*  DELETE
/payment-methods/{id} */public function destroy(Request $request) {}
}

Add route for payment methods.

Route::resource(‘payment-methods’, PaymentMethodsController::class);

So, it’s done now. Let’s start the action. First thing is to add a new card.

Add new card

When we click on the add card button we will call the create method in the controller.

<a href=”{{ route(‘payment-methods.create’) }}”>Add Card</a>

And in the create method we will use the setupIntent cashier method then return form view. It will set up the stripe card elements with secret from available intent.

Public function create( Request $request ) {
    $user = auth()->user();

            return view('card-form',  
['intent' => $user->createSetupIntent()] );
}

We will pass the intent to the card button available in the card form. To set up the stripe js you can follow this guide.

<button id="card-button" type="submit" data-secret="{{ $intent->client_secret }}"> Save Card </button>

Create the relationship between PaymentMethods and user

class User extends Authenticatable {
    
    Public function localPaymentMethod() {
        return $this->hasMany(‘App\Models\PaymentMethod’, ‘user_id’, ‘id’);
    }
}

We will use localPaymentMethod function because we are using laravel cashier and we have already paymentMehods function for user model. 

After submitting this form it will go to the store method of the controller. The createOrGetStripeCustomer cashier method helps us to create new customers to the stripe if this user does not exist there. But if it is already saved as a customer to the stripe then it will just return the customer data.

Public function store( Request $request ) {
    $user = auth()->user();

$user->createOrGetStripeCustomer();

            $paymentMethod = $request->payment_method;
            $user->addPaymentMethod($paymentMethod);
    $this->saveRecord([
        ‘pm_id’ => $paymentMethod
]);

            if ( !$user->hasDefaultPaymentMethod() ) {
                $user->updateDefaultPaymentMethod($paymentMethod);
        $this->setDefault($paymentMethod);
}

    return redirect()->route("payment-methods.index")->with([‘success’ => ‘Card is successfully saved!’]);
}

Protected function saveRecord( $col ) {
    $user = auth()->user();
    $paymentMethod = $user->findPaymentMethod($col[‘pm_id’]);

    $user->localPaymentMethod()->updateOrCreate($col, [
                'card_number' => $paymentMethod->card->last4,
                'brand' => $paymentMethod->card->brand,
                'exp_month' => $paymentMethod->card->exp_month,
                'exp_year' => $paymentMethod->card->exp_year,
                'type' => $paymentMethod->type
            ]);

}

Protected function setDefault( $paymentMethod ) {
$user = auth()->user();
   $user->localPaymentMethod()->where(‘default_method’, 1)->update([
        ‘default_method’ => 0
    ]);
 $user->localPaymentMethod()->where(‘pm_id’, $paymentMethod)->update([
        ‘default_method’ => 1
    ]);
}

Here is the logic that the first card will be the default card after that user can add as many as want and set default to another card.

Now, let’s list all the cards

Cards Listing

public function index(Request $request) {
    $user = auth()->user();
    $cards = $user->localPaymentMethod;
    
    return view(‘card-list’, [‘cards’ => $cards]);
}

Delete the card

public function destroy(Request $request) {
$user = auth()->user();

// delete from the stripe with cashier methods
$paymentMethod = 
$user->findPaymentMethod($request->paymentMethodId);
            $paymentMethod->delete();

// delete from our database
$user->localPaymentMethod()->where(‘pm_id’, $request->paymentMethodId)
    ->delete();

return redirect()->route("payment-methods.index")->with([‘success’ => ‘Card is successfully deleted!’]);
}

Update the card

We will use the update method to update the default payment method. If you remember we have already created a method called setDefault to set the default payment method. We are going to use that method here.

public function update(Request $request) {
    $user = auth()->user();
    
    // update to the stripe
    $paymentMethod = 
                $user->findPaymentMethod($request->paymentMethodId);
                $user->updateDefaultPaymentMethod($paymentMethod->id);

    // local update to our database
    $this->setDefault( $request->paymentMethodId );

    return redirect()->route("payment-methods.index")->with([‘success’ => ‘Card is successfully updated!’]);

}

Hope you find this article useful.

Satpal

Recent Posts

How to Switch PHP Versions in XAMPP Easily: Managing Multiple PHP Versions on Ubuntu

Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…

1 year ago

How to Use Coding to Improve Your Website’s SEO Ranking?

Let's understand about how to use coding to improve your website's SEO. In today’s computerized…

1 year ago

Most Important Linux Commands for Web Developers

Let's understand the most important linux commands for web developers. Linux, as an open-source and…

1 year ago

Top 75+ Laravel Interview Questions Asked by Top MNCs

Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…

1 year ago

Mailtrap Integration for Email Testing with Laravel 10

Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…

1 year ago

Firebase Cloud Messaging (FCM) with Ionic 6: Push Notifications

Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…

1 year ago