laravel paypal integration Tutorial from Scratch for Beginners

Today, We want to share with you laravel paypal integration.In this post we will show you PayPal standard payment gateway integration in Laravel PHP, hear for Integrate Laravel Paypal Payment Gateway For Fast Online Payments we will give you demo and example for implement.In this post, we will learn about Paypal payment gateway integration in Laravel 5|6|7 step by step with an example.

laravel paypal integration

There are the Following The simple About How to integrate PayPal payment gateway in Laravel Full Information With Example and source code.

As I will cover this Post with live Working example to develop laravel payoneer integration, so the laravel paypal invoice is used for this example is following below.

we are paypal/rest-api-sdk-php package.

Phase:1 Make a new Project

integrate PayPal Express Checkout

laravel new paypal

Phase:2 install a package omnipay

install the package omnipay via the composer.

composer require league/omnipay omnipay/paypal

And generate the default layout of Laravel using the flowing command.

php artisan make:auth

Phase: 3 Make some routes

app/routes/web.php

Now add new routes for the PayPal integration under app/routes/web.php

Route::get('/paypal/{supply?}','[email protected]')->name('supply.paypal');
Route::post('/checkout/payment/{supply}/paypal','[email protected]')->name('checkout.payment.paypal');
Route::get('/paypal/checkout/{supply}/completed','[email protected]')->name('paypal.checkout.completed');
Route::get('/paypal/checkout/{supply}/cancelled','[email protected]')->name('paypal.checkout.cancelled');
Route::post('/webhook/paypal/{supply?}/{env?}','[email protected]')->name('webhook.paypal.ipn');
Route::get('payment-completed/{supply}','[email protected]')->name('paymentCompleted');

PHP Laravel 6 PayPal Payment Gateway API Integration Step By Step

laravel paypal integration
laravel paypal integration

Phase: 4 Make Order table.

Make a migration, modal, and Controller for an order using this command.

php artisan make:model Order -mcr

Adding the required models for this implementation.

app/Order.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    const PAYMENT_COMPLETED = 1;
    const PAYMENT_PENDING = 0;

    /**
     * @var string
     */
    protected $table = 'supplys';

    /**
     * @var array
     */
    protected $dates = ['deleted_at'];

    /**
     * @var array
     */
    protected $fillable = ['money_history_id', 'amount', 'payment_status'];
}

Phase: 5 Update migration table

We already generated a new migration table for order, now add some columns.

Read Also:  convert string to array python

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTableOrders extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('supplys', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('member_id');
            $table->integer('service_id');
            $table->string('money_history_id')->nullable();
            $table->float('amount')->unsigned()->nullable();
            $table->integer('payment_status')->unsigned()->default(0);
            $table->timestamps();
            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('supplys');
    }
}

Phase:8 Make new Migration table Service

Using this flowing command.

php artisan make:model Service -mcr

Now, add some columns in Service table.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateServicesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('services', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('amount');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('services');
    }
}

then use this flowing command to migrate this service table.

php artisan migrate

Phase: 9 Add helper

Adding a new helper class for generating gateway object as well as routes to interact with PayPal API.

app/PayPal.php

<?php

namespace App;

use Omnipay\Omnipay;

/**
 * Class PayPal
 * @package App
 */
class PayPal
{
    /**
     * @return mixed
     */
    public function gateway()
    {
        $gateway = Omnipay::create('PayPal_Express');

        $gateway->setUsername(config('services.paypal.username'));
        $gateway->setPassword(config('services.paypal.password'));
        $gateway->setSignature(config('services.paypal.signature'));
        $gateway->setTestMode(config('services.paypal.sandbox'));

        return $gateway;
    }

    /**
     * @param array $arguments
     * @return mixed
     */
    public function purchase(array $arguments)
    {
        $response = $this->gateway()
            ->purchase($arguments)
            ->send();

        return $response;
    }

    /**
     * @param array $arguments
     */
    public function complete(array $arguments)
    {
        $response = $this->gateway()
            ->completePurchase($arguments)
            ->send();

        return $response;
    }

    /**
     * @param $amount
     */
    public function formatAmount($amount)
    {
        return number_format($amount, 2, '.', '');
    }

    /**
     * @param $supply
     */
    public function getCancelUrl($supply)
    {
        return route('paypal.checkout.cancelled', $supply->id);
    }

    /**
     * @param $supply
     */
    public function getReturnUrl($supply)
    {
        return route('paypal.checkout.completed', $supply->id);
    }

    /**
     * @param $supply
     */
    public function getNotifyUrl($supply)
    {
        $env = config('services.paypal.sandbox') ? "sandbox" : "live";

        return route('webhook.paypal.ipn', [$supply->id, $env]);
    }
}

Phase: 10 updates config/service.php

Laravel comes with a config file config/service.php to be used with third-party API services. For this implementation add following credentials under the same file as below.

Read Also:  Install Android 8.1 Oreo for Raspberry Pi 3

config/service.php

