Laravel 11 Integrate Authorize.net Payment Gateway Example

By Hardik Savani September 4, 2024 Category : Laravel

In this tutorial, I will show you how to integrate authorize.net payment gateway in laravel 11 application from scratch.

Authorize.net is an online payment gateway service that helps businesses accept credit card and electronic check payments. It offers secure, reliable payment processing for online and in-person transactions. Businesses can integrate it with their websites or point-of-sale systems to manage payments easily. Authorize.net also provides fraud detection tools, recurring billing options, and customer support to ensure smooth and safe transactions for both merchants and customers.

Here, we will use the authorizenet/authorizenet composer library for the authorize.net payment gateway in laravel 11. We will create a simple payment form where users need to add credit card information and pay $10. You need to create a authorize.net developer account and obtain API login id and transaction key for this example.

laravel 11 Authorize net payment gateway

Step for Laravel Integrate Authorize Net Payment Gateway Example

  • Step 1: Install Laravel 11
  • Step 2: Install authorizenet/authorizenet Package
  • Step 3: Create a Authorize.net Developer Account
  • Step 4: Create Controller
  • Step 5: Create Routes
  • Step 6: Create Blade File
  • Run Laravel App

Step 1: Install Laravel 11

This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Install authorizenet/authorizenet Package

In this step, we need to install authorizenet/authorizenet via the composer package manager, so open your terminal and fire the below command:

composer require authorizenet/authorizenet

Step 3: Create a Authorize.net Developer Account

Now, we need to set the authorizenet login id and transaction key in this step.

1. first you can go on Authorize.net website and create development account.

2. Click on "Account" button, Then click on "API Credentials and Keys" link:

3. Now you can copy Login ID and Generate new transaction key:

Now you need to put API Login ID and Transaction Key in .env file.

You need to add in your .env file:

.env

AUTHORIZENET_API_LOGIN_ID=43C9gcB9
AUTHORIZENET_TRANSACTION_KEY=6HXnd...

Step 4: Create Controller

In the next step, now we have to create a new controller named AuthorizeNetController and write both methods on it as below. So let's create both controllers:

app/Http/Controllers/AuthorizeNetController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;

class AuthorizeNetController extends Controller
{
    /**
     * success response method.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(): View
    {
        return view('authorize-net');
    }
      
    /**
     * success response method.
     *
     * @return \Illuminate\Http\Response
     */
    public function paymentPost(Request $request): RedirectResponse
    {
        $this->validate($request, [
             'card_number' => 'required',
             'expiration_date' => 'required',
             'cvv' => 'required'
        ]);

        $cardNumber = $request->input('card_number');
        $expirationDate = $request->input('expiration_date');
        $cvv = $request->input('cvv');

        $merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
        $merchantAuthentication->setName(env('AUTHORIZENET_API_LOGIN_ID'));
        $merchantAuthentication->setTransactionKey(env('AUTHORIZENET_TRANSACTION_KEY'));

        $creditCard = new AnetAPI\CreditCardType();
        $creditCard->setCardNumber($cardNumber);
        $creditCard->setExpirationDate($expirationDate);
        $creditCard->setCardCode($cvv);

        $payment = new AnetAPI\PaymentType();
        $payment->setCreditCard($creditCard);

        $transactionRequestType = new AnetAPI\TransactionRequestType();
        $transactionRequestType->setTransactionType("authCaptureTransaction");
        $transactionRequestType->setAmount("10.00");
        $transactionRequestType->setPayment($payment);

        $request = new AnetAPI\CreateTransactionRequest();
        $request->setMerchantAuthentication($merchantAuthentication);
        $request->setRefId("ref" . time());
        $request->setTransactionRequest($transactionRequestType);

        $controller = new AnetController\CreateTransactionController($request);
        $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);
        
        if ($response != null) {
            $tresponse = $response->getTransactionResponse();

            if ($tresponse != null & $tresponse->getResponseCode() == "1") {
                return back()->with('success', 'Payment successful!');
            } else {
                return back()->with('error', "Payment failed: ");
            }
        } else {
            return back()->with('error', "Payment failed: " . $response->getMessages()->getMessage()[0]->getText());
        }
        
    }
}

Step 5: Create Routes

In this step, we will create two routes for GET requests and another for POST requests. So, let's add a new route to that file.

routes/web.php

<?php
   
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\AuthorizeNetController;
  
Route::get('authorize/payment', [AuthorizeNetController::class, 'index']);
Route::post('authorize/payment', [AuthorizeNetController::class, 'paymentPost'])->name('authorize.payment');

Step 6: Create Blade File

In the last step, let's create `authorize-net.blade.php` (resources/views/authorize-net.blade.php) for layout and write code of jQuery to get token from authorize here and put the following code:

resources/views/authorize-net.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 Authorize.Net Payment - ItSolutionStuff.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-6 offset-md-3">
            <div class="card mt-5">
                <h3 class="card-header p-3">Laravel 11 Authorize.Net Payment - ItSolutionStuff.com</h3>
                <div class="card-body">

                    @session('success')
                        <div class="alert alert-success" role="alert"> 
                            {{ $value }}
                        </div>
                    @endsession

                    @session('error')
                        <div class="alert alert-danger" role="alert"> 
                            {{ $value }}
                        </div>
                    @endsession
          
                    <form method="POST" action="{{ route('authorize.payment') }}">
                        @csrf

                        <div class="row">
                            <div class="col-md-12">
                                <label for="card_number" class="col-form-label text-md-right">{{ __('Card Number') }}</label>

                                <input id="card_number" type="text" class="form-control @error('card_number') is-invalid @enderror" name="card_number" required autocomplete="off" maxlength="16" placeholder="4111111111111111">

                                @error('card_number')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                                @enderror

                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <label for="expiration_date" class="col-form-label text-md-right">{{ __('Expiration Date (MM/YY)') }}</label>

                                <input id="expiration_date" type="text" class="form-control @error('expiration_date') is-invalid @enderror" name="expiration_date" required autocomplete="off" maxlength="5" placeholder="12/27">

                                @error('expiration_date')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                                @enderror

                            </div>

                            <div class="col-md-6">
                                <label for="cvv" class="col-form-label text-md-right">{{ __('CVV') }}</label>

                                <input id="cvv" type="text" class="form-control @error('cvv') is-invalid @enderror" name="cvv" required autocomplete="off" maxlength="4" placeholder="1234">

                                @error('cvv')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                                @enderror

                            </div>
                        </div>

                        <div class="row mt-3">
                            <div class="col-md-12 text-center">
                                <button type="submit" class="btn btn-success">
                                    {{ __('Make Payment') }}
                                </button>
                            </div>
                        </div>
                    </form>

                </div>
            </div>
        </div>
    </div> 
</div>
      
</body>
 
</html>

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL, and view the app output:

http://localhost:8000/authorize/payment

Now you can check with the following card details:

Visa: 4111111111111111
MasterCard: 5424000000000015
American Express: 370000000000002
Discover: 6011000000000012

Output:

Email Output:

I hope it can help you...

Shares