Laravel PhonePe Integration Example

Laravel PhonePe Integration Example

Laravel PhonePe Integration Example

In this post, we will cover the integration of PhonePe in a Laravel application, including generating a payment request and verifying the payment status.

Step 1: Set Up Your PhonePe Account

Before starting the integration, you must set up a PhonePe merchant account. Obtain your merchant ID, API key, and other necessary credentials.

Step 2: Install Required Libraries

Ensure your Laravel project is set up correctly. You might need to use packages like guzzlehttp/guzzle for making API requests:

composer require guzzlehttp/guzzle

Step 3: Configuring Your .env File

Add your PhonePe credentials to the .env file:


PHONEPE_MERCHANT_ID=your_merchant_id
PHONEPE_API_KEY=your_api_key
PHONEPE_SALT_KEY=your_salt_key
PHONEPE_BASE_URL=https://api.phonepe.com
  

Step 4: Creating the Payment Request

Create a controller to handle the payment request:


<?php

namespace App\\Http\\Controllers;

use Illuminate\\Http\\Request;
use GuzzleHttp\\Client;

class PhonePeController extends Controller
{
    public function initiatePayment(Request $request)
    {
        $amount = $request->amount * 100; // Convert to paise
        $merchantId = env('PHONEPE_MERCHANT_ID');
        $apiKey = env('PHONEPE_API_KEY');
        $saltKey = env('PHONEPE_SALT_KEY');
        $baseUrl = env('PHONEPE_BASE_URL');

        $payload = [
            'merchantId' => $merchantId,
            'transactionId' => uniqid(), // Unique transaction ID
            'amount' => $amount,
            'currency' => 'INR',
            'redirectUrl' => route('payment.callback'),
            'validity' => time() + 600, // Payment validity in seconds
        ];

        $data = json_encode($payload);
        $hashedData = hash_hmac('sha256', $data, $saltKey);

        $client = new Client();
        $response = $client->post($baseUrl . '/v3/transaction/initiate', [
            'headers' => [
                'Content-Type' => 'application/json',
                'X-VERIFY' => $hashedData . '###' . $apiKey,
            ],
            'body' => $data,
        ]);

        return response()->json(json_decode($response->getBody(), true));
    }
}
  

Step 5: Payment Callback

Create a method to handle the callback from PhonePe and verify the payment status:


<?php

namespace App\\Http\\Controllers;

use Illuminate\\Http\\Request;
use GuzzleHttp\\Client;

class PhonePeController extends Controller
{
    public function paymentCallback(Request $request)
    {
        $transactionId = $request->transactionId;
        $merchantId = env('PHONEPE_MERCHANT_ID');
        $apiKey = env('PHONEPE_API_KEY');
        $saltKey = env('PHONEPE_SALT_KEY');
        $baseUrl = env('PHONEPE_BASE_URL');

        $url = $baseUrl . "/v3/transaction/$merchantId/$transactionId/status";
        $hashedData = hash_hmac('sha256', $url, $saltKey);

        $client = new Client();
        $response = $client->get($url, [
            'headers' => [
                'X-VERIFY' => $hashedData . '###' . $apiKey,
            ],
        ]);

        $statusResponse = json_decode($response->getBody(), true);

        if ($statusResponse['success']) {
            // Payment successful
            // Update your order status or take necessary action
        } else {
            // Payment failed
        }

        return response()->json($statusResponse);
    }
}
  

Step 6: Testing

Make sure to thoroughly test the integration using test credentials provided by PhonePe. Once everything is working as expected, you can switch to live mode.

With this setup, your Laravel application can handle PhonePe payments effectively!

Laravel Google Pay Integration Example

Laravel Google Pay Integration Example

Laravel Google Pay Integration Example

In this post, we'll walk through the process of integrating Google Pay in a Laravel application.

Step 1: Install Required Packages

First, ensure your project is set up with the necessary packages. You can use the following command to install a payment gateway package like Stripe or Braintree if required:

composer require stripe/stripe-php

Step 2: Setup Google Pay in Frontend

Next, add Google Pay JavaScript in your Blade template or HTML page:

<script async src="https://pay.google.com/gp/p/js/pay.js"></script>

Step 3: Initialize Google Pay

Add the following JavaScript code to initialize Google Pay:


