DEV Community

Cover image for PayPal Integration Laravel
Salman Abbas (سلیمان)
Salman Abbas (سلیمان)

Posted on

PayPal Integration Laravel

You can follow this video:

https://www.youtube.com/watch?v=GVrbVXLfFzw&t

Step # 01 :

Create PayPal account:

https://developer.paypal.com/
Enter fullscreen mode Exit fullscreen mode

By creating an account there will be two options as shown in the video. One is the sandbox account option and the other one is the Live account option. If you want to test or working in a development then you should create sandbox account and if you are working on a live server then you will use live option.

Image description

Now after creating new app, you can see your client id and secrect id.

Image description

Step # 02 :

Now add these above client id and secrect id in your .env file.

Image description

Step # 03 :

Now let's add a model and migration and connect to your database:

php artisan make:model Payment -m
Enter fullscreen mode Exit fullscreen mode

        Schema::create('payments', function (Blueprint $table) {
            $table->id();
            $table->string('payment_id');
            $table->string('payer_id');
            $table->string('payer_email');
            $table->float('amount', 10, 2);
            $table->string('currency');
            $table->string('payment_status');
            $table->timestamps();
        });
Enter fullscreen mode Exit fullscreen mode
php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Step # 04 :

Now let's install a package that we are going to use to integrate PayPal api into our application:

composer require league/omnipay omnipay/paypal

Step # 05 :

Now let's make a controller :

php artisan make:controller PaymentController
Enter fullscreen mode Exit fullscreen mode

This will be our controller code :


<?php

namespace App\Http\Controllers;

use App\Models\Payment;
use Illuminate\Http\Request;
use Omnipay\Omnipay;

class PaymentController extends Controller
{
    private $gateway;

    public function __construct() {
        $this->gateway = Omnipay::create('PayPal_Rest');
        $this->gateway->setClientId(env('PAYPAL_CLIENT_ID'));
        $this->gateway->setSecret(env('PAYPAL_CLIENT_SECRET'));
        $this->gateway->setTestMode(true);
    }

    public function pay(Request $request)
    {
        try {

            $response = $this->gateway->purchase(array(
                'amount' => $request->amount,
                'currency' => env('PAYPAL_CURRENCY'),
                'returnUrl' => url('success'),
                'cancelUrl' => url('error')
            ))->send();

            if ($response->isRedirect()) {
                $response->redirect();
            }
            else{
                return $response->getMessage();
            }

        } catch (\Throwable $th) {
            return $th->getMessage();
        }
    }

    public function success(Request $request)
    {
        if ($request->input('paymentId') && $request->input('PayerID')) {
            $transaction = $this->gateway->completePurchase(array(
                'payer_id' => $request->input('PayerID'),
                'transactionReference' => $request->input('paymentId')
            ));

            $response = $transaction->send();

            if ($response->isSuccessful()) {

                $arr = $response->getData();

                $payment = new Payment();
                $payment->payment_id = $arr['id'];
                $payment->payer_id = $arr['payer']['payer_info']['payer_id'];
                $payment->payer_email = $arr['payer']['payer_info']['email'];
                $payment->amount = $arr['transactions'][0]['amount']['total'];
                $payment->currency = env('PAYPAL_CURRENCY');
                $payment->payment_status = $arr['state'];

                $payment->save();

                return "Payment is Successfull. Your Transaction Id is : " . $arr['id'];

            }
            else{
                return $response->getMessage();
            }
        }
        else{
            return 'Payment declined!!';
        }
    }

    public function error()
    {
        return 'User declined the payment!';   
    }

}
Enter fullscreen mode Exit fullscreen mode

Step # 06 :

Now let's make make routes :


Route::get('/', [HomeController::class, 'index']);
Route::post('pay', [PaymentController::class, 'pay'])->name('payment');
Route::get('success', [PaymentController::class, 'success']);
Route::get('error', [PaymentController::class, 'error']);
Enter fullscreen mode Exit fullscreen mode

You are good to go, now you can easily use the route in your checkout form.

I hope it will be helpful!

Comment below if you face any issue.

Thanks!

Top comments (3)

Collapse
 
howtomakeaturn profile image
尤川豪

you saved my day. thank you very much!

Collapse
 
vijay706 profile image
Akhil Vijay • Edited

It works fine, I have a question, Its getting an ID only from

'transactionReference' => $request->input('paymentId')

Where can i find the product items in the $response ?
please resopnd.

Collapse
 
adrianooo30 profile image
adrianooo30

Thanks.