Skip to content

Commit ea9288a

Browse files
authored
Add Twitter OAuth2 provider (#574)
1 parent 4e6f7e4 commit ea9288a

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed

src/SocialiteManager.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
use Laravel\Socialite\Two\GitlabProvider;
1414
use Laravel\Socialite\Two\GoogleProvider;
1515
use Laravel\Socialite\Two\LinkedInProvider;
16+
use Laravel\Socialite\Two\TwitterProvider as TwitterOAuth2Provider;
1617
use League\OAuth1\Client\Server\Twitter as TwitterServer;
1718

1819
class SocialiteManager extends Manager implements Contracts\Factory
@@ -112,6 +113,20 @@ protected function createGitlabDriver()
112113
)->setHost($config['host'] ?? null);
113114
}
114115

116+
/**
117+
* Create an instance of the specified driver.
118+
*
119+
* @return \Laravel\Socialite\Two\AbstractProvider
120+
*/
121+
protected function createTwitterOAuth2Driver()
122+
{
123+
$config = $this->config->get('services.twitter');
124+
125+
return $this->buildProvider(
126+
TwitterOAuth2Provider::class, $config
127+
);
128+
}
129+
115130
/**
116131
* Build an OAuth 2 provider instance.
117132
*

src/Two/TwitterProvider.php

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
<?php
2+
3+
namespace Laravel\Socialite\Two;
4+
5+
use Illuminate\Support\Arr;
6+
7+
class TwitterProvider extends AbstractProvider
8+
{
9+
/**
10+
* The scopes being requested.
11+
*
12+
* @var array
13+
*/
14+
protected $scopes = ['users.read', 'tweet.read'];
15+
16+
/**
17+
* Indicates if PKCE should be used.
18+
*
19+
* @var bool
20+
*/
21+
protected $usesPKCE = true;
22+
23+
/**
24+
* The separating character for the requested scopes.
25+
*
26+
* @var string
27+
*/
28+
protected $scopeSeparator = ' ';
29+
30+
/**
31+
* {@inheritdoc}
32+
*/
33+
public function getAuthUrl($state)
34+
{
35+
return $this->buildAuthUrlFromBase('https://twitter.com/i/oauth2/authorize', $state);
36+
}
37+
38+
/**
39+
* {@inheritdoc}
40+
*/
41+
protected function getTokenUrl()
42+
{
43+
return 'https://api.twitter.com/2/oauth2/token';
44+
}
45+
46+
/**
47+
* {@inheritdoc}
48+
*/
49+
protected function getUserByToken($token)
50+
{
51+
$response = $this->getHttpClient()->get('https://api.twitter.com/2/users/me', [
52+
'headers' => ['Authorization' => 'Bearer '.$token],
53+
'query' => ['user.fields' => 'profile_image_url'],
54+
]);
55+
56+
return Arr::get(json_decode($response->getBody(), true), 'data');
57+
}
58+
59+
/**
60+
* {@inheritdoc}
61+
*/
62+
protected function mapUserToObject(array $user)
63+
{
64+
return (new User)->setRaw($user)->map([
65+
'id' => $user['id'],
66+
'nickname' => $user['username'],
67+
'name' => $user['name'],
68+
'avatar' => $user['profile_image_url'],
69+
]);
70+
}
71+
}

0 commit comments

Comments
 (0)