Laravel Paypal Integration - Smart button with server-side integration

  •        0
  

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.



You would have seen a lot of blogs for paypal php integration with REST api which is driven completely in the backend. For checkout, paypal provides an easy way to checkout for client side ready-to-use smart button payment. This approach will work only from the frontend, which will not be safe and difficult to reconcile as the backend doesn’t have any information about it. Server side integration with the paypal smart button will help us to reconcile or track the payments even after some issues in the user’s payment journey. In this blog, we have walkthrough the paypal smart button with server side php laravel integration.

Paypal :
PayPal is an online popular payment platform that offers payment gateway related services to individuals and businesses entities. In addition to online payments, PayPal also offers a variety of related services including debit cards for payments, credit card readers for small merchants, and lines of credit. PayPal is one of very secure method of sending payments online.

PayPal API:
PayPal provides a REST API interface to the third party developers to integrate the payment gateway into their app. API caters for making payments on a website, refunding sales, looking up details of transactions, setting up a billing plan, storing a credit card’s history securely, etc. As it is a REST API, it uses HTTP methods to be easily incorporated into the web and mobile apps. Paypal provides different accounts like PayPal Premier, Business or Website Payments Pro account.  We need to give debit card information for creating business accounts but they won't charge any fee for it.  It allows you to accept payments immediately.

Set Up Your Development Environment:

To generate REST API credentials we need client id and secret, it can be generated by creating the sandbox environments. Follow the below steps to create the sandbox environments

  • For online transactions, you need to create a PayPal account at developer.paypal.com
  • Log in to the Developer Dashboard with your PayPal account
  • Under the Dashboard menu, select My Apps & Credentials
  • Make sure you're on the Sandbox tab to get the API credentials you'll use while you're developing code . These details include your secret_key and client_id. After you test and before you go live, switch to the Live tab to get live credentials
  • Under the App Name column, select Default Application, which PayPal creates with a new Developer Dashboard account. Select Create App if you don't see the default app

Render the Smart Payment Buttons:

Include  the PayPal JavaScript sdk with client id in the head of the web page.

<head>
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css">
<script src="https://www.paypal.com/sdk/js?client-id= YOUR_CLIENT_ID "></script>
</head>

Default values for the PayPal JavaScript SDK

To streamline the integration, the PayPal JavaScript SDK uses default values for parameters. Depending on how you want your integration to work, you might want to override these default values by explicitly passing a different value. A few common parameters you might override:

  • currency - The PayPal JavaScript SDK defaults to USD.
  • intent - The PayPal JavaScript SDK defaults to capture, which results in the capturing the funds immediately. If you want to authorize funds immediately but capture the funds later, you have to explicitly pass authorize as the intent for the transaction.

I created the div container with id and used the id to render the PayPal Smart Payment Buttons to a container element on the web page.

<script>
              /* Render the PayPal button into #paypal-button-container */
              paypal.Buttons({          
                  /* Set up the transaction */
                       //..
}       }).render('#paypal-button-container'); </script>

Paypal Buttons javascript code snippet is typical code snippet given by Paypal to render the Paypal smart button. In this code snippet, there are two main listeners

CreateOrder is to create the order id in the paypal system for the payment transactions. After the user pays the amount, onApprove method is invoked where it captures the payment details and responds in the ui screen about the payment status.

<script>
  // Render the PayPal button into #paypal-button-container
    	paypal.Buttons({
          	// Set up the transaction
        	createOrder: function(data, actions) {
            	return actions.order.create({
                	purchase_units: [{
                    	amount: {
                        	value: '88.44'
                    	}
                	}]
            	});
        	},

        	// Finalize the transaction
        	onApprove: function(data, actions) {
            	return actions.order.capture().then(function(orderData) {
                	// Successful capture! For demo purposes:
                	console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
                	var transaction = orderData.purchase_units[0].payments.captures[0];
                	alert('Transaction '+ transaction.status + ': ' + transaction.id 
                                       + '\n\nSee console for all available details');

                	// Replace the above to show a success message within this page, e.g.
                	// const element = document.getElementById('paypal-button-container');
                	// element.innerHTML = '';
                	// element.innerHTML = '<h3>Thank you for your payment!</h3>';
                	// Or go to another URL:  actions.redirect('thank_you.html');
            	});
        	}
    	}).render('#paypal-button-container');
</script>

Payment Workflow:

