Laravel 9 Authorize.Net Payment Gateway Integration

  • 20-02-2023
  • 1396
  • Laravel 9
  • Haresh Chauhan

Watch Youtube Video (HINDI) :

in this post we will integrate the payment gateway in laravel, Authorize.Net is a popular payment gateway that allows you to process payments online. Integrating Authorize.Net with Laravel can be done by following these steps.

We need to install the "authorize net/authorize net" package in the laravel app to provide core dependency from the library package, we will integrate authorize. next payment gateway API for your help to integrate into your e-commerce website. Nowadays this payment gateway is very popular for the e-commerce website for accepting payment from users.

In this post we will discuss how to install payment in laravel, as well as I am providing a youtube video tutorial for more understanding for the developer community.

I will show you a live demo of doing the payment sandbox and also in this post I have provided all guidelines for the integration.

Step 1. Clone Project

First, we will install a new fresh laravel clone project, if you already installed then skip this step and move forward to the next step.

composer create-project laravel/laravel:^9.0 example-app

Step 2. Model & Migration

In this step, we will create a model and migration file for the store record and payment id in the database, use below provided command and generate it.

php artisan make:model PaymentLog -m

After that make your migration file something like below provided.


use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePaymentLogsTable extends Migration
      * Run the migrations.
      * @return void
    public function up()
        Schema::create('payment_logs', function (Blueprint $table) {

      * Reverse the migrations.
      * @return void
    public function down()

After that, we will migrate this migration file and create a payment log database table.

php artisan migrate

once you migrate we will put all the table fields in the fillable array attribute in the PaymentLog.php model.


namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class PaymentLog extends Model
    use HasFactory;

    protected $fillable = [

Step 3. Composer Install

Now we will install the composer package for the core dependency of the payment gateway, just copy the below command and paste it into your app command prompt.

composer require "authorizenet/authorizenet"

Step 4. Routes Define

Well, now time to create a router, just copy the below-given router in your web.php file. make sure that you have authenticated your app for the users already.


use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PaymentController;
| Web Routes
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!

Route::get('/', function () {
    return view('welcome');


Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');


Step 5. .env Fiel Key Add

We will set the "MERCHANT_LOGIN_ID" and "MERCHANT_TRANSACTION_KEY" keys in the .env file. these are both keys you need to generate from the dashboard. paste both keys in your .env file and also add both keys as values.


Step 6. PaymentController

Now we will create a PaymentController for the defined route method and action redirection to the payment portal. use the below command and generate a controller.

php artisan make:controller PaymentController

Now just copy the given controller given method in your PaymentController.


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;
use App\Models\PaymentLog;

class PaymentController extends Controller
    public function pay()
        return view('pay');

    public function handleonlinePay(Request $request)
        $input = $request->all();

    /* Create a merchantAuthenticationType object with authentication details
    retrieved from the constants file */
    $merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
    // Set the transaction's refId
    $refId = 'ref' . time();

    // Create the payment data for a credit card
    $creditCard = new AnetAPI\CreditCardType();
    $creditCard->setExpirationDate($input['expiration-year'] .'-'. $input['expiration-month']);

    // Add the payment data to a paymentType object
    $paymentOne = new AnetAPI\PaymentType();

    // // Create order information
    // $order = new AnetAPI\OrderType();
    // $order->setInvoiceNumber("10101");
    // $order->setDescription("Golf Shirts");

    // // Set the customer's Bill To address
    // $customerAddress = new AnetAPI\CustomerAddressType();
    // $customerAddress->setFirstName("Ellen");
    // $customerAddress->setLastName("Johnson");
    // $customerAddress->setCompany("Souveniropolis");
    // $customerAddress->setAddress("14 Main Street");
    // $customerAddress->setCity("Pecan Springs");
    // $customerAddress->setState("TX");
    // $customerAddress->setZip("44628");
    // $customerAddress->setCountry("USA");

    // // Set the customer's identifying information
    // $customerData = new AnetAPI\CustomerDataType();
    // $customerData->setType("individual");
    // $customerData->setId("99999456654");
    // $customerData->setEmail("");

    // // Add values for transaction settings
    // $duplicateWindowSetting = new AnetAPI\SettingType();
    // $duplicateWindowSetting->setSettingName("duplicateWindow");
    // $duplicateWindowSetting->setSettingValue("60");

    // // Add some merchant defined fields. These fields won't be stored with the transaction,
    // // but will be echoed back in the response.
    // $merchantDefinedField1 = new AnetAPI\UserFieldType();
    // $merchantDefinedField1->setName("customerLoyaltyNum");
    // $merchantDefinedField1->setValue("1128836273");

    // $merchantDefinedField2 = new AnetAPI\UserFieldType();
    // $merchantDefinedField2->setName("favoriteColor");
    // $merchantDefinedField2->setValue("blue");

    // Create a TransactionRequestType object and add the previous objects to it
    $transactionRequestType = new AnetAPI\TransactionRequestType();
    // $transactionRequestType->setOrder($order);
    // $transactionRequestType->setBillTo($customerAddress);
    // $transactionRequestType->setCustomer($customerData);
    // $transactionRequestType->addToTransactionSettings($duplicateWindowSetting);
    // $transactionRequestType->addToUserFields($merchantDefinedField1);
    // $transactionRequestType->addToUserFields($merchantDefinedField2);

    // Assemble the complete transaction request
    $request = new AnetAPI\CreateTransactionRequest();

    // Create the controller and get the response
    $controller = new AnetController\CreateTransactionController($request);
    $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);
    // dd($response);

    if ($response != null) {
        // Check to see if the API request was successfully received and acted upon
        if ($response->getMessages()->getResultCode() == "Ok") {
            // Since the API request was successful, look for a transaction response
            // and parse it to display the results of authorizing the card
            $tresponse = $response->getTransactionResponse();
            if ($tresponse != null && $tresponse->getMessages() != null) {
                echo " Successfully created transaction with Transaction ID: " . $tresponse->getTransId() . "\n";
                echo " Transaction Response Code: " . $tresponse->getResponseCode() . "\n";
                echo " Message Code: " . $tresponse->getMessages()[0]->getCode() . "\n";
                echo " Auth Code: " . $tresponse->getAuthCode() . "\n";
                echo " Description: " . $tresponse->getMessages()[0]->getDescription() . "\n";

                    $msg_type = 'success_msg';
                    $message_text = $tresponse->getMessages()[0]->getDescription().' Transaction ID:'.$tresponse->getTransId();

                        'amount' => $input['amount'],
                        'response_code' =>  $tresponse->getResponseCode(),
                        'transaction_id' =>  $tresponse->getTransId(),
                        'auth_id' =>  $tresponse->getAuthCode(),
                        'message_code' =>  $tresponse->getMessages()[0]->getCode(),
                        'name_of_card' =>  $input['owner'],
                        'qty' =>  1,

            } else {
                echo "Transaction Failed \n";
                if ($tresponse->getErrors() != null) {
                    echo " Error Code  : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
                    echo " Error Message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";

                    $msg_type = 'error_msg';
                    $message_text = $tresponse->getErrors()[0]->getErrorText();
            // Or, print errors if the API request wasn't successful
        } else {

              $msg_type = 'error_msg';
                $message_text = 'Transaction Failed ';

            // echo "\n";
            $tresponse = $response->getTransactionResponse();
            if ($tresponse != null && $tresponse->getErrors() != null) {
                echo " Error Code  : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
                echo " Error Message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";

                $msg_type = 'error_msg';
                $message_text = $tresponse->getErrors()[0]->getErrorText();
            } else {
                echo " Error Code  : " . $response->getMessages()->getMessage()[0]->getCode() . "\n";
                echo " Error Message : " . $response->getMessages()->getMessage()[0]->getText() . "\n";

                $msg_type = 'error_msg';
                $message_text = $response->getMessages()->getMessage()[0]->getText();
    } else {
        $msg_type = 'error_msg';
        $message_text = 'No reponse returned';

    return back()->with($msg_type,$message_text);

Step 7. Blade View File

We will also create a blade view file the collect user details. use the below blade file view. This is a form you just need to add data inside for the testing payment gateway. you can make your custom form.


<div class="container-fluid inner-page">
  <div class="card-panel">
    <div class="container">
      <div class="row">
        <div class="col-md-12">
          <h1>Laravel Payment</h1>
        <div class="col-md-12">
          <div class="alert alert-success">{{session('success_msg')}}</div>
          <div class="alert alert-danger">{{session('error_msg')}}</div>
        <div class="col-md-6" style="background: lightgreen;border-radius: 5px;padding: 10px;">
          <div class="panel panel-primary">
              <form method="post" action="{{ route('') }}">
                <div class="row">
                  <div class="form-group col-md-8">
                    <input type="text" name="owner" class="form-control" required>
                  <div class="form-group col-md-4">
                    <input type="number" name="cvv" class="form-control" required>

                <div class="row">
                  <div class="form-group col-md-8">
                    <label>Card Number</label>
                    <input type="text" name="cardNumber" class="form-control" required>
                  <div class="form-group col-md-4">
                    <input type="number" name="amount" class="form-control" required>

                <div class="row">
                  $months = ['1' => 'Jan','2' => 'Feb','3' => 'March','4' => 'April','5' => 'May','6'
                  => 'Jun','7' => 'July','8' => 'Aug','9' => 'Sep','10' => 'OCT','11' => 'Nov','12' =>
                  <div class="form-group col-md-6">
                    <label>Exp Date</label>
                    <select class="form-control" name="expiration-month">
                      @foreach($months as $k => $v)
                      <option value="{{ $k }}">{{$v}}</option>
                  <div class="form-group col-md-6">
                    <label>Exp Year</label>
                    <select class="form-control" name="expiration-year">
                      @for($i = date('Y'); $i <= (date('Y') + 15); $i++) <option value="{{ $i }}">
                <div class="row">
                  <div class="col-md-12">
                    <button class="btn btn-primary" type="submit">Make Payment</button>

Step 8. Start Server

Now time to start the development server, use the below command and start the development server.

php artisan serve

Run the given URL in your browser, you will see a payment form, just enter payment details and test your authorization. next payment. that's it, for now, I hope you guys successfully installed it with your help and this post helped you to integrate it into your laravel app.

We always thanks to you for reading our blogs.


Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us


Haresh Chauhan


We Are Also Recommending You :