Tektriks

Coding starts here
Home / Blog

How to create WordPress user using latest Facebook PHP SDK

There are many plugins available for WordPress to integrate login with social networking sites. Some of them are very handy as non-technical person can install and manage those following their simple instructions. But many of them comes with their in-built buttons or images as a group of login links. For many developers, it becomes nightmare to handle those if some customizations required. If you search on internet “login with facebook php sdk “, you can find same working codes are available but can be seen rare for WordPress. Today I will show you how to integrate login with latest Facebook PHP SDK v4-5.0-dev.
Our logic will be –

  • Provide user a login link
  • Get email from Facebook
  • Register and login user if email is new or login directly if email is already registered

First of all, download Facebook SDK and create a Facebook app. Go to Facebook Developers. Next follow the instructions given below:

1
2








Now extract your Facebook SDK files. Go to facebook-php-sdk-v4-5.0-dev > src folder. Copy the facebook folder, rename it as “facebook-sdk” and upload to root folder of your site. Open wp-config.php file and define facebook app constants like ‘APP_ID’, ‘APP_SECRET’ & ‘REDIR_URL’. Open header.php file of your theme folder. On the top of it, write down the code given below:

<?php
require_once 'facebook-sdk/autoload.php';

if( ! isset( $_GET['code'] ) )
{
	session_start();
}	

// setup application using API keys and handlers
$fb = new Facebook\Facebook([
  'app_id' => APP_ID,
  'app_secret' => APP_SECRET,
  'default_graph_version' => 'v2.4',
  'http_client_handler' => 'curl', // can be changed to stream or guzzle
  'persistent_data_handler' => 'session' // make sure session has started
]);

if( isset( $_GET['code'] ) )
{
	$helper = $fb->getRedirectLoginHelper();
	// Trick below will avoid "Cross-site request forgery validation failed. Required param "state" missing." from Facebook
	$_SESSION['FBRLH_state'] = $_REQUEST['state'];
}
else
{
	// login helper with redirect_uri
	$helper = $fb->getRedirectLoginHelper( REDIR_URL );	
}


// see if we have a code in the URL
if( isset( $_GET['code'] ) ) {
  // get new access token if we've been redirected from login page
  try {
    // get access token
    $access_token = $helper->getAccessToken();
    
    // save access token to persistent data store
    $helper->getPersistentDataHandler()->set( 'access_token', $access_token );
  } catch ( Exception $e ) {
    // error occured
    echo 'Exception 1: ' . $e->getMessage() . '
';
  }
  
	// get stored access token
	$access_token = $helper->getPersistentDataHandler()->get( 'access_token' );  
}

// check if we have an access_token, and that it's valid
if ( $access_token && !$access_token->isExpired() )
{ 
  // set default access_token so we can use it in any requests
  $fb->setDefaultAccessToken( $access_token );
	try {
		// Returns a `Facebook\FacebookResponse` object
		$response = $fb->get('/me?fields=first_name,last_name,email', $access_token);
	} 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;
	}
	
	$user = $response->getGraphObject()->asArray();

	$fb_email 		= $user['email'];
	$fb_firstname 	= $user['first_name']; 
	$fb_lastname	= $user['last_name'];
	$username 		= substr( md5( $fb_email ), 0, 10 );
	$password		= substr( md5( $fb_email ), 10, 10 );  	
	
    if( ! email_exists( $fb_email ) ) {
  	
		$userdata = array(
			'user_login'  =>  $username,
			'user_email'  =>  $fb_email,
			'user_pass'   =>  $password
		);

		$user_id = wp_insert_user( $userdata ) ;

        if ( is_wp_error( $user_id ) ) {
            $error_message = $wp_user_id->get_error_code();
            // There was an error creating this user provide error message
        }
        else 
        {
		$meta = array(
			'first_name' => $fb_firstname,
			'last_name'  => $fb_lastname
		);
		
		foreach ( $meta as $key => $value ) {
			update_user_meta( $user_id, $key, $value );
		}			

		wp_set_current_user( $userid );
		wp_set_auth_cookie( $user_id, false, is_ssl() );

		// Send mail to new user
		$to = $fb_email;
		$blogname = get_bloginfo( 'name' );
		$adminmail = get_option( 'admin_email' );
		$subject = "[$blogname] Welcome Mail";
		$message = "Hi $fb_firstname,

";
		$message.= "Thank you for joining $blogname.

";
		$message.= 'Here are your login credentials: 
';
		$message.= "Username: $username 
Password: $password 

";
		$message.= "Thank you,
$blogname Customer Support Team";
		$headers = array('Content-Type: text/html; charset=UTF-8');
		$headers[] = "From: $blogname <$adminmail>";
		
		// Send mail to new user
		wp_mail($to, $subject, $message, $headers);

		// Send mail to admin for new user registration
		wp_new_user_notification( $user_id, $password );

		wp_redirect( get_permalink( 4 ) );  // redirect to any page
		exit;
        }
    }	
    else
	{
    	$user_obj = get_user_by( 'email', $fb_email ); // get user by email

	wp_set_current_user( $user_obj->ID );
	wp_set_auth_cookie( $user_obj->ID, false, is_ssl() );

	wp_redirect( get_permalink( 4 ) ); // redirect to any page
	exit;		        	
    }    
}
?>

Feel free to comment us if any error occurred.

Subscribe
Notify of
guest
6 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Mourn Mey
4 years ago

Hi All Bro . I get Error Undefined variable: access_token in ,How solution !!

Margarito
8 years ago

Simply wish to say your article is as amazing.

The clearness in your post is simply nice and i can assume you’re an expert on this subject.

Fine with your permission allow me to grab your feed to keep updated with forthcoming post.
Thanks a million and please carry on the enjoyable work.

kittchen
8 years ago

I just could not depart your site before suggesting that I extremely enjoyed the usual info an individual provide in your visitors?
Is gonna be back often to check up on new posts

Ugg En España
8 years ago

Hello, I enjoy reading through your article post.
I like to write a little comment to support you.

Swen
8 years ago

I’m extremely pleased to uncover this website.

I want to to thank you for your time just for this fantastic read!!

I definitely really liked every part of it and I have you saved as a favorite to check out new information in your
web site.

Young
8 years ago

Hmm is anyone else having problems with the pictures on this blog loading?
I’m trying to find out if its a problem on my end or if it’s
the blog. Any responses would be greatly appreciated.

6
0
Would love your thoughts, please comment.x
()
x