Friday, March 29, 2019

Login with Facebook using PHP.

Before you begin to integrate Login with Facebook using PHP, take a look the files structure.
facebook_login_php/
├── config.php
├── index.php
├── logout.php
├── User.class.php
├── facebook-php-graph-sdk/
├── images/
│   ├── fb-login-btn.png
└── css/
    └── style.css
 For Login with Facebook using PHP follow these step.

Create Facebook App


  • Go to the Facebook for Developers page and log in with your Facebook account.
  • Click the My Apps link at the top navigation bar and select Add New App.
    • Enter the Display Name and Contact Email.
    • Click on the Create App ID button.
    • You will be redirected to the App Dashboard.
  • Navigate to the Settings » Basic page.
    • Specify the App Domains and select the Category of your App.
    • Click the Save Changes.
  • Navigate to the Add a Product page by clicking the PRODUCTS(+) link at the left navigation menu panel.
    • Select Facebook Login to Set Up.
    • Select Web as the App platform.
    • Enter the Site URL and Save.
  • Navigate to the Facebook Login » Settings page.
    • In the Valid OAuth Redirect URIs field, enter the Redirect URL.
    • Click the Save Changes.
Go to the Settings » Basic page, note the App ID and App Secret. This App ID and App secret allow you to access the Facebook APIs.


Get the Profile Link and Gender


  • Go to the App Review » Permissions and Features page.
  • Request for user_link and user_gender permissions and submit the required information.


 

Create Database Table


CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `oauth_provider` enum('','facebook','google','twitter') COLLATE utf8_unicode_ci NOT NULL,
 `oauth_uid` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `gender` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
 `picture` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
 `link` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Facebook SDK for PHP


 <?php

class User {
    private $dbHost     DB_HOST;
    private $dbUsername DB_USERNAME;
    private $dbPassword DB_PASSWORD;
    private $dbName     DB_NAME;
    private $userTbl    DB_USER_TBL;
    
    function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost$this->dbUsername$this->dbPassword$this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " $conn->connect_error);
            }else{
                $this->db $conn;
            }
        }
    }
    
    function checkUser($userData = array()){
        if(!empty($userData)){
            // Check whether user data already exists in database
            $prevQuery "SELECT * FROM ".$this->userTbl." WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."'";
            $prevResult $this->db->query($prevQuery);
            if($prevResult->num_rows 0){
                // Update user data if already exists
                $query "UPDATE ".$this->userTbl." SET first_name = '".$userData['first_name']."', last_name = '".$userData['last_name']."', email = '".$userData['email']."', gender = '".$userData['gender']."', picture = '".$userData['picture']."', link = '".$userData['link']."', modified = NOW() WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."'";
                $update $this->db->query($query);
            }else{
                // Insert user data
                $query "INSERT INTO ".$this->userTbl." SET oauth_provider = '".$userData['oauth_provider']."', oauth_uid = '".$userData['oauth_uid']."', first_name = '".$userData['first_name']."', last_name = '".$userData['last_name']."', email = '".$userData['email']."', gender = '".$userData['gender']."', picture = '".$userData['picture']."', link = '".$userData['link']."', created = NOW(), modified = NOW()";
                $insert $this->db->query($query);
            }
            
            // Get user data from the database
            $result $this->db->query($prevQuery);
            $userData $result->fetch_assoc();
        }
        
        // Return user data
        return $userData;
    }
}

Site Settings and API Configuration (config.php)


Database Constants:
  • DB_HOST – Specify the database host.
  • DB_USERNAME – Specify the database username.
  • DB_PASSWORD – Specify the database password.
  • DB_NAME – Specify the database name.
  • DB_USER_TBL – Specify the table name where the user’s account data will be stored.
Facebook API Constants:
  • FB_APP_ID – Specify the Facebook App ID.
  • FB_APP_SECRET – Specify the Facebook App Secret.
  • FB_REDIRECT_URL – Specify the Callback URL.
Call Facebook API:
  • The PHP SDK library is used to connect with Facebook API and working with OAuth client.


 <?php
/*
 * Basic Site Settings and API Configuration
 */

// Database configuration
define('DB_HOST''MySQL_Database_Host');
define('DB_USERNAME''MySQL_Database_Username');
define('DB_PASSWORD''MySQL_Database_Password');
define('DB_NAME''MySQL_Database_Name');
define('DB_USER_TBL''users');

