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

[Best-Practices] Securing NodeJS Express APIs with JWT Authentication and custom Authorization

Overview


A Node.js library for use as Express middleware to secure endpoints with JWTs. The implementation uses a JWT endpoint of an Authorization Server to get the keys required for verification of the token signature. There is also an example Express app that shows how to use the library.

Package: https://www.npmjs.com/package/jsonwebtoken

Using the JSON web token, we can simply authenticate each and every request on our server. As a standard / best practice, we can use JWT (JSON web token) middleware to validate all requests.

JWT Middleware


  const jwt = require('jsonwebtoken')

  module.exports = (expectedRole) => (req, res, next) => {

  const authHeader = req.get('Authorization')
  if (!authHeader) {
    const error = new Error('Not authenticated.')
    error.statusCode = 401
    throw error
  }

  const token = authHeader.split(' ')[1]
  if (!token) {
    const error = new Error('Not authenticated.')
    error.statusCode = 401
    throw error
  }

  let decodedToken
  try {
    decodedToken = jwt.verify(token, process.env.SECRET_KEY)
  } catch (error) {
    error.statusCode = 401
    throw error
  }

  if (!decodedToken) {
    const error = new Error('Not authenticated.')
    error.statusCode = 401
    throw error
  }

  const role = decodedToken.role

  const authorised = expectedRole.includes(role)
  if (!authorised) {
    const error = new Error('Not authorised.')
    error.statusCode = 401
    throw error
  }

  req.user = decodedToken
  next()
}

This middleware has been prepared and exported. Therefore, we need to include it in our routes file and pass it to the expected role, so in our JWT middleware, we will validate the request with the JWT token, then verify that the user has access to an expected role (this role saved in the database) to this endpoint.

Routes File


 const express = require('express')
 const router = express.Router()

 const auth = require('./auth/index')
 const admin = require('./admin/index')
 const common = require('./common/index')
 const authorize = require('../middleware/jwtAuth')

 router.use('/auth', auth)
 router.use('/admin', authorize(['admin']), admin)
 router.use('/common', authorize(['admin', 'user']), common)

 module.exports = router 

Now that we have set up our authentication and authorization middleware in our routes, we are passing the required role to access these routes. These roles will be checked against our user role.

Our middleware simply next() the request if the user has a valid JWT token and is authorized to access this route, otherwise, it will throw the global error that is caught by the express global error handler.

November 08, 20222 minutesauthorSmit Gajera
Useful Figma Tricks to Work Faster

Whether you're new to Figma or an expert user, you've probably realised that there are always more effective methods to go about your task. Speaking of effective work, here are several strategies you may or may not be aware of that might increase your productivity on Figma, or at the very least make navigating less stressful.

1. Math in Fields

Spend less time trying to manually resize items to get the right measurement. You may employ percentages like 100%. Math operations like plus (+), minus (-), multiplication (*), and division (/) are also possible.

2. Adjust Opacity Quickly

To easily adjust the opacity of shapes or other objects, all you have to do is click on it and choose the desired percentage, which saves you from having to repeatedly move the mouse. That is 10 for 10%, 25 for 25%, and so on.

3. Resizing Tips

The scale tool would be activated if you pressed K while choosing a frame or element. use of it? It gives you the option to resize the chosen content while keeping its proportions. When resizing, holding the alt or option buttons would make it larger from the center.

4. Collapse All Layers

In the past, I've been guilty of leaving groups after groups and elements after elements open in my Layers panel, which makes it more difficult to discover anything there. Use the convenient keyboard shortcut Alt + L to periodically collapse all Layers to keep your panel appearing nice and orderly and to maintain your attention on the current project.

5. Quicker Layers Navigation

Use the keyboard commands Enter and Tab to rapidly navigate between the Layers panel's items and locate what you're looking for. To navigate back up through your Layer groups and parent containers, hold Shift while using the keyboard keys I just mentioned.

6. Add Images in Bulk