In my app, the user needs to enter the amount and my app shows the paypal smart button for the user to open the paypal payment form. In the form, user pays the amount from their account and finally land on our app success page.   I created one more sandbox paypal personal account to pay in the app while checkout. Internally I put the flow between client and backend of our app along with the paypal server. The workflow steps are listed below:

  1. Enter the amount and click “paypal” it goes to the createorder method in the smart button javascript sdk.
  2. From createroder javascript function It  goes to our backend paymentcontroller->createorder method and which in turn calls the paypal server to create order and comes back to the paypal button create order.
  3. After the create order javascript method returns the orderid, javascript sdk will take us to the paypal login page, where we enter the personal paypal account to login. It will redirect us to the paypal payment page,for the user to pay.  
  4. Once a user pays, javascript sdk takes it to the Payal server.
  5. Paypal server approves the payment and then it calls the onapprove listener of javascript sdk.
  6. In this on approve javascript sdk method, it needs to call the payment controller->getstatus method to confirm the payment happened successfully by capturing the payment.
  7. Payment controller captures payments by invoking paypal capture payment rest api with the paypal payment id.
  8. It then returns back the payment capture details.
  9. If the payment details are successful, then show the payment success page. If it got cancelled, capture payment returns status failure, to show the order cancelled page.

The below flow diagram will make you clearer understand of paypal transaction:

 

I have made a simple order checkout for the user to enter the amount with the paypal smart button. 

 

Create order:

In the javascript sdk, I am calling the backend paymentController using the  backend api url -  payment/paypal/createTransaction. 

    return fetch('/payment/paypal/createTransaction', {
                          method: 'post',
                          headers: {      
                          },
                          body:  JSON.stringify({})                             
                    }

In paymentcontroller, createOrder method we do the POST paypal request to /v2/checkout/orders.


An order represents a payment between two or more parties.The Orders API to create, update, retrieve, authorize, and capture orders are available. To make REST API calls, include the bearer token in the header with the Bearer authentication scheme. The value is Bearer <Access-Token> or Basic <client_id:secret>. Access token is generated in the construct method of the class using the client and client secret which we got as part of the sandbox paypal app sdk. This token will be stored in the class member.

public function __construct()
    {
  /** PayPal api context **/
        $paypal_conf = \Config::get('paypal');   
        // Creating an environment
        $clientId = $paypal_conf['client_id'];
        $clientSecret = $paypal_conf['secret'];
        $this->_paypalApiUrl = $paypal_conf['api_url'];
        $params=['name'=>$clientId, 'surname'=>$clientSecret];
        $ch = curl_init($this->_paypalApiUrl."v1/oauth2/token");
        curl_setopt($ch, CURLOPT_POST, 1);
        $headers = array(
            'Content-Type: application/json',
            'Accept: application/json',
            'Authorization: Basic '. base64_encode($clientId.":".$clientSecret) 
        );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, rawurldecode(http_build_query(array(
            'grant_type' => 'client_credentials'
          ))));
          $this->_token_response = json_decode(curl_exec($ch));
          $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
          Log::info('token generation status: '.$status.'response'.gettype($this->_token_response));      
    }

Headers are set with content type and bearer token and in body, we have to pass the order number and amount. A successful request returns the HTTP 201 Created status code and a JSON response body that includes by default a minimal response with the ID, status, and HATEOAS links

public function payWithpaypal(Request $request)
    {
        $paypal_conf = \Config::get('paypal');
        $paypalApiUrl = $paypal_conf['api_url'];
        $input = $request->all();
        $order_no = $input['order_no'];
        $amount = $input['amount'];
        $ch = curl_init($this->_paypalApiUrl."v2/checkout/orders");
        curl_setopt($ch, CURLOPT_POST, 1);
        $headers = array(
            'Content-Type: application/json',
            'Accept: application/json',
            'Authorization: Bearer '. $this->_token_response->access_token
        );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, '{
            "intent": "CAPTURE",
            "purchase_units": [
              {
                "amount": {
                  "currency_code": "'.$paypal_conf['currency_type'].'",
                  "value": "'.$amount.'"
                }
              }
            ]
          }');
          $_order_response = json_decode(curl_exec($ch), true);
          $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
          Log::info('order generation response: '.$status.'response'.gettype($_order_response));
        return response()->json($_order_response);
    }

Once the rest api is executed, the create order response has been sent to the frontend fetch call where it takes the order id from the response and then returns back to createOrder javascript sdk method . 

Then it takes the user to the paypal login followed by the payment screen so that the user pays the amount. Below screen is where the end user pay the amount and finally lands on the payment status page. 

 Once paid, it calls the onApprove javascript sdk method where we need to call application backend API to capture the payment using the current system order id, with paypal order id and facilitator access token in the request body.

// Finalize the transaction
         onApprove: function(data, actions) {
                console.log("on approve", data);
                
                return fetch('/payment/paypal/capture/{{$order_no}}', {
                    method: 'post',
                    headers: {
                          
                      },
                    body: JSON.stringify(data),
                }).then(function(res) {
                    return res.json();
                })
      }

Capture payment for an order:

API:   POST   /v2/checkout/orders/{id}/capture

