Sunday 9 December 2018

Integrating Google Signin For Websites

As I said in My Previous Post Nowadays in almost all websites, You can find login via Social media accounts. So its inevitable for all the developers to learn more about these processes & integrate into their own websites. Their are many benefits of integrating this.


1) You can reduce the time consumption for the long form filling process during the registration
2) You doesn't want to wait for the customers to verify their email address or anything.
3) You can retrieve much more information about the personal info from their social media accounts.

Integrating Google Sigin is more easier than the facebook Signup.
Here You Just need to Create a Project in Google account by visiting:-

https://console.developers.google.com/apis/

Their You have to Create a Project like this:-


Here While Creating Project you will get an ID related to the App.
So Just save it somewhere, so that you have to use it in the code..

Now Create 2 files in Your project root folder.. one is google.php and then myprofile.php. You can name whatever you want. I named it as per my convenience.

1) In google.php.. Place the code:-
<html lang="en">
  <head>
    <meta name="google-signin-scope" content="profile email">
    <meta name="google-signin-client_id" content="CLIENT_ID">
    <script src="https://apis.google.com/js/platform.js" async defer></script>
  </head>
  <body>
    <div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
    <script>
      function onSignIn(googleUser) {
        // Useful data for your client-side scripts:
        var profile = googleUser.getBasicProfile();
        console.log("ID: " + profile.getId()); // Don't send this directly to your server!
        console.log('Full Name: ' + profile.getName());
        console.log('Given Name: ' + profile.getGivenName());
        console.log('Family Name: ' + profile.getFamilyName());
        console.log("Image URL: " + profile.getImageUrl());
        console.log("Email: " + profile.getEmail());

        // The ID token you need to pass to your backend:
        var id_token = googleUser.getAuthResponse().id_token;
        console.log("ID Token: " + id_token);

        var id = profile.getId();
        var name = profile.getName();
        var email = profile.getEmail();
        var token= id_token;

        window.location.href = "googleaccess.php?id="+id+"&nm="+name+"&ml="+email+"&tk="+token;

      };
    </script>

Above script you noticed this line:-   <meta name="google-signin-client_id" content="CLIENT_ID">

Here update the CLIENT_ID variable with the value Iam going to explain to you.

Visit: https://developers.google.com/identity/sign-in/web/sign-in#before_you_begin

Here go to this portion Down:-

Click on the Red Dotted highlighted area.. Then a dialogue box appears:-

HERE the project and credentials will come.. But for better copying you click on the View Link on the Bottom which I highlighted in green. Then you will redirect to a page :-

Here You can see Client Id & Client Secret Values. Just copy the Client Id from here & paste it in the CLIENT_ID Place

<meta name="google-signin-client_id" content="CLIENT_ID">

2) Now From this page value will be passed to googleaccess.php..
Create a Page called googleaccess.php & copy paste the code their:-


<?php 
session_start();

?>

<head>

     <title>Login with Google</title>

     <link

        href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"

        rel = "stylesheet">

  </head>

  <body>     

  <?php if($_GET['id']) {?>

        <div class = "container">

           <div class = "jumbotron">

              <h1>Hello <?php echo $_GET['nm']; ?></h1>

              <p>Welcome to UAE Travel Agents</p>

           </div>

              <ul class = "nav nav-list">

                 

                 <h4>ID</h4>

                 <li><?php echo  $_GET['id']; ?></li>

                 <h4>Fullname</h4>

                 <li><?php echo $_GET['nm']; ?></li>

                 <h4>Email</h4>

                 <li><?php echo $_GET['ml']; ?></li>

                 <h4>Token</h4>

                 <li><?php echo $_GET['tk']; ?></li>
              </ul>

          </div>

<?php } ?>



Now You will get all the details in this page...

Integrating Facebook Login in Your Websites

Nowadays in almost all websites, You can find login via Social media accounts. So its inevitable for all the developers to learn more about these processes & integrate into their own websites. Their are many benefits of integrating this.

1) You can reduce the time consumption for the long form filling process during the registration
2) You doesn't want to wait for the customers to verify their email address or anything.
3) You can retrieve much more information about the personal info from their social media accounts.

Steps For Integration 

