InfyOm Blog

latest-post

How to integrate paypal payment gateway with Laravel / PHP ?

In this tutorial we are going to see to integrate the paypal payment gateway with checkout method using the Laravel.

We are going to use package : https://github.com/srmklive/laravel-paypal

Install the package

composer require srmklive/paypal:~3.0

Publish Assets

php artisan vendor:publish --provider "Srmklive\PayPal\Providers\PayPalServiceProvider"

Set Paypal credentials into config/paypal.php

return [
    'mode'    => env('PAYPAL_MODE', 'sandbox'), // Can only be 'sandbox' Or 'live'. 
    'sandbox' => [
        'client_id'         => env('PAYPAL_SANDBOX_CLIENT_ID', ''),
        'client_secret'     => env('PAYPAL_SANDBOX_CLIENT_SECRET', ''),
        'app_id'            => '',
    ],
    ......
    ......
];

Create Routes

routes/web.php

 Route::get('paypal-onboard', [PaypalController::class, 'onBoard'])->name('paypal.init');
 Route::get('paypal-payment-success', [PaypalController::class, 'success'])->name('paypal.success');
 Route::get('paypal-payment-failed', [PaypalController::class, 'failed'])->name('paypal.failed');

Create Controller

app\Http\Controllers\PaypalController.php

setCurrency('EUR');
        $provider->getAccessToken();
        $data = [
            "intent"              => "CAPTURE",
            "purchase_units"      => [
                [
                    "amount" => [
                        "value"         => 100,
                        "currency_code" => getCurrencyCode(),
                    ],
                ],
            ],
            "application_context" => [
                "cancel_url" => route('user.paypal.failed'),
                "return_url" => route('user.paypal.success'),
            ],
        ];

        $order = $provider->createOrder($data);

        return redirect($order['links'][1]['href']);
    }

    public function failed()
    {
        dd('Your payment has been declend. The payment cancelation page goes here!');
    }

    public function success(Request $request)
    {
        $provider = new PayPal();      // To use express checkout.
        $provider->getAccessToken();
        $token = $request->get('token');

        $orderInfo = $provider->showOrderDetails($token);
        $response = $provider->capturePaymentOrder($token);

        dump($orderInfo);
        dd($response);
    }
}

That's it. Enjoy.

September 01, 20221 minuteuserVishal Ribdiya

Posts

Integrate Amazon SNS into PHP Laravel to Send and Receive Messages

We used Amazon SNS into one of our project where we need to receive instant updates to the various different microservices from other microservices. I was not able to find any good article which highlights everything about SNS integration into PHP or Laravel. This can be most confusing who is working with SNS for the first time. so I decided to write one which can help others. Following things are really important before we get started.

  • What exactly SNS is?
  • Where/When you can use it?
  • How does it work?
  • How to integrate it with PHP?

I will try to explain in a little bit brief here about SNS and will focus more on integration and problem that we tried to solve.

1. What exactly AWS SNS is?

AWS SNS stands for Amazon Simple Notification Service. It's a distributed pub/sub messaging system for microservices. Where publishers can publish a message to different subscribers with various kinds of subscribers including SMS, HTTP Endpoints or Webhooks, Amazon SQS, Lambda, Mobile Push etc. We will cover HTTP only subscribers in this post.

Kind of pub/sub where the publisher can publish a message and multiple interested subscribers can subscribe to that. You can read more on the AWS Website Here.

2. When you need AWS SNS?

When your project is distributed into various microservices and if you need to communicate from one or multiple microservices to other microservices then SNS comes to play a really good role.

Our Problem:

In our case, our project contains 3 different systems, where authentication + user management is handled by one central system. But each system has its local users table, where minimal users data is cached for fast data retrieval and table joins. so it doesn't need to query the central user system for each and every query.

If any new user is created by Admin on a central user management system, we need to notify other systems that a new user is created and they update their local users table.

3. How does it work?

Amazon SNS provides topics. You need to create a Topic and then define subscribers either programmatically or manually from Amazon Console. It depends on your use case. If you want to dynamically add subscribers then go that way or if you have some fixed microservices then you can define it from the console directly. This process works as follows:

  1. Create a Topic in AWS Console
  2. Create an HTTP subscriber
  3. SNS will send a SubscriptionConfirmation message to your HTTP Webhook
  4. Your microservice needs to call SubscribeURL
  5. Your subscription will be confirmed

This is the initial setup process. Once this is done. Everytime when any new message is published to Topic, it will call your webhook with that Message.

4. How to integrate it with PHP (Or any other PHP Frameworks like Laravel)?

Amazon has a very good PHP Library for their AWS products. Recently for SNS they have created another light-weight library to handle SNS Messages.