public function getPaymentStatus(Request $request)
    {
          $input = $request->all();
          $payerId = $request->payerID; 
          $paypalOrderId = $request->orderID; 
          $facilitorAccessToken =  $request->facilitatorAccessToken;
          $ch = curl_init($this->_paypalApiUrl."v2/checkout/orders/".$paypalOrderId."/capture");
          
          curl_setopt($ch, CURLOPT_POST, 1);
        
        $headers = array(
            'Content-Type: application/json',
            'Accept: application/json',
            'Authorization: Bearer '. $this->_token_response->access_token,
            'PayPal-Request-Id:'.$facilitorAccessToken
        );

        log::info('order_no'.$paypalOrderId.'facilitortoken'.$facilitorAccessToken);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        $_capture_response = json_decode(curl_exec($ch), true, 512);
        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
          
        Log::info('order capture data : '.$status.'for'.$facilitorAccessToken.'response'
                         .gettype($_capture_response['purchase_units'][0]['payments']['captures']));
  
        return response()->json($_capture_response);
    }

In this method, we pass the request body to  Paypal capture rest api method. Details are available in the paypal documentation link It requires paypal order id and facilitor acesstoken to capture the paypal payment status. Captured response has been sent to the frontend, where it checks for success and then returns the response status. It checks the status of the response for authorized and then returns to the order success screen. If it fails, then the order failure screen will be shown.

Screen shot of the successful payment and payment failures are shown below. It will be shown on success and failure scenarios respectively.

 

Add routes:

In the case of payments, there are three routes, add the following routes to routes/web.php file. These are Payments, Payment success, and cancellation.

Route::post('/payment/paypal/createTransaction', 'PaymentController@payWithpaypal');
Route::post('/payment/paypal/capture/{orderid}', 'PaymentController@getPaymentStatus');
Route::get('/suceess/{order_no}', function (){
    return view('suceess');
});
Route::get('/', function (){
    return view('index');
});

Finally paypal payment with server side integration is completed and the completed code is available in our github repository

 


   

DevGroves Technologies is a IT consulting and services start-up company which is predominately to web technologies catering to static website, workflow based CRM websites, e-commerce websites and reporting websites tailoring to the customer needs. We also support open source community by writing blogs about how, why and where it need to be used for.

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter



Related Articles

Laravel eCommerce Platform - Bagisto

  • ecommerce shopping laravel php

Nowadays on the web, Shopping is one of the most popular activities. Everyone can shop at their recess, anytime from anywhere. However, this is interesting that anyone can have their pages built to display their favourite products and services.

Read More


ONLYOFFICE Document Server, an online office app for Nextcloud and ownCloud

  • office office-suite word spreadsheet

ONLYOFFICE Document Server is a free collaborative online office suite including viewers and editors for texts, spreadsheets and presentations, fully compatible with Office Open XML formats (.docx, .xlsx, .pptx). This article provides you the overview of ONLYOFFICE Document Server, its features, installation and integration with Nextcloud and ownCloud.

Read More


Push Notifications using Angular

  • angular push-notifications notifications

Notifications is a message pushed to user's device passively. Browser supports notifications and push API that allows to send message asynchronously to the user. Messages are sent with the help of service workers, it runs as background tasks to receive and relay the messages to the desktop if the application is not opened. It uses web push protocol to register the server and send message to the application. Once user opt-in for the updates, it is effective way of re-engaging users with customized content.

Read More


Build Consulting Website using Next.js

  • react nextjs website-development ssr

One of the popular web framework for building Single page application (SPA) or static site is React library. Application built with React packages will be rendered completely on the client side browser. If you want to reduce the load on client side browser, we need to pre-render the pages in server (Serer side rendering) and serve it to the client. So the client loads the page like simple html page. Also if the pages are rendered from server then search engine will be able to fetch and extract the pages. To do SSR for React, the best abstraction framework is Next.js. In this blog, we will explain how to build a simple consulting website using NextJS.

Read More


React Media Lightbox

  • lightbox gallery react audio video

Lightbox is a popular and widely used concept for showing the gallery of media files. It is a very impressive approach for the end user to glance through media files. Media files like audio or video will load the html audio or video controls.

Read More



PrestaShop - A feature rich Open Source eCommerce solution

PrestaShop is an Open Source eCommerce Solution. It comes complete with over 310 features that have been carefully developed to assist business owners in increasing sales with virtually little effort. It is being used in more than 150,000 online stores.

Read More


Desktop Apps using Electron JS with centralized data control

  • electronjs couchdb pouchdb desktop-app

