Watch Youtube Video (HINDI) :
in this post we will integrate the authorize.net 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 authorize.net 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 authorization.net 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.
database\migrations\2023_02_14_154301_create_payment_logs_table.php<?php 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) { $table->id(); $table->float('amount',8,2); $table->string('name_of_card')->nullable(); $table->string('response_code')->nullable(); $table->string('transaction_id')->nullable(); $table->string('auth_id')->nullable(); $table->string('message_code')->nullable(); $table->integer('qty'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('payment_logs'); } }
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.
app\Models\PaymentLog.php<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class PaymentLog extends Model { use HasFactory; protected $fillable = [ 'name_of_card', 'amount', 'response_code', 'transaction_id', 'auth_id', 'message_code', 'qty' ]; }
Step 3. Composer Install
Now we will install the composer package for the core dependency of the authorize.net 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.
routes\web.php<?php 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'); }); Auth::routes(); Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home'); Route::get('pay',[PaymentController::class,'pay'])->name('pay'); Route::post('dopay/online',[PaymentController::class,'handleonlinePay'])->name('dopay.online');
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 authorize.net dashboard. paste both keys in your .env file and also add both keys as values.
.envMERCHANT_LOGIN_ID=3v9zC3d6MYkk MERCHANT_TRANSACTION_KEY=96TnPu85ej9D2nPE
Step 6. PaymentController
Now we will create a PaymentController for the defined route method and action redirection to the authorize.net payment portal. use the below command and generate a controller.
App\Http\Controllers\PaymentController.phpphp artisan make:controller PaymentController
Now just copy the given controller given method in your PaymentController.
<?php 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(); $merchantAuthentication->setName(env('MERCHANT_LOGIN_ID')); $merchantAuthentication->setTransactionKey(env('MERCHANT_TRANSACTION_KEY')); // Set the transaction's refId $refId = 'ref' . time(); // Create the payment data for a credit card $creditCard = new AnetAPI\CreditCardType(); $creditCard->setCardNumber($input['cardNumber']); $creditCard->setExpirationDate($input['expiration-year'] .'-'. $input['expiration-month']); $creditCard->setCardCode($input['cvv']); // Add the payment data to a paymentType object $paymentOne = new AnetAPI\PaymentType(); $paymentOne->setCreditCard($creditCard); // // 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("EllenJohnson@example.com"); // // 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->setTransactionType("authCaptureTransaction"); $transactionRequestType->setAmount($input['amount']); $transactionRequestType->setPayment($paymentOne); // $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(); $request->setMerchantAuthentication($merchantAuthentication); $request->setRefId($refId); $request->setTransactionRequest($transactionRequestType); // 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(); PaymentLog::create([ '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.
@extends('layouts.app') @section('content') <div class="container-fluid inner-page"> <div class="card-panel"> <div class="container"> <div class="row"> <div class="col-md-12"> <h1>Laravel Athorized.net Payment</h1> </div> <div class="col-md-12"> @if(session('success_msg')) <div class="alert alert-success">{{session('success_msg')}}</div> @endif @if(session('error_msg')) <div class="alert alert-danger">{{session('error_msg')}}</div> @endif </div> <div class="col-md-6" style="background: lightgreen;border-radius: 5px;padding: 10px;"> <div class="panel panel-primary"> <div> <form method="post" action="{{ route('dopay.online') }}"> @csrf <div class="row"> <div class="form-group col-md-8"> <label>Owner</label> <input type="text" name="owner" class="form-control" required> </div> <div class="form-group col-md-4"> <label>CVV</label> <input type="number" name="cvv" class="form-control" required> </div> </div> <div class="row"> <div class="form-group col-md-8"> <label>Card Number</label> <input type="text" name="cardNumber" class="form-control" required> </div> <div class="form-group col-md-4"> <label>Amount</label> <input type="number" name="amount" class="form-control" required> </div> </div> <div class="row"> @php $months = ['1' => 'Jan','2' => 'Feb','3' => 'March','4' => 'April','5' => 'May','6' => 'Jun','7' => 'July','8' => 'Aug','9' => 'Sep','10' => 'OCT','11' => 'Nov','12' => 'Dec']; @endphp <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> @endforeach </select> </div> <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 }}"> {{$i}}</option> @endfor </select> </div> </div> <div class="row"> <div class="col-md-12"> <br> <button class="btn btn-primary" type="submit">Make Payment</button> </div> </div> </form> </div> </div> </div> </div> </div> </div> </div> @endsection
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.
http://127.0.0.1/pay
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
(Co-Founder)We Are Also Recommending You :
- Laravel 9 QR Code Generator Basic To Advanced Tutorial Example
- How to get images from outside project directory laravel
- Upayments Gateway Integration PHP - Laravel
- Join Query Same Table In Laravel
- Livewire Create Multiple Select2 Dynamic Dropdown In Laravel 9 8 Example
- Laravel-9 Multi Authentication Guard Passport API Example
- Laravel Pagination With Search Filter Not Working
- Call to undefined function Gregwar\Captcha\imagecreatetruecolor()
- resize image and upload example laravel intervention
- HTTP Client Guzzle Package With Basic Usage In Laravel