So we will use the following libraries in our integration.

Solution:

I will try to highlight the solution that we used to fix the above-mentioned problem. Check the following diagram:

As you can see, we set up an SNS Topic and created two HTTP/HTTPS subscribers for two different microservices. When an admin user creates a new user into the system, we publish a message to SNS Topic which sends an update to both different microservices.

Now, let's jump into the code.

Publishing a message:

You need to add aws/aws-sdk-php into your project. You can find installation steps on Github Repo. Also, you need to be familiar with AWS authentication process. These things are explained pretty well here. Collect all the things you need in terms of credentials.

  • Key
  • Secret
  • Region
  • Topic ARN

Following code hooked up into our central auth system. You can do this from wherever you want to publish your message. Create a client and then publish a message. You can pass two things into the SNS Message. Subject & Message body. Message body has several options. We will use a pure JSON string way for simplification.

use Aws\Credentials\Credentials; 
use Aws\Sns\SnsClient; 
$client = new SnsClient([     
      'version' => '2010-03-31',     
      'region' => $amazonRegion,    
      'credentials' => new Credentials(         
            $awsKey,         
            $awsSecret     
          ) 
      ]); 
      $subject = 'You got a new SNS Message'; 
      $message = json_encode([
      'message' => 'this is my first message via SNS Topic'
]); 
      $client->publish([    
      'TopicArn' => 'your-sns-topic-arn-here',     
      'Message' => $message,    
      'Subject' => $subject 
]); 

Generally, in our integration, what we did was, we used Subject to specify the type of event. Like Users.create, Users.update, Users.delete and Message used to contain user information. You can customize it based on your use-case.

That's it. Your message is published to a topic.

Handle Incoming SNS Message:

To handle SNS messages we need to integrate aws/aws-php-sns-message-validator into our project.

SNS will call our webhook for multiple kinds of events. It comes with Type param into the message body.

  • SubscriptionConfirmation
  • Message
  • UnsubscriptionConfirmation

Based on the Type parameter, we need to take relevant action. We have used the following code into our microservice webhook handlers.

use Aws\Sns\Message; 
use Aws\Sns\MessageValidator; 

try {     
// Retrieve the message     
$message = Message::fromRawPostData();   

// make validator instance     
$validator = new MessageValidator();   

// Validate the message     
if ($validator->isValid($message)) {         
      if ($message['Type'] == 'SubscriptionConfirmation') {  

// if it's subscription or unsubscribe event then call SubscribeURL             
      file_get_contents($message['SubscribeURL']);         
} elseif ($message['Type'] === 'Notification') {             
      $subject = $message['Subject'];             
      $messageData = json_decode($message['Message']);   

// use $subject and $messageData and take relevant action         
         }
     }
 } catch (Exception $e) {     // Handle exception .
} 

As you can see, based on Type, we are performing different operations.

This way, all our microservice can communicate in a very effective and highly available way to each other. Hope this helps :).

February 23, 20195 minutesauthorMitul Golakiya
Multi Column Search box in Datatables with InfyOm Laravel Generator

UX and UI designs are similar and are often used interchangeably. In fact, these two words have completely different meanings and relay different activities. These two businesses have essentially been around for years, but only recently have been involved in the technology industry, which has been renamed to encourage UI and UX designers.

These two components are essential when it comes to digital products, but the roles are very different. They refer to various aspects of both product development as well as the actual design process. Although UX means "user experience" and UI means "user interface", both jobs cover much more than they seem, which makes learning UX and UI more important at the same time.

User Experience Design (UX)

Originally defined by a cognitive scientist named Don Norman, the term "user experience" was defined before the 21st century. He described UX as "all aspects of the end-user interaction with the company, its services, and its products".

UX can be applied to anything in life that creates an experience. Whether it's a website, a mobile app, a theme park, or a tea party. UX doesn't have to be related to anything in the world of graphic design. User experience is the user's interactions and user "experience" with a product or service.

When it comes to digital products or services, UX is concerned with how a web page, mobile application, or software perceives the user. This may include simplifying the website checkout process or simplifying the application for general use.

uxdesign

You could say that a UX design job requires marketing, design, and project management skills. It is a complex role. Regardless of whether it is being applied to a car, shoe, or website, UX Designer's main goal is to create a simple and pleasant user experience. The product needs to communicate the owner’s goals, while also meeting the needs of the user.

User Interface Design (UI)

UX and user interface (UI) are often compared or grouped in the same job description. These two modes are very different, leaving the UI to be misinterpreted.

