Laravel 11 Integrate Authorize.net Payment Gateway Example


Integrating the Authorize.net payment gateway into a Laravel 11 application involves several steps. Here's a detailed guide to help you implement this integration:


### Step 1: Install Laravel 11


If you haven't already installed Laravel 11, create a new Laravel project:


```bash

composer create-project --prefer-dist laravel/laravel laravel-authorize-net

cd laravel-authorize-net

```


### Step 2: Set Up Authorize.net Account


1. **Sign Up for Authorize.net**: If you don’t have an Authorize.net account, sign up at [Authorize.net](https://www.authorize.net/).


2. **Obtain API Credentials**: After signing in, navigate to the API credentials page in the Authorize.net dashboard to obtain your `API Login ID` and `Transaction Key`.


### Step 3: Install Authorize.net SDK


You will need the official Authorize.net SDK for PHP:


```bash

composer require authorizenet/authorizenet

```


### Step 4: Configure Environment Variables


Add your Authorize.net API credentials to the `.env` file:


```env

AUTHORIZE_NET_API_LOGIN_ID=your_api_login_id

AUTHORIZE_NET_TRANSACTION_KEY=your_transaction_key

AUTHORIZE_NET_SANDBOX=true

```


### Step 5: Create PaymentController


Generate a new controller to handle payment processing:


```bash

php artisan make:controller PaymentController

```


In `app/Http/Controllers/PaymentController.php`, add the following methods to handle payment processing:


```php

namespace App\Http\Controllers;


use Illuminate\Http\Request;

use net\authorize\api\contract\v1 as AnetAPI;

use net\authorize\api\controller as AnetController;


class PaymentController extends Controller

{

    public function showForm()

    {

        return view('payment.form');

    }


    public function processPayment(Request $request)

    {

        $request->validate([

            'card_number' => 'required|numeric',

            'expiry_month' => 'required|numeric|min:1|max:12',

            'expiry_year' => 'required|numeric|min:' . date('Y'),

            'cvv' => 'required|numeric|min:3|max:4',

            'amount' => 'required|numeric|min:1',

        ]);


        $merchantAuthentication = new AnetAPI\MerchantAuthenticationType();

        $merchantAuthentication->setName(env('AUTHORIZE_NET_API_LOGIN_ID'));

        $merchantAuthentication->setTransactionKey(env('AUTHORIZE_NET_TRANSACTION_KEY'));


        $refId = 'ref' . time();


        $creditCard = new AnetAPI\CreditCardType();

        $creditCard->setCardNumber($request->card_number);

        $creditCard->setExpirationDate($request->expiry_year . "-" . $request->expiry_month);

        $creditCard->setCardCode($request->cvv);


        $paymentOne = new AnetAPI\PaymentType();

        $paymentOne->setCreditCard($creditCard);


        $transactionRequestType = new AnetAPI\TransactionRequestType();

        $transactionRequestType->setTransactionType("authCaptureTransaction");

        $transactionRequestType->setAmount($request->amount);

        $transactionRequestType->setPayment($paymentOne);


        $request = new AnetAPI\CreateTransactionRequest();

        $request->setMerchantAuthentication($merchantAuthentication);

        $request->setRefId($refId);

        $request->setTransactionRequest($transactionRequestType);


        $controller = new AnetController\CreateTransactionController($request);

        $response = env('AUTHORIZE_NET_SANDBOX', true) ?

            $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX) :

            $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::PRODUCTION);


        if ($response != null) {

            if ($response->getMessages()->getResultCode() == "Ok") {

                $tresponse = $response->getTransactionResponse();

                if ($tresponse != null && $tresponse->getMessages() != null) {

                    return back()->with('success', 'Transaction successful! ID: ' . $tresponse->getTransId());

                } else {

                    return back()->with('error', 'Transaction failed: ' . $tresponse->getErrors()[0]->getErrorText());

                }

            } else {

                $tresponse = $response->getTransactionResponse();

                $errorText = $tresponse != null && $tresponse->getErrors() != null ? $tresponse->getErrors()[0]->getErrorText() : $response->getMessages()->getMessage()[0]->getText();

                return back()->with('error', 'Transaction failed: ' . $errorText);

            }

        } else {

            return back()->with('error', 'No response from payment gateway.');

        }

    }

}

```


### Step 6: Create Payment Form View


Create a view to capture payment details. Create a new file at `resources/views/payment/form.blade.php`:


```html

<!DOCTYPE html>

<html>

<head>

    <title>Payment Form</title>

</head>

<body>

    <h1>Make a Payment</h1>


    @if (session('success'))

        <p style="color: green;">{{ session('success') }}</p>

    @endif


    @if (session('error'))

        <p style="color: red;">{{ session('error') }}</p>

    @endif


    <form action="{{ route('payment.process') }}" method="POST">

        @csrf


        <label for="card_number">Card Number:</label>

        <input type="text" id="card_number" name="card_number" required>

        <br><br>


        <label for="expiry_month">Expiry Month:</label>

        <input type="text" id="expiry_month" name="expiry_month" required>

        <br><br>


        <label for="expiry_year">Expiry Year:</label>

        <input type="text" id="expiry_year" name="expiry_year" required>

        <br><br>


        <label for="cvv">CVV:</label>

        <input type="text" id="cvv" name="cvv" required>

        <br><br>


        <label for="amount">Amount:</label>

        <input type="text" id="amount" name="amount" required>

        <br><br>


        <button type="submit">Pay Now</button>

    </form>

</body>

</html>

```


### Step 7: Define Routes


Add the necessary routes to `routes/web.php`:


```php

use App\Http\Controllers\PaymentController;


Route::get('/payment', [PaymentController::class, 'showForm'])->name('payment.form');

Route::post('/payment/process', [PaymentController::class, 'processPayment'])->name('payment.process');

```


### Step 8: Test the Payment Integration


Run the Laravel server:


```bash

php artisan serve

```


Navigate to `http://localhost:8000/payment` in your browser, fill in the payment form, and submit it. If everything is set up correctly, you should see a success message indicating that the transaction was processed.


### Conclusion


This guide demonstrates how to integrate the Authorize.net payment gateway into a Laravel 11 application using the official Authorize.net PHP SDK. You can now extend this example to handle real-world payment scenarios, including recurring payments, refunds, and more complex transaction types.

Post a Comment

0 Comments