When there is a requirement for having local storage for the desktop application context and data needs to be synchronized to central database, we can think of Electron with PouchDB having CouchDB stack. Electron can be used for cross-platform desktop apps with pouch db as local storage. It can sync those data to centralized database CouchDB seamlessly so any point desktop apps can recover or persist the data. In this article, we will go through of creation of desktop apps with ElectronJS, PouchDB and show the sync happens seamlessly with remote CouchDB.

Read More


How Bitcoin works? A simple introduction.

Bitcoin is an open source digital currency which could be transferred in a P2P payment network. It is decentralized and it is not controlled by any central authority or banks. It is transferred from person to person and no authority will be aware of your transaction. Its quite different from PayPal or Banks.

Read More


WebSocket implementation with Spring Boot

  • websocket web-sockets spring-boot java

Spring Boot is a microservice-based Java framework used to create web application. WebSocket API is an advanced technology that provides full-duplex communication channels over a single TCP connection. This article explains about how to implement WebSocket using Spring Boot.

Read More


Getting Started on Angular 7

  • angular ui-ux front-end-framework

Angular is a platform for building responsive web, native desktop and native mobile applications. Angular client applications are built using HTML, CSS and Typescript. Typescript is a typed superset of Javascript that compiles to plain Javascript. Angular core and optional modules are built using Typescript. Code has been licensed as MIT License.

Read More


Build Simple Ecommerce site using React and Jotai

  • ecommerce react jotai

Retail Ecommerce website can be created quickly with React. It can be created using React, Bootstrap, React DOM and Jotai. Data flow within the commerce site is done using Jotai in a light-weight manner. The main workflow of showing all the items in the gallery to user and user adding to the cart will be done as part of this blog.

Read More


Getting Started With Django Python Web Framework

  • django python web-framework

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. It is pre-loaded with user authentication, content administration, site maps, RSS feeds and many more tasks. Security features provided are cross site scripting (XSS) protection, cross site request forgery protection, SQL injection protection, click-jacking protection, host header validation, session security and so on. It also provides in built caching framework.

Read More


Angular Security - Authentication Service

  • angular security authentication jwt

Angular is a framework for creating single page web application. Angular facilitates the security feature and protection mechanism. It provides frameworks by verifying all the routing urls with security authguard interface to validate and verify the user and its permissions.

Read More


Electron JS- Native capabilities

  • electronjs electron desktop-app

Electron is an open source library to build native applications which also works as cross-platform desktop applications. It provision operating system functionalities with help of node integration. In this article, we will go through how to access the Operating System variables, Inter system communication, System dialog, Access files, folders also their statistics.

Read More


Generate PDF from Javascript using jsPDF

  • pdf jspdf javascript

We show lot of data in our web applications, it will be awesome if we quickly download specific part of PDF rather than printing it. It will be easy to share for different stakeholders and also for focused meetings. In web application development, download to PDF means, we need to develop backend api specifically and then link it in frontend which takes longer development cylce. Instead it would be really great, if there is way to download what we see in the user interface quickly with few lines of Javascript, similar to export options in word processing application.

Read More


React Media LightBox - Part 2

  • react lightbox gallery media

In this blog, we will bring the essential features zoom control, download, fullscreen to enhance the view experience of the media items. Lightbox components provide options for captioning the media items as well. Brought all the features only with material design and there are no dependencies required for the functionalities of the media lightbox.

Read More


8 Reasons Why Python Scores Over PHP for Web Development

  • python php web-development

PHP, the general-purpose scripting language has been used since decades for socket programming and web development. But in recent times, Python has become the most sought after programming language. This all-purpose programming language is attracting more developers in the industry owing to its highly dynamic and extensible nature. Let's see how Python is winning over age-old PHP.

Read More


Activiti - Open Source Business Automation

  • business-automation business bpm

Activiti Cloud is the first Cloud Native BPM framework built to provide a scalable and transparent solution for BPM implementations in cloud environments. The BPM discipline was created to provide a better understanding of how organisations do their work and how this work can be improved in an iterative fashion.

Read More


Exonum Blockchain Framework by the Bitfury Group

  • blockchain bitcoin hyperledger blockchain-framework

Exonum is an extensible open source blockchain framework for building private blockchains which offers outstanding performance, data security, as well as fault tolerance. The framework does not include any business logic, instead, you can develop and add the services that meet your specific needs. Exonum can be used to build various solutions from a document registry to a DevOps facilitation system.

Read More


Data Fetching and Form Building using NextJS

  • nextjs data-fetching form-handling

Next.js is one of the easy-to-learn frameworks for server-side pre-render pages for client-side web applications. In this blog, we will see how we can fetch data from API and make it pre-render pages. Also, let's see how forms work in Next.js and collect the data without maintaining the database.

Read More







We have large collection of open source products. Follow the tags from Tag Cloud >>


Open source products are scattered around the web. Please provide information about the open source projects you own / you use. Add Projects.