EN ES
Home > Web development > Laravel Tutorials > How to Integrate PayPal in Laravel 11

How to Integrate PayPal in Laravel 11

Diego Cortés
Diego Cortés
October 11, 2024
How to Integrate PayPal in Laravel 11

Integrating PayPal into your web application developed with Laravel 11 may seem like a challenge, but with the right steps, you can do it smoothly. This article will guide you through the entire process, from initial setup to full implementation.

Why Choose PayPal?

PayPal is one of the most popular payment platforms in the world. Its use has several advantages:

  • Reliability: PayPal is widely used and trusted by millions of users.
  • Security: It provides robust security measures to protect both customers and merchants.
  • Ease of Use: Users can make payments easily, which can increase your conversion rates.

Prerequisites

Before you start, make sure you have the following:

  • PHP: Laravel 11 requires PHP 8.1 or higher.
  • Composer: To manage dependencies.
  • PayPal Account: You need a PayPal Business account to obtain your credentials.
  • Laravel 11: Have a Laravel 11 project installed.

Step 1: Create a Laravel Project

If you haven't created your Laravel project yet, you can do so using Composer. Run the following command in your terminal:

composer create-project --prefer-dist laravel/laravel project-name

Step 2: Install the PayPal Library

To integrate PayPal, it is recommended to use the PayPal REST SDK library. You can install it with the following command:

composer require paypal/rest-api-sdk-php

Step 3: Configure PayPal Credentials

To integrate PayPal, you need your credentials, which include the Client ID and Client Secret. Follow these steps to obtain these credentials:

  1. Go to the PayPal Developer Portal.
  2. Create a new application in the dashboard.
  3. Copy the Client ID and Client Secret shown.

Next, add these credentials to your .env file:

PAYPAL_CLIENT_ID=your_client_id
PAYPAL_CLIENT_SECRET=your_client_secret
PAYPAL_MODE=sandbox
Note: Change sandbox to live when you are ready for production.

Step 4: Configure the PayPal Service

Create a new configuration file for PayPal. In the config directory, create a new file called paypal.php and add the following code:

<?php

return [
    'client_id' => env('PAYPAL_CLIENT_ID'),
    'client_secret' => env('PAYPAL_CLIENT_SECRET'),
    'settings' => [
        'mode' => env('PAYPAL_MODE', 'sandbox'),
        'http.ConnectionTimeOut' => 30,
        'log.LogEnabled' => true,
        'log.FileName' => storage_path('logs/paypal.log'),
        'log.LogLevel' => 'DEBUG', // PLEASE USE `INFO` LEVEL FOR LOGGING IN LIVE ENVIRONMENTS
    ],
];

Step 5: Create a PayPal Controller

Now, let's create a controller to handle payments. Use the following command to create a controller:

php artisan make:controller PayPalController

Open the PayPalController.php file and add the following code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution;

class PayPalController extends Controller
{
    public function createPayment(Request $request)
    {
        $apiContext = new \PayPal\Rest\ApiContext(
            new \PayPal\Auth\OAuthTokenCredential(
                config('paypal.client_id'),
                config('paypal.client_secret')
            )
        );

        $payer = new \PayPal\Api\Payer();
        $payer->setPaymentMethod('paypal');

        // Set up payment details
        $amount = new \PayPal\Api\Amount();
        $amount->setTotal(100); // Change the total according to your logic
        $amount->setCurrency('USD');

        $transaction = new \PayPal\Api\Transaction();
        $transaction->setAmount($amount);
        $transaction->setDescription('Payment description');

        $redirectUrls = new \PayPal\Api\RedirectUrls();
        $redirectUrls->setReturnUrl(route('paypal.success'))
                     ->setCancelUrl(route('paypal.cancel'));

        $payment = new Payment();
        $payment->setIntent('sale')
                ->setPayer($payer)
                ->setTransactions([$transaction])
                ->setRedirectUrls($redirectUrls);

        try {
            $payment->create($apiContext);
            return redirect($payment->getApprovalLink());
        } catch (\Exception $ex) {
            // Error handling
            return back()->with('error', 'Error creating payment: ' . $ex->getMessage());
        }
    }

    public function executePayment(Request $request)
    {
        // Implement payment execution logic
    }

    public function cancelPayment()
    {
        // Handle cancellation
        return 'The payment has been canceled.';
    }
}

Step 6: Configure Routes

Now you need to define the routes for your payment system in routes/web.php:

use App\Http\Controllers\PayPalController;

Route::get('/paypal/create', [PayPalController::class, 'createPayment'])->name('paypal.create');
Route::get('/paypal/success', [PayPalController::class, 'executePayment'])->name('paypal.success');
Route::get('/paypal/cancel', [PayPalController::class, 'cancelPayment'])->name('paypal.cancel');

Step 7: Execute the Payment

In the executePayment method, implement the logic to execute the payment:

public function executePayment(Request $request)
{
    $apiContext = new \PayPal\Rest\ApiContext(
        new \PayPal\Auth\OAuthTokenCredential(
            config('paypal.client_id'),
            config('paypal.client_secret')
        )
    );

    $paymentId = $request->input('paymentId');
    $payerId = $request->input('PayerID');

    $payment = Payment::get($paymentId, $apiContext);
    $execution = new PaymentExecution();
    $execution->setPayerId($payerId);

    try {
        $result = $payment->execute($execution, $apiContext);
        return 'Payment successfully completed.';
    } catch (\Exception $ex) {
        return back()->with('error', 'Error executing payment: ' . $ex->getMessage());
    }
}

Step 8: Test the Integration

Before launching your application, make sure to carry out thorough testing. Use PayPal's sandbox environment to conduct test transactions before going live.

Conclusion

Integrating PayPal in Laravel 11 can be a straightforward task if you follow the steps described in this article. Make sure to manage both the creation and execution of payments properly to ensure a good user experience.

With these steps, you'll be ready to process payments in your Laravel application with PayPal effectively. Good luck with your implementation!

Diego Cortés
Diego Cortés
Full Stack Developer, SEO Specialist with Expertise in Laravel & Vue.js and 3D Generalist

Categories

Page loaded in 32.02 ms