1) Creating Developer Account & Creating App

  • For Integrating this, first the developer has to create a developer account in facebook by going to https://developers.facebook.com/.
  • Now Create an App in that
  • Select Website as platform.
  • Now Give the Category, Email, App Type, Request URLS Approved.etc..




  • Keep the App ID & APP Secret safely in your hands. Dont Forget to make the app Live.
  • Also You can add Products in the app through this panel.


2) Downloading Facebook SDK

Download Facebook SDK from the web.
You can either install via composer or Can download from Github..  Download from here:- https://github.com/facebook/php-graph-sdk


3)Creating Our Login Script

Create two files in the application folder; index.php and myprofile.php.

Add the following code to index.php file. Comments are added to explain the code.

<?php
//initialize facebook sdk
require 'vendor/autoload.php'; //Link to the Folder Downloaded for afcebook graph sdk
session_start();
$fb = new Facebook\Facebook([
 'app_id' => 'Put Your App ID Here',
 'app_secret' => 'Put App Secret',
 'default_graph_version' => 'v2.5',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // optional
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
  $accessToken = $helper->getAccessToken();
}
} catch(Facebook\Exceptions\facebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}
if (isset($accessToken)) {
if (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
// getting short-lived access token
$_SESSION['facebook_access_token'] = (string) $accessToken;
  // OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
// setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// redirect the user to the profile page if it has "code" GET variable
if (isset($_GET['code'])) {
header('Location: profile.php');
}
// getting basic info about user
try {
$profile_request = $fb->get('/me?fields=name,first_name,last_name,email');
$requestPicture = $fb->get('/me/picture?redirect=false&height=200'); //getting user picture
$picture = $requestPicture->getGraphUser();
$profile = $profile_request->getGraphUser();
$fbid = $profile->getProperty('id');           // To Get Facebook ID
$fbfullname = $profile->getProperty('name');   // To Get Facebook full name
$fbemail = $profile->getProperty('email');    //  To Get Facebook email
$fbpic = "<img src='".$picture['url']."' class='img-rounded'/>";
# save the user nformation in session variable
$_SESSION['fb_id'] = $fbid.'</br>';
$_SESSION['fb_name'] = $fbfullname.'</br>';
$_SESSION['fb_email'] = $fbemail.'</br>';
$_SESSION['fb_pic'] = $fbpic.'</br>';
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
session_destroy();
// redirecting user back to app login page
header("Location: ./");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
} else {
// replace your website URL same as added in the developers.Facebook.com/apps e.g. if you used http instead of https and you used            
$loginUrl = $helper->getLoginUrl('http://sitename.com/url.php', $permissions);echo '<a href="' . $loginUrl . '">Log in with Facebook!</a>';
}
?>

Once done, go to the application URL in browser. You will see the Facebook button for login. Click it and the page will redirect to Facebook login page. Sign into the Facebook account. After successful login, the page will be redirected to the myprofile page.

Add the following code to myprofile.php to show the retrieved information. For the purpose of this tutorial, I will retrieve user id, Facebook profile picture, name and email.

<?php
session_start();
?>
<head>
     <title>Login with Facebook</title>
     <link
        href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
        rel = "stylesheet">
  </head>
  <body>   

  <?php if($_SESSION['fb_id']) {?>
        <div class = "container">
           <div class = "jumbotron">
              <h1>Hello <?php echo $_SESSION['fb_name']; ?></h1>
              <p>Welcome to PHP Dudes</p>
           </div>
              <ul class = "nav nav-list">
                 <h4>Image</h4>
                 <li><?php echo $_SESSION['fb_pic']?></li>
                 <h4>Facebook ID</h4>
                 <li><?php echo  $_SESSION['fb_id']; ?></li>
                 <h4>Facebook fullname</h4>
                 <li><?php echo $_SESSION['fb_name']; ?></li>
                 <h4>Facebook Email</h4>
                 <li><?php echo $_SESSION['fb_email']; ?></li>
              </ul>
          </div>
<?php } ?>
  </body>
</html> 


  • Now when the visitor, login via clicking the link, we will get info like this:-
  • Store the ID & token received in your Database & validate every time when use logins.. 

Download sample code from here:-  https://github.com/litto/Facebook