Integrating PayPal Payments in Your Laravel Application with Omnipay

Last update: 04-25-2024

In this tutorial, we'll explore how to create a basic Laravel application that integrates PayPal payments using the Omnipay library. If you're after a reliable payment solution for your app, look no further!

Prerequisites

Before you begin, ensure you have a PayPal Business account. You must set up a Business account before you can proceed with creating PayPal apps that can receive payments.

Step 1: Creating a PayPal App

After setting up your PayPal Business account, follow these steps to create a PayPal app:

  1. Log into your PayPal Business account.
  2. Navigate to the Developer section (top right corner).
  3. Click on Apps & Credentials.
  4. Select Create App in the dashboard.
  5. Provide a name for your app, select "Merchant" as the type, and then click on Create App.
  6. Take note of the generated client ID and secret key; these will be essential for integrating with your Laravel application.

Step 2: Setting Up Your Laravel Application

  1. Creating the Laravel Project: Begin by generating a new Laravel application named paypal-app. Run the following command in your terminal:
    composer create-project laravel/laravel paypal-app
    This command creates a fresh Laravel application in a directory named paypal-app.
  2. Open the project in your code editor: Use Visual Studio Code (or your favorite editor) to open the newly created Laravel project's folder.
    code paypal-app
  3. Installing Omnipay: Next, integrate Omnipay into your project, which is a flexible payment processing library. Install Omnipay along with the specific PayPal package using Composer:
    composer require league/omnipay omnipay/paypal
    These packages allow your application to communicate with PayPal's APIs.
  4. Creating the Payment Controller: Set up a controller to handle payment operations. Use Artisan, Laravel's command-line tool, to create a controller named PaymentController:
    php artisan make:controller PaymentController
    This controller will be responsible for managing the payment flow in your application, such as initiating payments and handling responses from PayPal.

Step 3: Configuring Your Application

Environment Setup

Update your .env file with your PayPal credentials and preferred currency:

PAYPAL_CLIENT_ID=your-paypal-client-id
PAYPAL_CLIENT_SECRET=your-paypal-secret-key
PAYPAL_CURRENCY=USD

Replace your-paypal-client-id and your-paypal-secret-key with the credentials you obtained from PayPal.

Routing

In your routes/web.php, set up the routes for handling payments:

use App\Http\Controllers\PaymentController;

Route::post('pay', [PaymentController::class, 'pay']);
Route::get('success', [PaymentController::class, 'success']);
Route::get('error', [PaymentController::class, 'error']);

Creating the Payment Form

Edit the welcome.blade.php to include a simple payment form:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Gateway</title>
</head>
<body>
    <form action="/pay" method="post">
        @csrf
        <input type="number" step="0.01" name="amount" placeholder="Enter amount">
        <button type="submit">Proceed to Payment</button>
    </form>
</body>
</html>

Step 4: Building the Payment Controller

The PaymentController will manage all operations related to the PayPal payment process. This includes setting up the gateway, processing payments, and handling success and errors.

A "use" for the Omnipay package:

use Omnipay\Omnipay;

The gateway variable definition:

private $gateway;

The Constructor

When the controller is instantiated, it sets up the PayPal gateway:

public function __construct() {
    $this->gateway = Omnipay::create('PayPal_Rest');
    $this->gateway->setClientId(env('PAYPAL_CLIENT_ID'));
    $this->gateway->setSecret(env('PAYPAL_CLIENT_SECRET'));
    $this->gateway->setTestMode(true);
}

Processing Payments

The pay method handles the payment initiation:

public function pay(Request $request)
{
    $response = $this->gateway->purchase(array(
        'amount' => $request->amount,
        'currency' => env('PAYPAL_CURRENCY'),
        'returnUrl' => url('success'),
        'cancelUrl' => url('error')
    ))->send();

    if ($response->isRedirect()) {
        $response->redirect();
    }
    else{
        return $response->getMessage();
    }
}

Handling Success and Errors

The success and error methods manage successful payments and errors, respectively. They ensure that the payment details are correctly processed or report any issues encountered during the transaction.

public function success(Request $request)
{
    if ($request->input('paymentId') && $request->input('PayerID')) {
        $transaction = $this->gateway->completePurchase(array(
            'payer_id' => $request->input('PayerID'),
            'transactionReference' => $request->input('paymentId')
        ));

        $response = $transaction->send();
        $arr = $response->getData();

        if ($response->isSuccessful()) {
            return "Payment of {$arr['transactions'][0]['amount']['total']} was accepted from {$arr['payer']['payer_info']['email']}. Transaction Id: {$arr['id']}.";
        }
        else{
            return $response->getMessage();
        }
    }
    else{
        return 'Payment declined!!';
    }
}

public function error()
{
    return 'Payment error';   
}

Step 5: Testing Your Application

Run your Laravel server:

php artisan serve

You can now access your application, enter an amount, and proceed to the payment using PayPal's gateway. After completing the payment, you can track API calls related to your app in the PayPal dashboard under "Event logs".

This setup provides a straightforward way to integrate PayPal payments into your Laravel applications, ensuring a smooth transaction process for your users.

StocksComparison.com ad

0 Comments

Add a new comment: