Categories
Blog
5/5 - (1 vote)

Let’s moves towards updated guide in 2024 , Here we will show you how to integrate PayPal payment features into your Laravel application. We’ll also begin by setting up a PayPal service to seamlessly connect your app with PayPal’s payment infrastructure, thus covering configuration settings and also how to obtain the required API credentials. Furthermore, we’ll walk you through the process of creating PayPal transactions. It will enable your users to securely make payments through your application. Thus by integrating PayPal in Laravel 11 app, you’ll provide a trusted and efficient payment solution for your users.

PayPal in Laravel 11 in 2024

As you know PayPal remains a widely used and trusted payment platform. It allows businesses to securely accept online payments. Laravel is a robust PHP framework. It offers a seamless environment for integrating PayPal’s API to manage transactions efficiently. This is updated guide in 2024, here we’ll show you how to integrate PayPal in Laravel 11. Thus covering key features such as creating and capturing orders. Hence to ensure a successful PayPal in Laravel 11 integration, simply follow these updated steps:

Securing Your API Credentials in 2024

Ensure that your PayPal API credentials, including your Client ID and Secret, are stored securely. It’s important to utilize Laravel’s configuration and environment files to safeguard these credentials, avoiding hardcoding them directly into your application code. For instance, you should place your credentials in the .env file to maintain their security:

# PayPal API credentials
PAYPAL_CLIENT_ID=YourClientIDHere
PAYPAL_SECRET=YourSecretKeyHere

# PayPal environment settings
PAYPAL_MODE=sandbox # Use ‘live’ for production
PAYPAL_SANDBOX_URL=https://api-m.sandbox.paypal.com
PAYPAL_LIVE_URL=https://api-m.paypal.com

Let’s start retrieve them in your config/services.php:

‘paypal’ => [

‘client_id’ => env(‘PAYPAL_CLIENT_ID’),

‘secret’ => env(‘PAYPAL_SECRET’),

‘sandbox_api_url’ => env(‘PAYPAL_SANDBOX_URL’, ‘https://api-m.sandbox.paypal.com’),

‘live_api_url’ => env(‘PAYPAL_LIVE_URL’, ‘https://api-m.paypal.com’),

],

Explanation:

  • The env() function is used to retrieve environment variables from your .env file.
  • The 'sandbox_api_url' and 'live_api_url' keys provide default URLs for the PayPal API in sandbox and live modes, respectively.

Setting Up the PayPal Service in 2024:

In 2024 this section, we will develop a PayPalService class to manage interactions with PayPal’s API effectively. This class will encompass methods for retrieving an authentication token, creating orders, and capturing payments.

Here’s how to define the PayPalService class:

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class PayPalService
{
private const API_SANDBOX_URL = ‘https://api-m.sandbox.paypal.com’;
private const API_LIVE_URL = ‘https://api-m.paypal.com’;

private $apiUrl;
private $clientId;
private $clientSecret;

public function __construct()
{
$this->apiUrl = config(‘services.paypal.mode’) === ‘sandbox’
? self::API_SANDBOX_URL
: self::API_LIVE_URL;

$this->clientId = config(‘services.paypal.client_id’);
$this->clientSecret = config(‘services.paypal.secret’);
}

private function getAuthToken()
{
$response = Http::asForm()
->withHeaders([
‘Authorization’ => ‘Basic ‘ . base64_encode($this->clientId . ‘:’ . $this->clientSecret),
‘Content-Type’ => ‘application/x-www-form-urlencoded’,
])
->post($this->apiUrl . ‘/v1/oauth2/token’, [
‘grant_type’ => ‘client_credentials’,
]);

if ($response->failed()) {
throw new \Exception(‘Failed to obtain PayPal access token’);
}

return $response->json(‘access_token’);
}

public function createOrder(float $amount)
{
$token = $this->getAuthToken();

$response = Http::withToken($token)
->post(“{$this->apiUrl}/v2/checkout/orders”, [
‘intent’ => ‘CAPTURE’,
‘purchase_units’ => [
[
‘amount’ => [
‘currency_code’ => ‘USD’,
‘value’ => $amount,
],
],
],
‘application_context’ => [
‘return_url’ => route(‘paypal.return’),
‘cancel_url’ => route(‘paypal.cancel’),
],
]);

if ($response->failed()) {
throw new \Exception(‘Failed to create PayPal order’);
}

return $response->json();
}

public function captureOrder(string $orderId)
{
$token = $this->getAuthToken();

$response = Http::withToken($token)
->post(“{$this->apiUrl}/v2/checkout/orders/{$orderId}/capture”, [
‘headers’ => [
‘Content-Type’ => ‘application/json’,
‘PayPal-Request-Id’ => uniqid(), // Optionally use a unique ID for idempotency
],
]);

Log::info($response->body());

if ($response->failed()) {
throw new \Exception(‘Failed to capture PayPal order: ‘ . $response->body());
}

return $response->json();
}
}

Important functionality of PayPal in Laravel 11 code in 2024

Environment Setup:

  • API Credentials: Obtain necessary credentials (client ID, client secret) from your PayPal developer account.
  • Mode Selection: Choose between sandbox (testing) or live (production) mode based on your development stage.

API Library Integration:

  • Select a Library: Incorporate a suitable PayPal API library (e.g., PayPal-SDK-PHP, PayPal-SDK-Python) into your project.

Authorization:

  • OAuth Token: Acquire an OAuth access token using the client ID and client secret.
  • Token Storage: Securely store the token for subsequent API calls.

Order Creation:

  • Order Details: Specify order items, total amount, currency, and other relevant information.
  • API Call: Send a POST request to the PayPal API’s /v2/checkout/orders endpoint.

Redirect to PayPal:

  • Checkout URL: Redirect the user to the generated PayPal checkout URL to complete the payment.

Webhook Setup:

  • Webhook URL: Register a webhook URL on your server to receive notifications from PayPal.

Payment Confirmation:

  • Webhook Event: Handle the webhook event when the payment status changes.
  • Order Capture: If the payment is successful, capture the order to receive the funds.

Payment Capture:

  • API Call: Send a POST request to the PayPal API’s /v2/checkout/orders/{order_id}/capture endpoint.

Error Handling:

  • Error Codes: Implement error handling to gracefully handle potential exceptions or API errors.
  • Logging: Log error details for troubleshooting and debugging.

Refund Processing:

  • Refund API: Use the PayPal API’s /v2/checkout/orders/{order_id}/refunds endpoint to process refunds if necessary.

Setting Up Routes of PayPal in Laravel 11 in 2024

Using Named Routes for Cleaner Code

Route::post('paypal/create-order', [PaypalController::class, 'createOrder'])->name('paypal.create');

Route::get('paypal/return', [PaypalController::class, 'handleReturn'])->name('paypal.return');

Route::get('paypal/cancel', [PaypalController::class, 'handleCancel'])->name('paypal.cancel');

Grouping Routes for Organization

Route::group(['prefix' => 'paypal'], function () {
    Route::post('create-order', [PaypalController::class, 'createOrder']);
    Route::get('return', [PaypalController::class, 'handleReturn'])->name('paypal.return');
    Route::get('cancel', [PaypalController::class, 'handleCancel'])->name('paypal.cancel');
});

Using Middleware for Authentication or Authorization

PRoute::post(‘paypal/create-order’, [PaypalController::class, ‘createOrder’])->middleware(‘auth’);

Route::get('paypal/return', [PaypalController::class, 'handleReturn'])->middleware('auth');

Route::get('paypal/cancel', [PaypalController::class, 'handleCancel'])->middleware('auth');

Using a Resource Controller for CRUD Operations

Route::resource('paypal', PaypalController::class);

This will automatically generate routes for index, create, store, show, edit, update, destroy actions.

Using Route Groups with Named Parameters

Route::group(['prefix' => 'paypal/{order_id}'], function () {
    Route::get('return', [PaypalController::class, 'handleReturn'])->name('paypal.return');
    Route::get('cancel', [PaypalController::class, 'handleCancel'])->name('paypal.cancel');
});

Let’s Create the PaypalPaymentController in 2024:

namespace App\Http\Controllers;

use App\Services\PayPalService;
use Illuminate\Http\Request;

class PaypalController extends Controller
{
protected $paypal;

public function __construct(PayPalService $paypal)
{
$this->paypal = $paypal;
}

public function createOrder(Request $request)
{
$amount = $request->input(‘amount’);
$description = $request->input(‘description’, ‘Payment’); // Optional description

// Create a PayPal order with additional details
$response = $this->paypal->createOrder($amount, $description);

return response()->json([
‘order_id’ => $response[‘id’],
‘status’ => $response[‘status’],
‘links’ => $response[‘links’],
]);
}

public function handleReturn(Request $request)
{
$orderId = $request->query(‘token’);

try {
$order = $this->paypal->captureOrder($orderId);

// Handle successful payment
// …

return response()->json([‘status’ => ‘Payment completed successfully’, ‘order’ => $order]);
} catch (\Exception $e) {
// Handle payment capture failure
// …

return response()->json([‘error’ => $e->getMessage()], 500);
}
}

public function handleCancel()
{
// Handle payment cancellation
// …

return response()->json([‘status’ => ‘Payment cancelled’]);
}
}

Key improvements and considerations:

  • Optional description: Added a description parameter to the createOrder method to allow for more informative order details.
  • Error handling: Enhanced error handling for both payment capture and cancellation scenarios. Consider logging errors or redirecting users to an appropriate error page.
  • Payment success/failure handling: Replace the placeholder comments with your actual logic for handling successful payments and payment failures (e.g., storing order information, updating user status, sending notifications).
  • Security: Ensure that sensitive information (e.g., PayPal API credentials) is securely stored and handled. Consider using environment variables or configuration files to avoid exposing them in plain text.
  • Testing: Thoroughly test the controller’s functionality to ensure it works as expected under various conditions.

 

Explanation Related to our codes:

Integrating PayPal Payments in Laravel

To implement PayPal in Laravel 11 application, you’ll need to create three primary functions:

  1. createOrder(): This function generates a PayPal order and returns the required details for the payment process.
  2. handleReturn(): This function captures the order when the user is redirected back to your site after completing the payment.
  3. handleCancel(): This function handles scenarios where the user cancels the payment.

By following these steps, you can seamlessly integrate PayPal into your Laravel project, providing a secure and convenient payment experience for your users. Remember to thoroughly test your integration in PayPal’s sandbox environment before deploying it to production.

PayPal in Laravel 11

PayPal in Laravel 11

PayPal in Laravel 11

 

PayPal in Laravel 11

FAQ’s

How to implement PayPal payment gateway in Laravel?

Here are the steps involved in the integration process. Each step is discussed in detail as well:

Create a PayPal business account.

Install a Laravel app.

Install a composer package.

Enter your PayPal details from your Sandbox account.

Create routes for payments.

Create a controller.

Add a blade view.

PayPal in Laravel 11

What does the PayPal API allow developers to do?

PayPal APIs (Application Programming Interfaces) are a set of tools and protocols that enable developers to integrate PayPal’s payment functionalities, including processing transactions, managing accounts, and accessing financial data, into their applications, websites, or platforms.

 

How to integrate payment gateway API in laravel?

Step 1 – Install the Laravel 8 Application.

Step 2 – Connect Database to an Application.

Step 3 – Add RazorPay Credentials.

Step 4 – Install the Composer Package of RazorPay.

Step 5 – Create Route.

Step 6 – Create Migration and Model.

Step 7 – Create Controller.

How do I create a payment gateway like PayPal?

Create your payment gateway infrastructure. You’ll need a server to host your gateway, whether it’s your own or via a third party.

Choose a payment processor.

Create a customer relationship management (CRM) system.

Implement security features.

Obtain required certifications.

What gateway does PayPal use?

Payflow is a secure, open payment gateway. Merchants can choose that PayPal host the checkout pages and manage security for sales and authorizations. Merchants who want total control over the checkout experience can host their own checkout pages and send transactions to Payflow via an API.

Leave a Reply

Your email address will not be published. Required fields are marked *