// Facebook API configuration
define('FB_APP_ID''Insert_Facebook_App_ID');
define('FB_APP_SECRET''Insert_Facebook_App_Secret');
define('FB_REDIRECT_URL''Callback_URL');

// Start session
if(!session_id()){
    session_start();
}

// Include the autoloader provided in the SDK
require_once __DIR__ '/facebook-php-graph-sdk/autoload.php';

// Include required libraries
use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;

// Call Facebook API
$fb = new Facebook(array(
    'app_id' => FB_APP_ID,
    'app_secret' => FB_APP_SECRET,
    'default_graph_version' => 'v3.2',
));

// Get redirect login helper
$helper $fb->getRedirectLoginHelper();

// Try to get access token
try {
    if(isset($_SESSION['facebook_access_token'])){
        $accessToken $_SESSION['facebook_access_token'];
    }else{
          $accessToken $helper->getAccessToken();
    }
} catch(FacebookResponseException $e) {
     echo 'Graph returned an error: ' $e->getMessage();
      exit;
} catch(FacebookSDKException $e) {
    echo 'Facebook SDK returned an error: ' $e->getMessage();
      exit;
}

Login & Get Facebook Account Data (index.php)


 <?php
// Include configuration file
require_once 'config.php';

// Include User class
require_once 'User.class.php';

if(isset($accessToken)){
    if(isset($_SESSION['facebook_access_token'])){
        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    }else{
        // Put short-lived access token in session
        $_SESSION['facebook_access_token'] = (string) $accessToken;
        
          // OAuth 2.0 client handler helps to manage access tokens
        $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;
        
        // Set default access token to be used in script
        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    }
    
    // Redirect the user back to the same page if url has "code" parameter in query string
    if(isset($_GET['code'])){
        header('Location: ./');
    }
    
    // Getting user's profile info from Facebook
    try {
        $graphResponse $fb->get('/me?fields=name,first_name,last_name,email,link,gender,picture');
        $fbUser $graphResponse->getGraphUser();
    } catch(FacebookResponseException $e) {
        echo 'Graph returned an error: ' $e->getMessage();
        session_destroy();
        // Redirect user back to app login page
        header("Location: ./");
        exit;
    } catch(FacebookSDKException $e) {
        echo 'Facebook SDK returned an error: ' $e->getMessage();
        exit;
    }
    
    // Initialize User class
    $user = new User();
    
    // Getting user's profile data
    $fbUserData = array();
    $fbUserData['oauth_uid']  = !empty($fbUser['id'])?$fbUser['id']:'';
    $fbUserData['first_name'] = !empty($fbUser['first_name'])?$fbUser['first_name']:'';
    $fbUserData['last_name']  = !empty($fbUser['last_name'])?$fbUser['last_name']:'';
    $fbUserData['email']      = !empty($fbUser['email'])?$fbUser['email']:'';
    $fbUserData['gender']     = !empty($fbUser['gender'])?$fbUser['gender']:'';
    $fbUserData['picture']    = !empty($fbUser['picture']['url'])?$fbUser['picture']['url']:'';
    $fbUserData['link']       = !empty($fbUser['link'])?$fbUser['link']:'';
    
    // Insert or update user data to the database
    $fbUserData['oauth_provider'] = 'facebook';
    $userData $user->checkUser($fbUserData);
    
    // Storing user data in the session
    $_SESSION['userData'] = $userData;
    
    // Get logout url
    $logoutURL $helper->getLogoutUrl($accessTokenFB_REDIRECT_URL.'logout.php');
    
    // Render Facebook profile data
    if(!empty($userData)){
        $output  '<h2>Facebook Profile Details</h2>';
        $output .= '<div class="ac-data">';
        $output .= '<img src="'.$userData['picture'].'"/>';
        $output .= '<p><b>Facebook ID:</b> '.$userData['oauth_uid'].'</p>';
        $output .= '<p><b>Name:</b> '.$userData['first_name'].' '.$userData['last_name'].'</p>';
        $output .= '<p><b>Email:</b> '.$userData['email'].'</p>';
        $output .= '<p><b>Gender:</b> '.$userData['gender'].'</p>';
        $output .= '<p><b>Logged in with:</b> Facebook</p>';
        $output .= '<p><b>Profile Link:</b> <a href="'.$userData['link'].'" target="_blank">Click to visit Facebook page</a></p>';
        $output .= '<p><b>Logout from <a href="'.$logoutURL.'">Facebook</a></p>';
        $output .= '</div>';
    }else{
        $output '<h3 style="color:red">Some problem occurred, please try again.</h3>';
    }
}else{
    // Get login url
    $permissions = ['email']; // Optional permissions
    $loginURL $helper->getLoginUrl(FB_REDIRECT_URL$permissions);
    
    // Render Facebook login button
    $output '<a href="'.htmlspecialchars($loginURL).'"><img src="images/fb-login-btn.png"></a>';
}
?>