Often when looking at job descriptions for UI offerings, you will see a closer description of graphic design. Although UI positions sometimes deal with parts of branding or even frontend development, they do not indicate the original position.

User interface design is a digital term. This is mainly where it differs from UX. A UI is simply an interaction between a user and a digital product or service. This may include a touchpad that allows you to select your coffee from an automatic coffee machine or from your computer screen. It also deals with applications and websites that look and feel how the user interacts with the product.

uidesign

The main purpose of the UI is that the designer will use design tools that enable better communication between the designer and the developer. This in turn will facilitate implementation with developers.

The user interface is an incredibly important element that allows the user to trust the brand. The UI designer is also responsible for relaying the message of the product as well as its research and content into a compelling display or experience.

UX vs. UI

The comparison of UX and UI is almost like apple and orange. If you take the human brain with the right hand representing creativity (usually left-handed individuals), this would be the UI design. If the left side of the brain represents the analysis (usually right-handed individuals), then the left side UX.

ui_ux

UI design is creative, fuzzy, beautiful, and presentable. UX design is, alternatively, the optimization, organization, and structure of the data to be implemented. Without one or the other, the project cannot be completed. To complete the product, you may not lack UX or UI. Despite this, they have completely different roles with different functions.

In general, a UX designer will need to fully map the entire user's journey to solve a specific problem in a product. Much of the UX Designer's job is to understand the user's problems and how to solve them. UX designers work by researching to understand the users they are targeting and what their needs will be.

Alternatively, UI designers consider all aspects of the visual elements. Everything from the first screen to the last screen. The UI designer will make sure the colors are readable. This may include ensuring that a partially blind 65-year-old feels comfortable using the same screen as a normal 13-year-old.

March 04, 20172 minutesauthorMitul Golakiya
24th Sep 2016 InfyOm Laravel Generator Release

Another minor update release for InfyOm Laravel Generator with some enhancement for datatables and few bug fixes.

This release contains datatable duplication script & CSS fixes with partial files support for datatables js and CSS files.

Also, it contains a few bug fixes about save JSON model schema, text area field generation and few more.

You can find full release notes here.

September 30, 20161 minuteauthorMitul Golakiya
How to Display Image in DataTable with yajra laravel-datatables with laravel generator

In this tutorial, we are going to learn how to display image in datatable or add image column to datatable while using yajra/laravel-datatables with infyom laravel generator.

We are continuously getting some questions like how we can achieve something with laravel generator. Recently, we got a question like, how we can display Image in DataTable while using yajra/laravel-datatables with infyom laravel generator. so I thought maybe it can be a requirement for lots of other developers as well and tried myself to find a solution. And then I decided to write a tutorial on that, so other developers can get an idea on that.

so here is the use case, suppose we have a Post model which contains three fields,

  1. Title
  2. Image
  3. Body

Image field contains a full or relative URL of the image which we need to show in a datatable (same as above image).

When you are using InfyOm Laravel Generator it generates PostDataTable.php file for the definition of DataTable. That file contains a function named, getColumns() for the definition of columns of DataTable. Something like following,

 return [     
   'title' => ['name' => 'title', 'data' => 'title'],     
   'image' => ['name' => 'image', 'data' => 'image'],     
   'body'  => ['name' => 'body', 'data' => 'body'] 
]; 

This is a very simple implementation of a DataTable Column definition.

To Display images in DataTable, we need to use the `render` function on the column to display images. You can define your own render function which will return the data that should be rendered in the column. In our case, we want to render an image, so our render function will be something like following,

 return [     
   'title' => ['name' => 'title', 'data' => 'title'],     
   'image' => ['name' => 'image', 'data' => 'image'],     
   'body'  => ['name' => 'body', 'data' => 'body'] 
]; 

If you will look carefully, we are returning, from render function. Where data will be the data from the model. In our case, It will be a URL.
Render function gets the data parameter as a first argument. You can find more information about render function over here.

Above code will generate output something like following,

"name": "image",    
   "data": "image",    
   "render": function (data, type, full, meta) {        
        return <img src=\"" + data + "\" height=\"50\"/>;     
},     
   "title": "Image",    
   "orderable": true,   
   "searchable": true 
}

So, this is how we can display an image in a datatable.

September 30, 20162 minutesauthorMitul Golakiya
Fix datatables_css or datatables_js not found or failed to open stream

Recently, we introduced some breaking updates by which many developers are getting something from the following errors:

  • datatables_css.stub failed to open stream
  • datatables_js.stub failed to open stream
  • View [datatables_css] not found
  • View [datatables_js] not found

Problem:

so, the purpose of this breaking update was, till now when we generate CRUD with datatables we were including datatable scripts into table.blade.php something like the following:

