如何让用户访问令牌Facebook获得用户id


How to get user accesses token Facebook to get user id

我试图获得用户访问令牌我尝试了一百万次,但不工作,请任何人帮助我这样尝试

$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; 

我试着像这样登录

$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;

登录后,返回的url如下所示

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

和返回错误

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

我不知道返回的url中的代码和状态是什么,我的代码来自facebook文档

请帮助获得facebook用户id和访问令牌提前非常感谢任何帮助。

获得访问令牌后,只需:

    // 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());

首先我添加了这个函数来获取facebook登录链接

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;
}

在我的页面,我想得到的用户id,如果调用这个函数和隐藏facebook链接,因为我想触发这个链接在checkbox输入点击

$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);
                    }
                });
            }
        });

点击checkbox输入后,点击它将触发Facebook登录事件,并将在URL中生成代码和状态,返回URL用于与访问令牌交换,因此在重新加载后,我从URL中获取代码,就像这样在同一页面中,我想获得用户id

 $parts = parse_url($_SERVER['REQUEST_URI']);
        parse_str($parts['query'], $query);
        if(!empty($query['code'])) {
            $IsFaceBookLinked = LinkFaceBookToUserProfile($query['code']);
        }

则获取用户id的过程在LinkFaceBookToUserProfile()函数中,如下所示

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;
}

希望帮助任何寻找这个和节省时间链接可能会帮助你。