简体   繁体   中英

How to get user accesses token Facebook to get user id

i'm trying to get user access token i tried a million time but is not working can any one please help i'm trying like this

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

try {
    // Returns a `Facebook\FacebookResponse` object
    $response = $fb->get('/me?fields=id,name', '{ THE 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->getGraphUser();

return $user; 

i try to log in like this

$helper = $fb->getRedirectLoginHelper();

$permissions = ['public_profile','email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('http://WebSite', $permissions);

echo '<a href="' . $loginUrl . '">Log in with Facebook!</a>';

  try {
        $accessToken = $helper->getAccessToken();
        var_dump($accessToken);
    } 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 ($helper->getError()) {
            header('HTTP/1.0 401 Unauthorized');
            echo "Error: " . $helper->getError() . "\n";
            echo "Error Code: " . $helper->getErrorCode() . "\n";
            echo "Error Reason: " . $helper->getErrorReason() . "\n";
            echo "Error Description: " . $helper->getErrorDescription() . "\n";
        } else {
            header('HTTP/1.0 400 Bad Request');
            echo 'Bad request';
        }
        exit;
    }

// Logged in
    echo '<h3>Access Token</h3>';
    var_dump($accessToken->getValue());

// The OAuth 2.0 client handler helps us manage access tokens
    $oAuth2Client = $fb->getOAuth2Client();

// Get the access token metadata from /debug_token
    $tokenMetadata = $oAuth2Client->debugToken($accessToken);
    echo '<h3>Metadata</h3>';
    var_dump($tokenMetadata);

// Validation (these will throw FacebookSDKException's when they fail)
    $tokenMetadata->validateAppId($config['1611286245754691']);
// If you know the user ID this access token belongs to, you can validate it here
//$tokenMetadata->validateUserId('123');
    $tokenMetadata->validateExpiration();

    if (!$accessToken->isLongLived()) {
        // Exchanges a short-lived access token for a long-lived one
        try {
            $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
        } catch (Facebook\Exceptions\FacebookSDKException $e) {
            echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n";
            exit;
        }

        echo '<h3>Long-lived</h3>';
        var_dump($accessToken->getValue());
    }

    $_SESSION['fb_access_token'] = (string)$accessToken;

after i login the returned url is like this

http://websitr?code=*******&state=********#_=_

and return error

Facebook SDK returned an error: Cross-site request forgery validation failed. The "state" param from the URL and session do not match.

i don't relay know what is the code and state in the returned url my code from the face book documentation

please any help to get the face book user id and the accesses token many thanks in advance for any help.

Once you get your access token, just :

    // The OAuth 2.0 client handler helps us manage access tokens
    $oAuth2Client = $fb->getOAuth2Client();

    // Get the access token metadata from /debug_token
    $tokenMetadata = $oAuth2Client->debugToken($accessToken);
    print_r($tokenMetadata->getUserId());

i manage to work this first i add this function to get the face book log in link

function Get_FaceBookProfileLink() // get the face book link
{
    $fb = new Facebook\Facebook([
        'app_id' => '********',
        'app_secret' => '*******',
        'default_graph_version' => 'v2.3',
    ]);

    $helper = $fb->getRedirectLoginHelper();
    $permissions = ['public_profile','email']; // Optional permissions
    $RedirectURL = home_url() .'/user-profile/'. wp_get_current_user()-> ID;
    $loginUrl = $helper->getLoginUrl(  $RedirectURL , $permissions);

    return $loginUrl;
}

in my page that i want to get the user id if call this function and hide the face book link because i want trigger this link on checkbox input click

$FaceBookProfileLink = Get_FaceBookProfileLink();

 <?php echo '<a id="FaceBookProfileLink" href="' . $FaceBookProfileLink . '" style="display: none;" >Log in with Facebook!</a>'; ?>


 $("#facebook").click(function () {

            if ($(this).is(':checked')) {

                window.location.href =$('#FaceBookProfileLink').attr('href');

            } else if (!$(this).is(':checked')) {

                $.ajax({
                    type: "POST",
                    async: true,
                    dataType: "json",
                    url: ajaxurl,

                    data: ({
                        type: "POST",
                        action: 'Ajax_DisableFaceBookLink'
                    }),
                    success: function (response) {
                        if (response.Message === 'Updated') {
                            alert('FaceBook disabled');
                        } else {
                            alert('ERRORS');
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.log(jqXHR);
                        console.log(textStatus);
                        console.log(errorThrown);
                    }
                });
            }
        });

after the click on the checkbox input click it will trigger the Facebook login event and will generate a code and states in the URL the returend url used to be exchange with an accesses token so after the reloading i toke the code from the URL like this in the same page that i want to get the user id

 $parts = parse_url($_SERVER['REQUEST_URI']);
        parse_str($parts['query'], $query);

        if(!empty($query['code'])) {

            $IsFaceBookLinked = LinkFaceBookToUserProfile($query['code']);

        }

then the process of getting the user id is in LinkFaceBookToUserProfile() function like this

function Get_FaceBookAccessToken($code)
{
    $AppSecret = '***************';
    $APPID = '******************';
    $RedirectURL = home_url() .'/user-profile/'. wp_get_current_user()-> ID;
    $url = 'https://graph.facebook.com/v2.3/oauth/access_token?client_id='.$APPID.'&redirect_uri='.$RedirectURL.'&client_secret='.$AppSecret.'&code='.$code;

    $ch = curl_init();

    curl_setopt_array($ch, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => 2
    ));

    $result = curl_exec($ch);
    curl_close($ch);

    $results = json_decode($result, true);

    return $results['access_token'];
}

function Get_FaceBookUser($AccessToken) {

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

    try {
        // Returns a `Facebook\FacebookResponse` object
        $response = $fb->get('/me?fields=id,name', $AccessToken);
    } 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->getGraphUser();

    return $user;
}

function Get_FaceBookUserID($code)
{
   return Get_FaceBookUser(Get_FaceBookAccessToken($code));
}

function LinkFaceBookToUserProfile($code)
{
    $FaceBookUserID = Get_FaceBookUserID($code)['id'];

    $UserPod = pods('user', wp_get_current_user()->ID);

    $data = array(
        'facebook_link' => 'https://www.facebook.com/app_scoped_user_id/' . $FaceBookUserID
    );
    $UserID = $UserPod->save($data);
    return $UserID;
}

hope to help any one looking for this and save time link may help you .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM