How to Integrate PhonePe Payment Gateway for Website in Laravel: A Guide to Production Environment Integration

 

PhonePe, a leading digital payments platform in India, offers a seamless integration process for businesses looking to accept payments. Integrating PhonePe into your production environment involves several steps to ensure a smooth and secure payment experience for your customers. In this guide, we'll walk you through the process of integrating PhonePe into your production environment.

 

Step 1: Create a PhonePe Business Account

 

Before you can integrate PhonePe into your production environment, you'll need to create a PhonePe Business Account. Visit the PhonePe Business website and follow the instructions to create an account. Once your account is set up, you'll receive access to the PhonePe Merchant Dashboard, where you can manage your transactions and settings.

 

Step 2:  Obtain PhonePe Payment API Credentials

 

To integrate PhonePe into your production environment, you'll need to obtain API credentials from PhonePe. Log in to your PhonePe Merchant Dashboard and navigate to the API section. Here, you'll find your API key and other necessary credentials. Keep these credentials secure, as they are essential for integrating PhonePe into your application.

 

Step 3: Setting Up Merchant ID and Merchant Key

 

First, open your .env file and add your Merchant ID and Merchant Key provided by PhonePe:

 

PHONEPE_MERCHANT_ID=your_merchant_id_here

PHONEPE_MERCHANT_KEY=your_merchant_key_here

 

Step 4: Installing the Ixudra\Curl Package

 

Next, install the Ixudra\Curl package to handle HTTP requests:

 

composer require ixudra/curl

 

Step 5: Creating and Setting Up config\phonepe.php

 

Create a new configuration file config\phonepe.php and add the following configuration:

 

return [

    'merchant_id' => env('PHONEPE_MERCHANT_ID'),

    'merchant_key' => env('PHONEPE_MERCHANT_KEY'),

];

 

Step 6: Setting Up VerifyCsrfToken Middleware

 

In the app\Http\Middleware\VerifyCsrfToken.php file, add the following to the $except array to exclude the PhonePe callback URL from CSRF verification:

 

protected $except = [

    'phonepe/callback',

];

 

Step 7: Creating Product Cart Page and Payment Success Page


Create a product cart page where users can add items to their cart and proceed to payment. Also, create a payment success page to display the payment status after completing the transaction. Payment blade page
@extends('layouts.app')
@section('title') PhonePe Integration
@endsection
@section('content')
< div class="container mt-3">
< div class="row">
< div class="col-lg-6">
< div class="paymentBox mt">

Online Donation

Your Donation Supports Our Mission


< form method="get" action="{{ route('payment') }}">
@csrf
< div class="inputBox">
< span>₹
< input type="text" name="amount" placeholder=" Amount">
< /div>
< div class="inputBox">
< input type="text" name="name" placeholder="Enter Your Name">
< /div>
< div class="col-md-12 px-0">
< div class="donate_box">
< button type="submit" class="theme-btn activeBtn align-middle">Donate and Support
< /div>
< /div>
< /form>
< /div>
< /div>
< /div>
< /div>
@endsection

Payment success blade page

@extends('layouts.app')
@section('title') phonePe Integration
@endsection
@section('content')
< div class="container">
< div class="row justify-content-center">

Congratulations! {{ $data->message }}

@if(!empty($data->data->transactionId))

Transaction Id : {{ $data->data->transactionId } @endif
@if(!empty($data->data->amount))

Amount : ₹ {{ $data->data->amount / 100}}

@endif
< /div>
< /div>
< /div>
< /div>
< /div>
@endsection

Step 8: Creating Routes for Payment and Status


Define routes in your routes\web.php file for payment and status:


Route::get('/payment', 'PaymentController@makePayment')->name('payment');


Route::any('/phonepe/callback', 'PaymentController@paymentCallback')->name('payment.callback');


Step 9: Creating Controller and Setting Up Functions

Create a PaymentController using the following command:


php artisan make:controller PaymentController


In the PaymentController, define the makePayment function to initiate the payment and the paymentCallback function to handle the payment status callback from PhonePe:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Ixudra\Curl\Facades\Curl;

class PaymentController extends Controller {

    public function makePayment()

$merchantID = config('phonepe.merchant_id');

$saltKey = config('phonepe.merchant_key');

$saltIndex = 1;

$transactionId = 'PHONEPE' . uniqid();

// Store the transaction ID in the session

$request->session()->put('phonepe_transaction_id', $transactionId);

// Retrieve the transaction ID from the session

$merchantTransactionId = $request->session()->get('phonepe_transaction_id');

$data =  [

"merchantId" => $merchantID,

=> $merchantTransactionId,

"merchantUserId" => "PHONEPEUSER" . $merchantTransactionId,

            "amount" => $request->amount * 100,

            "redirectUrl" => route('response'),

            "redirectMode" => "REDIRECT",

            "callbackUrl" => route('response'),

            "mobileNumber" => "1325879687",

            "paymentInstrument" => [

                "type" => "PAY_PAGE"

            ],

        ];

        $encode = base64_encode(json_encode($data));

        $string = $encode . '/pg/v1/pay' . $saltKey;

        $sha256 = hash('sha256', $string);

        $finalXHeader = $sha256 . '###' . $saltIndex;

        $url = "https://api.phonepe.com/apis/hermes/pg/v1/pay";

        $response = Curl::to($url)

            ->withHeader('Content-Type: application/json')

            ->withHeader('X-VERIFY: ' . $finalXHeader)

            ->withData(json_encode(['request' => $encode]))

            ->post();

        $rData = json_decode($response);

        if (isset($rData->data->instrumentResponse->redirectInfo->url)) {

            return redirect()->to($rData->data->instrumentResponse->redirectInfo->url);

        } else {

            return "Error: Redirect URL not found in response.";

        }

    }

    public function paymentCallback(Request $request)

    {

        //  Retrieve merchantTransactionId from session

       $merchantTransactionId =  $request->session()->get('phonepe_transaction_id');

        // Retrieve other necessary data

        $merchantID = config('phonepe.merchant_id');

        $saltKey = config('phonepe.merchant_key');

        $saltIndex = 1;

        $finalXHeader = hash('sha256', '/pg/v1/status/' .$merchantID. '/' . $merchantTransactionId . $saltKey) . '###' . $saltIndex;

        $response = Curl::to('https://api.phonepe.com/apis/hermes/pg/v1/status/' . $merchantID . '/' . $merchantTransactionId)

            ->withHeader('Content-Type:application/json')

            ->withHeader('accept:application/json')

            ->withHeader('X-VERIFY:' . $finalXHeader)

            ->withHeader('X-MERCHANT-ID:' . $merchantID)

            ->get();

        $data = json_decode($response);

        if ($data->success && $data->code === 'PAYMENT_SUCCESS') {

            return view('phonepe-success')->with('data', $data);

        } else {

            // Handle error message

            $errorMessage = $data->message ?? 'Unknown error occurred';

            return "Error: $errorMessage";

        }

    }

}    

 

 

Conclusion

 

By following these steps, you can integrate PhonePe payments into your Laravel application for production use. PhonePe provides a seamless payment experience for your users, helping you increase conversions and streamline your payment process.

 

Comments

We Serve clients globally in diverse industries

Stay Upto Date With Our Newsletter.