<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Login with Facebook using PHP </title>
<meta charset="utf-8">
</head>
<body>
<div class="container">
    <div class="fb-box">
        <!-- Display login button / Facebook profile information -->
        <?php echo $output?>
    </div>
</div>
</body>
</html>

Logout (logout.php)


<?php
// Include configuration file
require_once 'config.php';

// Remove access token from session
unset($_SESSION['facebook_access_token']);

// Remove user data from session
unset($_SESSION['userData']);

// Redirect to the homepage
header("Location:index.php");
?>

Post to a Facebook page using the Facebook PHP API

1. Create a Facebook 'App':

Firstly you need to create a Facebook App, which is required in order to use the API. Sign in to your Facebook Developers account and click the ‘Add a New App’ link as shown below:



Enter your App name and click ‘create’. Under ‘settings’, you’ll need to add a ‘website platform’ and enter the domain where this script will sit. For security, it’s also worth adding the IP address of the server where your site sits in the ‘Server IP Whitelist’ field. You do so under ‘advanced settings’.

2. Install the Facebook PHP SDK:

In this example I’ll assume your code will sit in a ‘facebook’ folder in the root directory of your site. Firstly, create a blank ‘index.php’ file within your ‘facebook’ folder. Next up, you need to include the Facebook SDK for PHP.
Facebook recommend you include the PHP SDK in your project using Composer, but you can also manually do so. In this example we’ll manually include the SDK, so you firstly need to download the SDK.
Unzip the files and put the ‘src’ folder in your ‘facebook’ folder. Then include the SDK in your index.php file:

define('FACEBOOK_SDK_V4_SRC_DIR', __DIR__.'/src/Facebook/');
require_once(__DIR__.'/src/Facebook/autoload.php');

3. Enter your App's settings:

Next up, you need to enter your ‘App ID’ and ‘App secret’ keys into the code below. You can get your App’s ‘App ID’ and ‘App secret’ under the ‘dashboard’ tab:

$fb = new Facebook\Facebook([
 'app_id' => 'xxxxxxxxxx',
 'app_secret' => 'xxxxxxxxxx',
 'default_graph_version' => 'v2.2',
]);

4. Get a non-expiring Access Token for your App:

Next up, if you want to automatically post content to your Facebook page like I needed to…you’re going to need to get a non-expiring Access Token for your page. Firstly, visit the Facebook Graph API Explorer page. You’ll see an ‘Application’ button in the top right as show below:


As you can see, currently this is set to ‘Graph API Explorer’. Select your Facebook App instead. Now click the ‘get token’ button which you can also see in the image above. Select ‘Get User Access Token’ and make sure the ’publish_pages’, ‘manage_pages’ and ‘publish_actions’ permissions are ticked, then click the ‘Get Access Token’ button. Now click the ‘get token’ button again and select your Facebook page. You now have your Access Token which we need to convert into the non-expiring Access Token. To do so, pass your App ID, App Secret and Access Token into the following URL:
https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=appid&client_secret=appsecret&fb_exchange_token=accesstoken
Now copy the token provided.

5. The code that does the 'posting':

Next up, the code that actually posts the content to the Facebook page. In my case I wanted to loop through WordPress posts and post a link and comment for any newly added posts onto my clients Facebook page. Within my WordPress posts loop was the all important code below:

//Post property to Facebook
$linkData = [
 'link' => 'yoururl.com',
 'message' => 'Your message here'
];
$pageAccessToken ='yournonexpiringtoken';

try {
 $response = $fb->post('/me/feed', $linkData, $pageAccessToken);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
 echo 'Graph returned an error: '.$e->getMessage();
 exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
 echo 'Facebook SDK returned an error: '.$e->getMessage();
 exit;
}
$graphNode = $response->getGraphNode();
 
There you go, if you now run this file it will post your content to your Facebook page.



Ads Management:

You can visit   

https://developers.facebook.com/docs/marketing-api/buying-api/




 


No comments:

Post a Comment