Skip to main content
Laravel

7 steps, how to integrate PayPal into a Laravel

In this article, we will show you how to add PayPal as a payment option to your booking management application built in Laravel.

By integrating PayPal, you can provide your customers with a secure and easy-to-use online payment option.

We will walk you through the process of installing the PayPal PHP SDK, creating a payment form, handling payment success and cancellation, implementing PayPal’s Instant Payment Notification (IPN) feature, and testing the integration.

Whether you are a developer or a business owner, this guide will provide you with the necessary steps to add PayPal to your booking management application.

The steps are as follows:

  1. Install the PayPal PHP SDK

    To interact with PayPal’s API using PHP, you’ll need to install the PayPal PHP SDK. You can do this by adding the following line to your composer.json file

     "paypal/rest-api-sdk-php": "^1.14"
    

    Then, run composer install to install the package.

  2. Create a PayPal App

    Next, you need to create a PayPal App to get the API credentials required to interact with PayPal’s API. You can create a new app by following the instructions on the PayPal Developer website.

  3. Add PayPal credentials to your Laravel application

    Once you have created a PayPal App, you need to add the API credentials to your Laravel application’s .env file:

     PAYPAL_CLIENT_ID=your_client_id
     PAYPAL_SECRET=your_secret
     PAYPAL_MODE=sandbox
    

    Note that PAYPAL_MODE can be either sandbox or live, depending on whether you’re testing your application or deploying it to a production environment.

  4. Create a PayPal payment form

    Next, you need to create a payment form that allows users to pay for their bookings using PayPal. You can do this by creating a route in your Laravel application that displays a form where users can enter their payment details:

     // Display the payment form
     Route::get('/pay-with-paypal', function () {
         return view('paypal-form');
     });
    
     // Process the payment
     Route::post('/pay-with-paypal', function (Request $request) {
         $apiContext = new PayPalRestApiContext(
             new PayPalAuthOAuthTokenCredential(
                 config('services.paypal.client_id'),
                 config('services.paypal.secret')
             )
         );
    
         $payer = new PayPalApiPayer();
         $payer->setPaymentMethod('paypal');
    
         $amount = new PayPalApiAmount();
         $amount->setTotal($request->input('amount'));
         $amount->setCurrency('USD');
    
         $transaction = new PayPalApiTransaction();
         $transaction->setAmount($amount);
    
         $redirectUrls = new PayPalApiRedirectUrls();
         $redirectUrls->setReturnUrl(url('/payment-success'))
                      ->setCancelUrl(url('/payment-cancelled'));
    
         $payment = new PayPalApiPayment();
         $payment->setIntent('sale')
                 ->setPayer($payer)
                 ->setTransactions([$transaction])
                 ->setRedirectUrls($redirectUrls);
    
         try {
             $payment->create($apiContext);
             return redirect($payment->getApprovalLink());
         } catch (PayPalExceptionPayPalConnectionException $e) {
             return redirect('/payment-error');
         }
     });
    

    In the above code, we create a new ApiContext instance using the PayPal credentials stored in our Laravel application’s .env file. We then create a new payment using the PayPal API, with the payment amount and other transaction details specified by the user in the payment form. Finally, we redirect the user to PayPal’s website to complete the payment.

  5. Handle payment success and cancellation

    Once the user completes the payment on PayPal’s website, they will be redirected back to your Laravel application. You’ll need to create routes to handle both successful and cancelled payments:

     // Handle successful payment
     Route::get('/payment-success', function () {
         return view('payment-success');
     });
    
     // Handle cancelled payment
     Route::get('/payment-cancelled', function () {
         return view('payment-cancelled');
     });
    

    In the above code,we simply display a success or cancellation message to the user, depending on whether their payment was successful or not.

  6. Implement PayPal’s IPN (Instant Payment Notification)

    To verify that the payment was successful and update your booking management application accordingly, you need to implement PayPal’s IPN (Instant Payment Notification) feature. This allows PayPal to send a notification to your application whenever a payment is made or updated.

    Here’s an example of how you can implement the IPN feature in Laravel:

     Route::post('/paypal-ipn', function (Request $request) {
         $listener = new PayPalIPNListener();
         $listener->useSandbox();
         $listener->setSecret(config('services.paypal.secret'));
    
         try {
             $verified = $listener->processIpn($request->getContent());
         } catch (Exception $e) {
             return response()->json(['error' => $e->getMessage()], 400);
         }
    
         if ($verified) {
             $transactionId = $request->input('txn_id');
             // Update booking record in database with $transactionId
             // Send confirmation email to customer
             return response()->json(['status' => 'ok'], 200);
         } else {
             return response()->json(['error' => 'Invalid IPN'], 400);
         }
     });
    

    In the above code, we create a new route to handle the IPN requests sent by PayPal. We use the PayPal SDK’s IPN listener to verify the authenticity of the IPN message and update the booking record in our database with the transaction ID returned by PayPal. We also send a confirmation email to the customer.

  7. Test the PayPal integration

    Once you’ve implemented the PayPal integration in your booking management application, you should test it thoroughly to ensure that everything is working as expected. You can do this by creating test bookings and completing the payment process using a PayPal sandbox account.

In summary, integrating PayPal into a booking management application built with Laravel involves installing the PHP SDK, creating a PayPal App to get the API credentials, adding the PayPal credentials to your Laravel application, creating a payment form, handling payment success and cancellation, implementing PayPal’s IPN feature, and testing the integration thoroughly.