如何使用API​​在Twitter中获取当前登录的用户详细信息

时间:2016-09-15 07:41:37

标签: twitter laravel-5

我正在使用Socialite使用Twitter登录并使用Abrahams的TwitterOauth来使API工作。在laravel中,我将API密钥信息设置为:

'twitter' => [
        'client_id'        => '**************',
        'client_secret'    => '**************',
        'access_token'     => '***************',
        'access_token_key' => '***************',
        'redirect'         => '***********',
    ],

连接到Twitter我用过:

public function getTwitterConnection()
    {
        $this->connection = new TwitterOAuth(Config::get('services.twitter.client_id'), Config::get('services.twitter.client_secret'), Config::get('services.twitter.access_token'), Config::get('services.twitter.access_token_key'));
    }

使用Socialite,我可以让用户通过他们的凭据登录。但是当我尝试访问时:

public function getCurrentLoggedInUser() {
        $this->getTwitterConnection();
        return $this->connection->get("account/verify_credentials");
    }

我正在获取开发者的Twitter帐户的信息,即我的。 我想我无法在Socialite和TwitterOauth之间进行同步。 我该如何解决这个问题?请建议我获取登录用户信息的更好方法。

4 个答案:

答案 0 :(得分:2)

我知道它已经很晚了。但无论如何,这是答案。

    'access_token'     => '***************',
    'access_token_key' => '***************',

您不需要包含这些详细信息。此access_tokenaccess_token_key属于您自己的帐户,这就是您获取帐户信息而非登录用户的原因。您必须使用已登录用户的access_tokenaccess_token_key,因此不应由您预先填写。

在处理twitter的回调重定向的控制器内部:

    // get logged in twitter user
    $user = Socialite::driver('twitter')->user();

    // OAuth One Providers
    $token = $user->token; // this is access_token that you need
    $tokenSecret = $user->tokenSecret; // this is the access_token_key that you need

    // now call TwitterOauth with all the details 
    // and then you can send request to account/verify_credentials

答案 1 :(得分:0)

这些代码对我帮助很大:

登录:

public function redirectToTwitter() // AuthController.php
{
    $t = new Twitter();
    $t->sessionDestroy();
    return redirect($t->getAuthUrl());
}

public function handleTwitterCallback(Request $request)
{
    $t = new Twitter();
    $oauth = $request->all();
    $user = $t->getCurrentLoggedInUser($oauth);
}

验证:T​​witter.php

public function getTwitterConnection(){
    $oauth_token = Session::get('oauth_token');
    $oauth_token_secret = Session::get('oauth_token_secret');
    if(!empty($oauth_token) && !empty($oauth_token_secret)) {
        $this->connection = new TwitterOAuth(Config::get('services.twitter.client_id'), Config::get('services.twitter.client_secret'), $oauth_token, $oauth_token_secret);
    }
    //return $this->connection->get("account/verify_credentials");
}

public function getAuthUrl() {
    $this->getAuthConnection();
    $token = $this->connection->oauth("oauth/request_token", array("oauth_callback" => Config::get('services.twitter.redirect')));
    Session::put($token);
    $url = $this->connection->url("oauth/authorize", ['oauth_token' => $token['oauth_token']]);
    return $url;
}

public function getCurrentLoggedInUser($oauth) {
    $this->getTwitterConnection(); //gets oauth for developers
    $access = $this->connection->oauth("oauth/access_token", array("oauth_verifier" => $oauth['oauth_verifier']));
    Session::put('oauth_token', $access['oauth_token']);
    Session::put('oauth_token_secret', $access['oauth_token_secret']);
    $this->getTwitterConnection(); //after login gets oauth for logged user
    return $this->connection->get("account/verify_credentials");
}

答案 2 :(得分:0)

与社交名流的推特 使用

$user = Socialite::driver('twitter')->userFromTokenAndSecret($token,$secret);

答案 3 :(得分:0)

这是我在Laravel API + Vue SPA(使用存储在cookie中的JWT)中进行GitHub和Twitter oauth登录的方式。我将展示安装,因为其中可能包含一些稀有元素。

我已经可以使用GitHub的oauth重定向和回调,所以我只需要添加Twitter,事实证明这很困难。我使用abraham/twitteroauth作曲家软件包解决了这个问题。这是一个灵巧的最小脚本。