<script>
  const baseRequest = {
    apiVersion: 2,
    apiVersionMinor: 0
  };

  const allowedCardNetworks = ["MASTERCARD", "VISA"];
  const allowedCardAuthMethods = ["PAN_ONLY", "CRYPTOGRAM_3DS"];

  const tokenizationSpecification = {
    type: 'PAYMENT_GATEWAY',
    parameters: {
      'gateway': 'stripe', // or your gateway name
      'stripe:version': '2020-08-27',
      'stripe:publishableKey': 'your-publishable-key'
    }
  };

  const cardPaymentMethod = {
    type: 'CARD',
    parameters: {
      allowedAuthMethods: allowedCardAuthMethods,
      allowedCardNetworks: allowedCardNetworks
    },
    tokenizationSpecification: tokenizationSpecification
  };

  const paymentsClient = new google.payments.api.PaymentsClient({ environment: 'TEST' });

  const paymentDataRequest = Object.assign({}, baseRequest);
  paymentDataRequest.allowedPaymentMethods = [cardPaymentMethod];
  paymentDataRequest.transactionInfo = {
    totalPriceStatus: 'FINAL',
    totalPrice: '10.00',
    currencyCode: 'USD'
  };
  paymentDataRequest.merchantInfo = {
    merchantId: 'your-merchant-id',
    merchantName: 'Your Merchant Name'
  };

  function onGooglePayLoaded() {
    paymentsClient.isReadyToPay({ allowedPaymentMethods: [cardPaymentMethod] })
      .then(function(response) {
        if (response.result) {
          createAndAddButton();
        }
      })
      .catch(function(err) {
        console.error(err);
      });
  }

  function createAndAddButton() {
    const button = paymentsClient.createButton({ onClick: onGooglePayButtonClicked });
    document.getElementById('container').appendChild(button);
  }

  function onGooglePayButtonClicked() {
    paymentsClient.loadPaymentData(paymentDataRequest)
      .then(function(paymentData) {
        // Handle payment data
        console.log(paymentData);
      })
      .catch(function(err) {
        console.error(err);
      });
  }
</script>
  

Step 4: Backend Integration

On the server side, you can use a package like stripe/stripe-php to process the payment:


<?php

namespace App\\Http\\Controllers;

use Illuminate\\Http\\Request;
use Stripe\\Stripe;
use Stripe\\Charge;

class PaymentController extends Controller
{
    public function processPayment(Request $request)
    {
        Stripe::setApiKey('your-stripe-secret-key');

        try {
            $charge = Charge::create([
                'amount' => $request->amount,
                'currency' => 'usd',
                'source' => $request->token,
                'description' => 'Payment Description'
            ]);

            return response()->json(['success' => true, 'data' => $charge]);
        } catch (\\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()]);
        }
    }
}
  

Step 5: Testing

Make sure to test your integration in the Google Pay TEST environment before switching to production.

With this setup, you have a working integration of Google Pay with Laravel!

Laravel Livewire User Active and Inactive Status Example

Laravel Livewire User Active and Inactive Status Example

Laravel Livewire User Active and Inactive Status Example

In this post, we'll walk through an example of using Laravel Livewire to toggle a user's status between active and inactive.

Setting Up the Livewire Component

First, generate a Livewire component:

php artisan make:livewire UserStatusToggle

Component Code

Here's the code for the UserStatusToggle component:


<?php

namespace App\\Http\\Livewire;

use App\\Models\\User;
use Livewire\\Component;

class UserStatusToggle extends Component
{
    public $user;

    public function toggleStatus()
    {
        $this->user->status = $this->user->status === 'active' ? 'inactive' : 'active';
        $this->user->save();
    }

    public function render()
    {
        return view('livewire.user-status-toggle');
    }
}
  

Blade View

Next, create the livewire.user-status-toggle Blade view:


<div>
    <button wire:click="toggleStatus">
        {{ $user->status === 'active' ? 'Set Inactive' : 'Set Active' }}
    </button>
</div>
  

Including Livewire in Your View

Make sure to include Livewire in your layout file:


<head>
    <!-- Other head content -->
    <livewire:styles />
</head>
<body>
    <!-- Your body content -->
    <livewire:scripts />
</body>
  

With this setup, you can easily toggle user statuses using Livewire!