{!! $dataTable->table(['width' => '100%']) !!}
@section('scripts')
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.0.3/css/buttons.dataTables.min.css">
    <script src="https://cdn.datatables.net/buttons/1.0.3/js/dataTables.buttons.min.js"></script>
    <script src="vendor/datatables/buttons.server-side.js"></script>
    {!! $dataTable->scripts() !!}
@endsection

And the main CSS files for datatables were included in the layout file layout/app.blade.php, also some js files were also included in the same folder. Like following,

<!-- Datatables -->
<script src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.11/js/dataTables.bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.1/js/buttons.colVis.min.js"></script>

So the problem that we found was when we want to update the datatables version, we have to go to each file and update them manually. Also, there were some redundant JS and CSS files that were included in both table.blade.php & app.blade.php.

Solution:

As a solution, we decided to move these things to two partial files datatables_css.blade.php & datatables_js.blade.php. Which were published during the publishing layout.

php artisan infyom.publish:layout

so if anyone is getting this error then, run composer update to update your code to the latest commits and then try to run the above command and publish these two files into your layouts folder. As an alternative, you can also create those files manually from the templates and can update your layout file accordingly.

If anyone is still facing issues after performing these steps, then please post your comments below.

September 29, 20162 minutesauthorMitul Golakiya
AdminLTE Templates in mainstream development for Laravel Generator

Today we are going to take another major decision on our template development for Laravel Generator.

It's been around more than 7 months since we launched a new Laravel generator with the ability to select any CSS framework based on developers choice. Even anyone can develop his own templates and use it with a generator.

After these 7 months, now we have around 4 templates repository including Bootstrap Templates, AdminLTE Theme Templates, FlatLab Theme Templates, Metronic Theme Templates with maintaining templates for 3 different version of Laravel including 5.1, 5.2, 5.3. Also, laravel has a rapid release cycle, so it's very hard to maintain 4 packages with 3 different versions supported.

Also, what we realized is, lots of developers are using AdminLTE templates only for their main backend development. We found AdminLTE far better than any other templates. Also, It comes with a better setup, better elements support, regular updates and fits best for back-end Admin Panel development.

So today, we are taking a decision to actively only maintain AdminLTE templates and deprecate all other template development from our end. so we can focus on one template repository and can add more features to it.

It doesn't mean that packages will be deleted from its GitHub repository. It will always be there, but we will be focusing more on AdminLTE templates and all other templates will be more community driven.

September 27, 20161 minuteauthorMitul Golakiya
Introducing InfyOm Labs Blog

Greetings friends. Finally, the InfyOm Labs blog is here.

This is my first blog, so, of course, this is my first post. so I spent quite a huge time reading how to start a blog. Let me take you in the past and give you a brief idea, how all these things were started.

Back in 2015, I just got started with full-time freelancing. It has been almost 2 years, I started working with Laravel. And recently Laravel 5 was just released in Feb 2015. It was a great time when the Laravel community was growing really fast. Lots of developers were accepting Laravel as their primary framework for their mainstream development.

In these 2 years, I worked on a lot of projects where I developed some CRM systems, Analytics Platforms, lots of APIs for mobile applications, etc. And the common problem that I found was, every time when I start a new module or a project, I have to create lots of common classes like, migration, model, controller, crud views files, repository, test cases, etc. And this was a problem for lots of developers.

Then I started to streamline this process and this is how my first laravel-api-generator package was born. In just a few days, it has been started to be used by lots of developers and I got a lot of feature requests.

mitulgolakiya/laravel-api-generator

Almost after a year, I realized that it was missing some modularity architecture where a community can have the option to customize it the way they want to use it. Like customizing CSS framework, generator templates, etc.

so I decided to rewrite a full package with a modular way and then the second version of the package was introduced with a new name InfyOmLabs/laravel-generator as a part of my new company's Labs project with a new website and detailed better documentation.

InfyOmLabs/laravel-generator

InfyOm Labs is a place where we do various experiments and release it as an open-source project for a community.

Again, we got a huge attraction and even this time in a short period of around 6-7 months we completed 1000 stars on our new InfyOmLabs Github Account.

Just after some time, I got comments from a community that there should be some blog where tutorials & videos should be posted to use the generator package for some newbie developers and some more complex features of the package.

Then today, I finally started a blog and will post tutorials and videos for Generator as well as for Laravel & PHP from time to time.

so stay tuned for the videos and tutorials. Also, I would like to hear your ideas about the tutorials and videos that you want to be posted here. Just post a comment about your ideas below.

Looking for the first idea to be submitted. :)

September 24, 20162 minutesauthorMitul Golakiya