/**
 * Redirect the user to the provider authentication page. Twitter uses OAuth1.0a, and does not support
 * Socialite::driver($provider)->stateless(), so library `abraham/twitteroauth` is used to handle everything.
 *
 * @param  string $provider
 * @return \Illuminate\Http\RedirectResponse
 */
public function redirectToProvider($provider)
{
    if ($provider === 'twitter') {
        $tempId = Str::random(40);

        $connection = new TwitterOAuth(config('services.twitter.client_id'), config('services.twitter.client_secret'));
        $requestToken = $connection->oauth('oauth/request_token', array('oauth_callback' => config('services.twitter.callback_url').'?user='.$tempId));

        \Cache::put($tempId, $requestToken['oauth_token_secret'], 86400); // 86400 seconds = 1 day

        $url = $connection->url('oauth/authorize', array('oauth_token' => $requestToken['oauth_token']));
    } else {
        $url = Socialite::driver($provider)->stateless()->redirect()->getTargetUrl();
    }

    return [
        'url' => $url,
    ];
}

/**
 * Obtain the user information from the provider.
 *
 * @param  string $driver
 * @return \Illuminate\Http\Response
 */
public function handleProviderCallback(Request $request, $provider)
{
    if ($provider === 'twitter') {
        $connection = new TwitterOAuth(config('services.twitter.client_id'), config('services.twitter.client_secret'), $request->oauth_token, \Cache::get($request->user));
        $access_token = $connection->oauth('oauth/access_token', ['oauth_verifier' => $request->oauth_verifier]);

        $connection = new TwitterOAuth(config('services.twitter.client_id'), config('services.twitter.client_secret'), $access_token['oauth_token'], $access_token['oauth_token_secret']);
        $user = $connection->get('account/verify_credentials', ['include_email' => 'true']);
        $user->token = $access_token['oauth_token']; // this is used in the findOrCreateUser and createUser function
    } else {
        $user = Socialite::driver($provider)->stateless()->user();
    }
    $user = $this->findOrCreateUser($provider, $user);

    $this->guard()->setToken(
        $token = $this->guard()->login($user)
    );

    return view('oauth/callback', [
        'token' => $token,
        'token_type' => 'bearer',
        'expires_in' => $this->guard()->getPayload()->get('exp') - time(),
    ]);
}

如果您仔细观察,将会看到\Cache::put()\Cache::get()。这样做的目的是向handleProviderCallback方法提供Twitter访问令牌。 Twitter将'?user='.$tempId附加到回调请求,因此您可以使用`$ request-> user查找访问令牌的临时用户ID。

阅读Laravel文档以了解更多信息。默认的.env变量CACHE_DRIVER=file,因此Cache :: put()会将文件放置在某处。

'include_email' => 'true'是您指示Twitter包括用户电子邮件地址的方式,并且仅当您在Twitter应用设置区域中启用电子邮件地址支持时,此方法才有效。为此,需要有一个服务条款页面和一个隐私策略页面。

我相信我的Socialite安装基本上是正常的;您可以查看这个示例仓库,我从中得到了所有东西(请注意Laravel API + Vue SPA):https://github.com/cretueusebiu/laravel-vue-spa

.env

# localhost
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
GITHUB_CALLBACK_URL=https://something.test/api/oauth/github

TWITTER_CLIENT_ID=
TWITTER_CLIENT_SECRET=
TWITTER_CALLBACK_URL=https://something.test/api/oauth/twitter/callback

注意:我创建了两个GitHub应用程序和两个Twitter应用程序:一个用于localhost,一个用于生产。唯一的区别是域。这将允许您在本地测试oauth登录。

config / services.php

    'github' => [
        'client_id' => env('GITHUB_CLIENT_ID'),
        'client_secret' => env('GITHUB_CLIENT_SECRET'),
        'callback_url' => env('GITHUB_CALLBACK_URL'),
    ],

    'twitter' => [
        'client_id' => env('TWITTER_CLIENT_ID'),
        'client_secret' => env('TWITTER_CLIENT_SECRET'),
        'callback_url' => env('TWITTER_CALLBACK_URL'),
    ],

请不要忘记使用这些oauth密钥名称来更新您的.env.example文件。

也不要忘记检查示例存储库,因为我在此基础上添加了Twitter内容。