'paypal' => [
        'username' => env('PAYPAL_USERNAME'),
        'password' => env('PAYPAL_PASSWORD'),
        'signature' => env('PAYPAL_SIGNATURE'),
        'sandbox' => env('PAYPAL_SANDBOX'),
    ],

Phase:11 Make a new controller

To Make a new controller use this flowing command.

php artisan make:controller PaymentGatewayController

update PaymentGatewayController.php

<?php

namespace App\Http\Controllers;

use App\Order;
use App\PayPal;
use App\Service;
use App\User;
use Illuminate\Http\Request;

/**
 * Class PaymentGatewayController
 * @package App\Http\Controllers
 */
class PaymentGatewayController extends Controller
{
    
    
    public function form(Request $request, $service_id)
    {

        $service = Service::findOrFail($service_id);


       
        $supply = new Order;
        $money_history_id = rand(10000000,99999999);
        $supply->member_id = 1 ;  //member id
        $supply->money_history_id = $money_history_id;
        $supply->service_id    = $service->id;
        $supply->amount    = $service->amount;
        $supply->save();

        // the above supply is just for example.
        return view('form', compact('service','money_history_id'));
    }

    /**
     * @param $supply_id
     * @param Request $request
     */
    public function checkout($money_history_id, Request $request)
    {
            $supply = Order::where('money_history_id', decrypt($money_history_id))->first();

            $paypal = new PayPal;

            $response = $paypal->purchase([
                'amount' => $paypal->formatAmount($supply->amount),
                'transactionId' => $supply->money_history_id,
                'currency' => 'USD',
                'cancelUrl' => $paypal->getCancelUrl($supply),
                'returnUrl' => $paypal->getReturnUrl($supply),
            ]);

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

            return redirect()->back()->with([
                 'message' => $response->getMessage(),
                
            ]);
    }

    /**
     * @param $supply_id
     * @param Request $request
     * @return mixed
     */
    public function completed($supply_id, Request $request)
    {

        $supply = Order::findOrFail($supply_id);

        $paypal = new PayPal;

        $response = $paypal->complete([
            'amount' => $paypal->formatAmount($supply->amount),
            'transactionId' => $supply->money_history_id,
            'currency' => 'USD',
            'cancelUrl' => $paypal->getCancelUrl($supply),
            'returnUrl' => $paypal->getReturnUrl($supply),
            'notifyUrl' => $paypal->getNotifyUrl($supply),
        ]);

        if ($response->isSuccessful()) {
            $supply->update([
                'money_history_id' => $response->getTransactionReference(),
                'payment_status' => Order::PAYMENT_COMPLETED,
            ]);

            return redirect()->route('paymentCompleted', encrypt($supply_id))->with([
                'message' => 'You recent payment is sucessful with reference code ' . $response->getTransactionReference(),
            ]);
        }

        return redirect()->back()->with([
            'message' => $response->getMessage(),
        ]);

    }
    public function paymentCompleted($supply)
    {
        # code...
        return "Thanks! payment completed";
    }

    /**
     * @param $supply_id
     */
    public function cancelled($supply_id)
    {
        $supply = Order::findOrFail($supply_id);

        return redirect()->route('supply.paypal', encrypt($supply_id))->with([
            'message' => 'You have cancelled your recent PayPal payment !',
        ]);
    }

        /**
     * @param $supply_id
     * @param $env
     * @param Request $request
     */
    public function webhook($supply_id, $env, Request $request)
    {
        // to do with new release of sudiptpa/paypal-ipn v3.0 (under development)
    }
    
}

Phase:12 Make the view

An Last we Make two views one for send amount to Paypal as well as one for land after payment

Read Also:  Vuejs color picker Plugins With Examples

form.blade.php

@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="gateway--info">
            <div class="gateway--desc">
                @if(session()->has('message'))
                    <p class="message">
                        {{ session('message') }}
                    </p>
                @endif
                <div class="row">
                    <div class="col">
                        <img src="{{ asset('images/paypal.png') }}" class="img-responsive gateway__img">
                    </div>
                    <div class="col">
                        <img src="{{ asset('images/laravel.png') }}" class="img-responsive gateway__img">
                    </div>
                </div>
                <p><strong>Order Overview !</strong></p>
                <hr>
                <p>Item : Yearly Subscription cost !</p>
                <p>Amount : ${{ $service->amount }}</p>
                <hr>
            </div>
            <div class="gateway--paypal">
                <form method="POST" action="{{ route('checkout.payment.paypal', ['money_history_id' => encrypt($money_history_id)]) }}">
                    {{ csrf_field() }}
                    <button class="btn btn-pay">
                        <i class="fa fa-paypal" aria-hidden="true"></i> Pay with PayPal
                    </button>
                </form>
            </div>
        </div>
    </div>
@stop

Phase:13 Update .env file with PayPal credential details.

PAYPAL_USERNAME = [email protected]
PAYPAL_PASSWORD = abcDXXX_478jkd8998
PAYPAL_SIGNATURE = your_signature
PAYPAL_SANDBOX  = sandbox   // name

Web Programming Tutorials Example with Demo

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about laravel paytm integration.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.