This Figma shortcut gives you quick access to the Place Image tool, which makes it simple to add photographs to a Figma document. Press Ctrl + Shift + K, then select the required images and place them on canvas. You may import a photo straight onto the frame to keep it at its original size, or you can upload a photo inside a design form to scale it to match the shape. You may add a lot of photographs to your design at once.

October 30, 20222 minutesauthorNency Dobariya
How to implement Laravel impersonate

What is user impersonate and why we use it in projects?

  • User Impersonate is useful when we want to login on behalf of admin user.
  • When we are a super-admin and we want to know about our users what they do in their account then this package is useful to check their activity.
  • If you implemented impersonate in your project then you need to maintain it because it may cause a security issue as well as user's privacy issue.

Here is a full documentation of laravel impersonate: https://github.com/404labfr/laravel-impersonate

So let's start with installing impersonate on your project copy the below code where we will install this package using composer.

 composer require lab404/laravel-impersonate

Add the service provider at the end of your config/app.php:

 'providers' => [
     // ...
     Lab404\Impersonate\ImpersonateServiceProvider::class,
  ],

Add the trait Lab404\Impersonate\Models\Impersonate to your User model.

Using the built-in controller

In your routes file, under web middleware, you must call the impersonate route macro.

 Route::impersonate();

 // Where $id is the ID of the user you want impersonate
 route('impersonate', $id)

 // Or in case of multi guards, you should also add `guardName` (defaults to `web`)
 route('impersonate', ['id' => $id, 'guardName' => 'admin'])

 // Generate an URL to leave current impersonation
 route('impersonate.leave')

Blade

There are three Blade directives available.

When the user can impersonate

 @canImpersonate($guard = null)
     <a href="{{ route('impersonate', $user->id) }}">Impersonate this user</a>
 @endCanImpersonate

When the user can be impersonated

 @canBeImpersonated($user, $guard = null)
     <a href="{{ route('impersonate', $user->id) }}">Impersonate this user</a>
 @endCanBeImpersonated

When the user is impersonated

 @impersonating($guard = null)
     <a href="{{ route('impersonate.leave') }}">Leave impersonation</a>
 @endImpersonating

That's it. Enjoy.

October 15, 20221 minuteauthorMitesh Makwana
Use Laravel localization key into your Javascript code

Convert all your localization messages from your Laravel app to JavaScript.

Generally, we cannot use the laravel localization key in its javascript. is that possible to use laravel localization in javascript?

Yes, now you can use laravel localization into laravel, thanks to the rmariuzzo/Laravel-JS-Localization package.

In this tutorial, we will learn how to use laravel localization in javascript, so let's get started.

Install the package

 composer require mariuzzo/laravel-js-localization

In your Laravel app go to config/app.php and add the following service provider:

Mariuzzo\LaravelJsLocalization\LaravelJsLocalizationServiceProvider::class

Usage

The Laravel-JS-Localization package provides a command that generates the JavaScript version of all your messages found in app/lang (Laravel 4) or resources/lang (Laravel 5) directory.

Generating JS messages

 php artisan lang:js

The resulting JavaScript file will contain all your messages plus messages.js in your public directory.

Link that js file into your main layout.

 

Documentation

Getting a message

 Lang.get('messages.home');

Getting a message with replacements

 Lang.get('messages.welcome', { name: 'Joe' });

Changing the locale

 Lang.setLocale('es');
October 05, 20221 minuteauthorPankaj Makwana
How to Get Leads from LinkedIn

Add connections to your network

If you spend a minute or more each workday clicking the "Connect" button on the "People You May Know" list that LinkedIn posts in your feed, you'll expand your network, and you'll be known as a network expander. will, which is equally important.

Remember: Everyone you talk to about business or meet during a business day is a potential LinkedIn connection.

Build your lead list

Spend five minutes a day checking your contacts' connections to see who you don't know personally but would like to meet. Note down who you want to introduce. Start with the "recommendations" first, as those are likely the strongest connections of the LinkedIn user you're looking at.

Ask for recommendations outside of your LinkedIn account via email or phone. You will get a quick reply. (And you'll get a chance to quickly reconnect with your connections.)

Follow up with your current customers and prospects

Spend another two minutes each day searching for your current clients and top prospects. Find out if they have a company page. If they do, follow through and monitor.

Join groups

LinkedIn lets you connect with people who are in groups with you. Use this as a targeted way to add value to others, share insights, and build your network with prospects. Invest five minutes in this every day.

Use LinkedIn to celebrate the achievements of others

When you see a news story or post that provides good news about your client or prospect or any key contact, share the news as a status update. Identify a person with an "@" reply. It will ensure that they receive the mentioned notification. Spend a minute a day on this.

Write a recommendation

Securing LinkedIn recommendations is often difficult, if only because it takes time for the author to log in, write, and post.

Instead of waiting for someone to recommend you, take five minutes a day to write and post (reality-based) recommendations for your customers and key contacts. Once your contact approves the text, the recommendation will appear on his/her LinkedIn account.

September 30, 20222 minutesauthorAnkit Kalathiya
UUIDs as Primary Keys with a Trait in Laravel 9

What are UUIDs?

UUIDs stands for Universally Unique Identifiers and are 128 bits values used to uniquely identify some record in our database. UUIDs are represented as a hexadecimal string split into five groups separated by hyphens.UUIDs are universally unique alphanumeric identifiers that are 36 characters long.

Instead of using auto-incrementing integers as your Eloquent model's primary keys, you may choose to use UUIDs instead.

Updating Migration File

It is a very important step to update our migration file, I want to use the UUIDs in my User class so I will make changes to my User’s migration class.

 $table->id();

to this:

$table->uuid('id')->primary();

If you are using a UUID primary key as a foreign key in another table, you need to change the column type to UUID, where the foreign key is defined. from this:

$table->unsignedBigInteger('user_id')->unsigned();

to this:

$table->uuid('user_id');

Using Trait in Our Model Class

you may use the Illuminate\Database\Eloquent\Concerns\HasUuids trait on the model.

use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
  use HasUuids;

  // ...
}

$user = User::create(['name' => 'John','email' => 'john@doe.com']);

$user->id; //72106479-5367-4853-9b44-b8b7a1e94f01

By default, The HasUuids trait will generate "ordered" UUIDs for your models. These UUIDs are more efficient for indexed database storage because they can be sorted lexicographically.

  • UUIDs are safer than using regular numeric IDs because they are not easy to spoof. Regular IDs make it easy to get information about the application, like how many users the application has.
  • Using UUID is a great solution for multi-tenancy applications.

I hope you will find this post useful.

September 20, 20221 minuteauthorBhargav Rangani
How to start activity using Animation?

Material design apps use activity transitions to connect different states with motion and transformations. Entry and exit transitions, as well as transitions between shared elements, can be animated.

Android supports these enter and exit transitions

1] Explode :

  • Views are moved in or out of the scene's center.

2] Slide :

  • Views are moved in or out from a scene's edge.

3] Fade

  • Changes the opacity of a view to add or remove it from the scene.

These transitions are also supported on Android

ChangeBounds :

  • Makes target views' layout bounds change.

ChangeClipBounds :

  • Animates changes made to the clip boundaries of target views.

ChangeTransform :

  • Initiates the scale and rotation change of target views.

ChangeImageTransform :

  • Images have a change in size and scale as a result of animation.

Check on versions compatibility


// Check if we're running on Android 5.0 or higher
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                // Apply activity transition
            } else {
                // Swap without transition
}

Create custom transitions

  • When you define a style that inherits from the material theme, enable window content transitions with the android:windowActivityTransitions attribute.
<style name="BaseAppTheme" 
parent="android:Theme.Material">
      <!-- enable window content transitions -->
      <item name="android:windowActivityTransitions">true</item>
      <!-- specify enter and exit transitions -->
      <item name="android:windowEnterTransition">@transition/explode</item>
      <item name="android:windowExitTransition">@transition/explode</item>

<!-- specify shared element transitions -->
      <item name="android:windowSharedElementEnterTransition">
            @transition/change_image_transform</item>
      <item name="android:windowSharedElementExitTransition">
            @transition/change_image_transform</item>
</style>

This example defines the change_image_transform transition as follows:

<!-- res/transition/change_image_transform.xml -->
<!-- (see also Shared Transitions below) -->
<transitionSet 
       xmlns:android="http://schemas.android.com/apk/res/android">
       <changeImageTransform/>
</transitionSet>

In your code, enable window content transitions by calling Window.requestFeature() :

            // inside your activity (if you did not enable transitions in your theme)
            getWindow().requestFeature(Window.FEATURE_ACTIVITY_TRANSITIONS);

            // set an exit transition
            getWindow().setExitTransition(new Explode());

Use transitions to start an activity

startActivity(intent,ActivityOptions.makeSceneTransitionAnimation(this).toBundle());

Let someone start a new activity with a shared element

To make a screen transition animation between two activities that have a shared element:

            final View imgContainerView = findViewById(R.id.img_container);

            // get the common element for the transition in this activity
            final View androidRobotView = findViewById(R.id.image_small);

            // define a click listener
            imgContainerView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(this, Activity2.class);
                    // create the transition animation - the images in the layouts
                    // of both activities are defined with android:transitionName="robot"
                    ActivityOptions options = ActivityOptions
                        .makeSceneTransitionAnimation(this, androidRobotView, "robot");
                    // start the new activity
                    startActivity(intent, options.toBundle());
                }
            });

An activity with multiple elements is an excellent start

            ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(this,
                    Pair.create(view1, "agreedName1"),
                    Pair.create(view2, "agreedName2"));
September 15, 20222 minutesauthorVivek Beladiya
Motivational Theories

To enhance productivity at the workplace, Motivation is essential. but the question is how to motivate employees. Well, there are various motivational theories.

  • Maslow’s Hierarchy of Needs
  • Herzberg’s Two-Factor Theory
  • McGregor’s X and Y Theories
  • McClelland’s Need Achievement Theory
  • The Equity Theory
  • Value–Percept Theory
  • Vroom’s Expectancy Theory
  • Porter-Lawler Model

let's discuss the first theory

Maslow's Hierarchy of needs

This theory is based on the human requirement, Abraham Maslow explained how individuals behave when they met the requirement. Maslow's theory indicates that Job satisfaction revolved around employees' needs and that factors bring them to a reasonable level of satisfaction.

Maslow divided his theory into five different stages as per individuals' priorities, these five stages are based on the various needs of human beings.

  • Stage-1 Physiological needs
  • Stage-2 Safety and security needs
  • Stage-3 Social needs
  • Stage-4 Esteem Needs
  • Stage-5 Self- actualization needs

Stage-1 Physiological needs

Physiological needs are basic needs like drinking when thirsty, and eating when hungry, Maslow considered psychological needs as the most essential needs. people are more likely to fulfill these needs first, for instance- If anyone is really hungry then it's hard to focus on any other thing besides food.

Stage-2 Safety and security

Once the physiological needs are fulfilled then it's human tendency to think about safety and security which includes saving, investment, and extra income.

Stage-3 Social need

This step involved love feelings and acceptance. These needs include both relationship Romantic relationships as well as tied with friends and family members. It also includes forming a social group. Feeling the love from others and feeling love towards others both are the key points of this stage.

Stage-4 Esteem Needs

This need involved two components- the first component involved Feeling confident and feeling good about oneself. The second component involved feeling valued by others.

Stage-5 Self- actualization needs

Self-actualization needs to involve a feeling of fulfillment all needs are acquired by the individual. A person is living up to the potential. a significant feature of this stage is person looks different from others.

According to Maslow, this feeling of self-actualization is really rare for instance Albert Einstein and Mother Teresa. to read more about Maslow's theory please read my upcoming blog

November 15, 20222 minutesauthorDarshika Kyada