Blog Detail

10

Aug
Paypal Integration in Laravel with Braintree cover image

Paypal Integration in Laravel with Braintree

Braintree is a full-stack payments platform that makes it easy to accept payments in your app or website. It is a payment gateway service that assists you to store your client's credit card information and process your client's credit card charges for the service you provide. Braintree is part of Paypal and the most secure and stable payment method nowadays. It allows both Mobile and web payment.

In this article, I will demonstrate that how we can easily integrate Braintree with Laravel. First, you've to create a Braintree Sandbox account by following this link.

Installation

Next, you've to install Braintree in your laravel project via composer:

composer require braintree/braintree_php​

It will install the required packages for the Braintree gateway. Then you've to append these few lines in your .env file. So open the .env file and add these lines.

BTREE_ENVIRONMENT=
BTREE_MERCHANT_ID=
BTREE_PUBLIC_KEY=
BTREE_PRIVATE_KEY=

Go to the Braintree sandbox page and log in to your account. After account login, just move to Settings -> API keys and there you can get the API keys.

Now, you've to add the API keys to your .env file.

BRAINTREE_ENV=sandbox
BRAINTREE_MERCHANT_ID=**************
BRAINTREE_PUBLIC_KEY=***************
BRAINTREE_PRIVATE_KEY=**************

Braintree configuration

Next, Go to the App/Providers/AppServiceProvider.php, and set up Braintree in Laravel by adding the following code to your boot() method.

\Braintree_Configuration::environment(env(‘BRAINTREE_ENV’));
\Braintree_Configuration::merchantId(env(‘BRAINTREE_MERCHANT_ID’));
\Braintree_Configuration::publicKey(env(‘BRAINTREE_PUBLIC_KEY’));
\Braintree_Configuration::privateKey(env(‘BRAINTREE_PRIVATE_KEY’));

Controller and Routes

After configuration, you've to make a controller by running this command:

php artisan make:controller PaymentController

Now, Go to routes/web.php and add a new route for processing the payment.

Route::get('/payment/process', 'PaymentController@process')->name('payment.process');

Create Form

Next, create a file called payment.blade.php in resources/views for the demo. Then you've to add the following code to it.

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Braintree-Demo</title>
    <script  src="https://code.jquery.com/jquery-3.6.0.slim.min.js"  integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI="  crossorigin="anonymous"></script>
    <script src="https://js.braintreegateway.com/web/dropin/1.31.1/js/dropin.min.js"></script>

</head>
<body>
  <div class="container">
     <div class="row">
       <div class="col-md-6 col-md-offset-3">
         <div id="dropin-container"></div>
         <button id="submit-button">Submit</button>
       </div>
     </div>
  </div>

  <script>
    var button = document.querySelector('#submit-button');

    braintree.dropin.create({
      authorization: "{{ Braintree_ClientToken::generate() }}",
      container: '#dropin-container'
    }, function (createErr, instance) {
      button.addEventListener('click', function () {
        instance.requestPaymentMethod(function (err, payload) {
          $.get('{{ route('payment.process') }}', {payload}, function (response) {
            if (response.success) {
              alert('Payment successfull!');
            } else {
              alert('Payment failed');
            }
          }, 'json');
        });
      });
    });
  </script>
</body>
</html>

If you've entered the code correctly and the setup was successful, then a form will appear in the browser, where you can enter your credit card information.

Processing Payment

Next, Go to app/Http/Controllers and open your PaymentController. Now, create the process() method in this controller. Add the following code in the method.

use Braintree_Transaction;
public function process(Request $request)
{
    $payload = $request->input('payload', false);
    $nonce = $payload['nonce'];

    $status = Braintree_Transaction::sale([
    'amount' => '50.00',
    'paymentMethodNonce' => $nonce,
    'options' => [
        'submitForSettlement' => True
    ]
    ]);

    return response()->json($status);
}

Now our payment system is created! Now, open the blade file in your browser and enter some fake credit card data:

  • Braintree sandbox credit card number is 4111 1111 1111 1111
  • The expiration date can be whatever you want.

Then click on the Submit button, and it will make the payment. Our front-end part of the application will send a request to Braintree and ask for a payment method and a “nonce” that we will utilize to execute the payment in our controller. After getting a response from Braintree, a request to our application’s backend will be sent with the information provided by Braintree, and try to make a payment. PaymentController will return the status of the payment, and if your payment is successful then an informing alert will appear in the browser.

This is the simple Braintree Paypal payment process. I hope you like it. For more information, you can view the official documentation of Braintree and its source code on Github.

Published at : 10-08-2021

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

web application development client
web application development client
web application development client
web application development client
web application development client

Launch project