image

Laravel PayPal Integration

26 Apr, 2022 Abdelrahman Etry

In this topic i'm going to talk about how to integrate with PayPal with Laravel.

PayPal is an American multinational financial technology company operating an online payments system in the majority of countries that support online money transfers, and serves as an electronic alternative to traditional paper methods such as checks and money orders.

in this topic you'll learn how simply integrate with PayPal and add it to your project .


Requirements:

  1. Create a business account on PayPal.
  2. Activate your Sandbox account to get access to some important details and passwords that you will need in the integration process.
  3. Locate both client_id and secret_key in your PayPal business account.


Optional Step:

  • You can clone this repository from GitHub and put it directly in your project from here.


Steps:


First we need to configure our application

1- Create a new Laravel project by opening your terminal and running the following command:

composer create-project laravel/laravel paypal-integration

2- Navigate to project's directory:

cd paypal-integration

3- Install PayPal SDK in your project by running this command: 

composer require srmklive/PayPal

4- After installation process, you need to register it in your Laravel application in the config file inside

config/app.php

5- Locate the 'providers' array and add the following: 

'providers' => [
    ...
    Srmklive\PayPal\Providers\PayPalServiceProvider::class
]


6- In the same page locate the 'aliases' array and add the following:

'aliases' => [
    ...
    'PayPal' => Srmklive\PayPal\Facades\PayPal::class
]


7- Once done, navigate to the '.env' file in your project and add your PayPal integration credentials as follows:

PAYPAL_MODE=sandbox
PAYPAL_SANDBOX_API_USERNAME=xxxxx-xxx-xx
PAYPAL_SANDBOX_API_PASSWORD=xxxxxxxxxx
PAYPAL_SANDBOX_API_SECRET=xxxxxxx-xxxxx-xxx
PAYPAL_CURRENCY=USD
PAYPAL_SANDBOX_API_CERTIFICATE=


Next step we need to setup the transactions and actions


1- we need to create a controller to handle the actions in our applications by running the following command

php artisan make:controller PaypalController


2- we need to define the main methods for our application in the controller as follows

 <?php
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use Srmklive\PayPal\Services\PayPal as PayPalClient;

    class PayPalController extends Controller{
        public function createTransaction(){
            return view('transaction');
        }
        
        /**
        * process transaction.
        *
        * @return \Illuminate\Http\Response
        */
        
        public function processTransaction(Request $request){
            $provider = new PayPalClient;
            $provider->setApiCredentials(config('paypal'));
            $paypalToken = $provider->getAccessToken();
    
            $response = $provider->createOrder([
                "intent" => "CAPTURE",
                "application_context" => [
                    "return_url" => route('successTransaction'),
                    "cancel_url" => route('cancelTransaction'),
                ],
                "purchase_units" => [
                    0 => [
                        "amount" => [
                            "currency_code" => "USD",
                            "value" => "1000.00"
                        ]
                    ]
                ]
            ]);

            if (isset($response['id']) && $response['id'] != null) {
                // redirect to approve href
                foreach ($response['links'] as $links) {
                    if ($links['rel'] == 'approve') {
                        return redirect()->away($links['href']);
                    }
                }
    
                return redirect()
                    ->route('createTransaction')
                    ->with('error', 'Something went wrong.');
            } else {
                return redirect()
                    ->route('createTransaction')
                    ->with('error', $response['message'] ?? 'Something went wrong.');
            }
        }

        /**
         * success transaction.
         *
         * @return \Illuminate\Http\Response
         */
        public function successTransaction(Request $request){
            $provider = new PayPalClient;
            $provider->setApiCredentials(config('paypal'));
            $provider->getAccessToken();
            $response = $provider->capturePaymentOrder($request['token']);
    
            if (isset($response['status']) && $response['status'] == 'COMPLETED') {
                return redirect()
                    ->route('createTransaction')
                    ->with('success', 'Transaction complete.');
            } else {
                return redirect()
                    ->route('createTransaction')
                    ->with('error', $response['message'] ?? 'Something went wrong.');
            }
        }
    
        /**
         * cancel transaction.
         *
         * @return \Illuminate\Http\Response
         */
        public function cancelTransaction(Request $request){
            return redirect()
                ->route('createTransaction')
                ->with('error', $response['message'] ?? 'You have canceled the transaction.');
        }
}


3- We need to create a simple view for our application

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
        <title>Pay $1000</title>
        <script src="https://www.paypal.com/sdk/js?client-id={{ env('PAYPAL_SANDBOX_CLIENT_ID') }}"></script>
    </head>

    <body>
        <a class="btn btn-primary m-3" href="{{ route('processTransaction') }}">Pay $1000</a>
        @if(\Session::has('error'))
        <div class="alert alert-danger">{{ \Session::get('error') }}</div>
        {{ \Session::forget('error') }}
        @endif

        @if(\Session::has('success'))
        <div class="alert alert-success">{{ \Session::get('success') }}</div>
        {{ \Session::forget('success') }}
        @endif
    </body>
</html>


Finally we need to create the routes for our application


1- Navigate to the web.php file located in routes/web.php and add the following routes

Route::get('/'                                        ,   function () { return view('transaction');});
Route::get('create-transaction'         ,   'PayPalController@createTransaction')->name('createTransaction');
Route::get('process-transaction'      ,   'PayPalController@processTransaction')->name('processTransaction');
Route::get('success-transaction'      ,   'PayPalController@successTransaction')->name('successTransaction');
Route::get('cancel-transaction'         ,   'PayPalController@cancelTransaction')->name('cancelTransaction');


You can now test your application by running it in your terminal using the following command

php artisan serve
Recent Posts
image

Laravel Livewire

12 Sep, 2024 Abdelrahman Etry
image

Deployment with Envoyer and Laravel

30 Oct, 2023 Abdelrahman Etry
image

Laravel Request Lifecycle

28 Oct, 2023 Abdelrahman Etry
image

Laravel Queues: Everything You Need to Know

28 Oct, 2023 Abdelrahman Etry
image

Laravel Repository Pattern

28 Oct, 2023 Abdelrahman Etry
image

Laravel Packages You Should Know About

26 Oct, 2023 Abdelrahman Etry