You are here

function hook_simple_fb_connect_registration in Simple FB Connect 7.2

This hook allows other modules to act on user creation via Facebook login.

There is also a Rules event triggered that can be used to react on user creation via Simple FB Connect.

The example code shows how to make an additional query to Facebook API in order to request user's first and last name and how to map these to corresponding Drupal user fields.

This example assumes that you have added fields "field_first_name" and "field_last_name" to User entity at admin/config/people/accounts/fields and that the length of these text fields is 255 characters.

List of User fields on Facebook: https://developers.facebook.com/docs/graph-api/reference/user

Parameters

$drupal_user: Drupal user that was just created via Simple FB Connect.

1 invocation of hook_simple_fb_connect_registration()
simple_fb_connect_create_user in ./simple_fb_connect.module
Creates a new user account for a Facebook user.

File

./simple_fb_connect.api.php, line 96
Hooks provided by the Simple FB Connect module.

Code

function hook_simple_fb_connect_registration($drupal_user) {

  // Implement this hook in your own module to act on user creation.
  // The code here is just an example.
  // Get FacebookSession for current user.
  $fb_session = simple_fb_connect_get_session();

  // Get API version from Simple FB Connect settings.
  $api_version = simple_fb_connect_get_api_version();

  // Try to read first and last name from Facebook API.
  try {
    $request = new FacebookRequest($fb_session, 'GET', '/me', array(
      'fields' => 'first_name,last_name',
    ), $api_version);
    $object = $request
      ->execute()
      ->getGraphObject();

    // Truncate Facebook values to 255 characters.
    $first_name = substr($object
      ->getProperty('first_name'), 0, 255);
    $last_name = substr($object
      ->getProperty('last_name'), 0, 255);

    // Save Facebook values to Drupal user.
    $drupal_user->field_first_name[LANGUAGE_NONE][0]['value'] = $first_name;
    $drupal_user->field_last_name[LANGUAGE_NONE][0]['value'] = $last_name;

    // Save the user.
    user_save($drupal_user);
  } catch (FacebookRequestException $ex) {
    watchdog('YOURMODULE', 'Could not load fields from Facebook: FacebookRequestException. Error details: @message', array(
      '@message' => json_encode($ex
        ->getResponse()),
    ), WATCHDOG_ERROR);
  } catch (\Exception $ex) {
    watchdog('YOURMODULE', 'Could not load fields from Facebook: Unhandled exception. Error details: @message', array(
      '@message' => $ex
        ->getMessage(),
    ), WATCHDOG_ERROR);
  }
}