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.
PayPal is one of the most popular payment platforms in the world. Its use has several advantages:
Before you start, make sure you have the following:
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
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
To integrate PayPal, you need your credentials, which include the Client ID and Client Secret. Follow these steps to obtain these credentials:
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.
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 ], ];
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.'; } }
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');
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()); } }
Before launching your application, make sure to carry out thorough testing. Use PayPal's sandbox environment to conduct test transactions before going live.
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!
Page loaded in 32.02 ms