twitter验证
In the previous parts of this series, we created our initial interfaces, set up our Google+ login functionality and talked about how we can merge our accounts together. In this article, we will integrate Twitter and Facebook within our application. You will see a lot of similarities with the Google+ article, so if you could follow that one easily, you won’t have much trouble with this one. If you haven’t read that article yet, I suggest you read it first before continuing this article.
在本系列的前一部分中,我们创建了初始界面,设置了Google+登录功能,并讨论了如何将帐户合并在一起。 在本文中,我们将Twitter和Facebook集成到我们的应用程序中。 您会发现与Google+文章有很多相似之处,因此,如果您可以轻松地关注该文章 ,那么在这篇文章中就不会有太多麻烦。 如果您尚未阅读该文章,建议您在继续本文之前先阅读该文章。
You can view the code for all the articles on this Github page.
您可以在Github页面上查看所有文章的代码。
Once again, we start off by creating the following directory: src/SitePoint/SocialLogin/Twitter. Within this directory, we create the TwitterLogin class. This class implements the SocialLoginInterface interface which we created in the first article. Make sure a property called service is available to store our service in.
再次,我们从创建以下目录开始: src/SitePoint/SocialLogin/Twitter 。 在此目录中,我们创建TwitterLogin类。 此类实现了我们在第一篇文章中创建的SocialLoginInterface接口。 确保有一个称为service的属性可用于存储我们的服务。
Like Google+, Twitter has some specific needs to make sure we can log in. So make sure we have the following 3 properties present in the class:
像Google+一样,Twitter有一些特定的需求来确保我们可以登录。因此,请确保我们在类中具有以下3个属性:
Client id 客户编号 key 键 callback URL 回调网址Since all 3 properties are required for our application to work, our constructor will receive these 3 variables as parameters and set the properties.
由于应用程序必须具备所有3个属性,因此构造函数将接收这3个变量作为参数并设置属性。
Up until now, your code should look the same as the first example in the Google+ article.
到目前为止,您的代码应与Google+文章中的第一个示例相同。
Our next step is to create our Twitter service. We will be using the same OAuth library and will set up a connection within the init method.
我们的下一步是创建我们的Twitter服务。 我们将使用相同的OAuth库,并将在init方法内建立连接。
Before we can start, we have to add some use statements to the top of our class.
在开始之前,我们必须在类的顶部添加一些use语句。
use OAuth\ServiceFactory; use OAuth\OAuth1\Service\Twitter; use OAuth\Common\Storage\Session; use OAuth\Common\Consumer\Credentials;Everything for our init method is now present. Time to set up our connection with Twitter. We do this with the basic examples of the OAuth library we are using.
现在,我们的init方法的所有内容都已存在。 是时候建立我们与Twitter的联系了。 我们使用正在使用的OAuth库的基本示例进行此操作。
/** * Initializes our service */ public function init() { $storage = new Session(); $serviceFactory = new ServiceFactory(); $credentials = new Credentials($this->clientId, $this->key, $this->callbackUrl); $this->service = $serviceFactory->createService('twitter', $credentials, $storage); return $this; }Our service is set now, so we can now continue by filling out other methods from the interface. We will start off with the getLoginUrl method. This method will return a URL which you will be redirecting your user to.
现在已经设置了我们的服务,因此我们现在可以通过从界面填写其他方法来继续。 我们将从getLoginUrl方法开始。 此方法将返回一个URL,您将把用户重定向到该URL。
/** * Returns the login url for the social network * * @return string */ public function getLoginUrl() { $token = $this->service->requestRequestToken(); return $this->service->getAuthorizationUri(array('oauth_token' => $token->getRequestToken())); }You might notice that this method (and the following one which we will discuss) is slightly different from the Google+ article. This is due to the fact that Google+ uses OAuth 2, while Twitter uses OAuth 1. Twitter was one of the first companies to use OAuth, since the original creator of OAuth was working at Twitter at that time. Twitter is still using OAuth 1, although they are making progress moving to OAuth 2.
您可能会注意到,此方法(以及我们将讨论的以下方法)与Google+文章略有不同。 这是由于Google+使用OAuth 2,而Twitter使用OAuth1。Twitter是最早使用OAuth的公司之一,因为OAuth的原始创建者当时在Twitter工作。 微博仍使用OAuth 1中,尽管它们是进取移动到OAuth 2。
The next method to define is the loginCallback method. When a user accepts Twitter sharing data with your application, the user will be redirected back to the URL you defined as the callbackUrl. When the user is requesting that URL, you should call the loginCallback method from this class.
下一个要定义的方法是loginCallback方法。 当用户接受Twitter与您的应用程序共享数据时,该用户将被重定向回您定义为callbackUrl的URL。 当用户请求该URL时,您应该从此类中调用loginCallback方法。
If everything went well, we can now retrieve data from Twitter.
如果一切顺利,我们现在可以从Twitter检索数据。
/** * Handles the login callback from the social network * * @return SocialUserInterface */ public function loginCallback() { $storage = new Session(); $token = $storage->retrieveAccessToken('Twitter'); $this->service->requestAccessToken( $_GET['oauth_token'], $_GET['oauth_verifier'], $token->getRequestTokenSecret() ); $userData = json_decode($this->service->request('account/verify_credentials.json'), true); $twitterUser = new TwitterUser($userData); return $twitterUser; }This time we are using a class named TwitterUser here and we are returning a class with the interface SocialUserInterface. However, this class is not yet present. Time to create it!
这次,我们在这里使用一个名为TwitterUser的类,并返回一个带有SocialUserInterface接口的SocialUserInterface 。 但是,该课程尚不存在。 是时候创建它了!
Twitter returns the data back in a different way than Google+, so we have to normalize again. We need to create a class named TwitterUser which will implement the SocialUserInterface we created in the first article.
Twitter以不同于Google+的方式返回数据,因此我们必须再次进行规范化。 我们需要创建一个名为TwitterUser的类,该类将实现我们在第一篇文章中创建的SocialUserInterface 。
The constructor of this class expects the raw data of Twitter in this case. In every getter, we will retrieve the data we want from the raw data. In the end, your TwitterUser class could look like this.
在这种情况下,此类的构造函数需要Twitter的原始数据。 在每个获取器中,我们将从原始数据中检索所需的数据。 最后,您的TwitterUser类可能如下所示。
<?php namespace SitePoint\SocialLogin\Twitter; use SitePoint\SocialLogin\Interfaces\SocialUserInterface; class TwitterUser implements SocialUserInterface { /** * @var mixed user data */ private $userData; /** * Constructor. * * @param $userData mixed Raw social network data for this particular user */ public function __construct($userData) { $this->userData = $userData; } /** * Get the provider name * * @return string */ public function getProvider() { return "twitter"; } /** * Get the UID of the user * * @return string */ public function getUid() { if(array_key_exists('id', $this->userData)) { return $this->userData['id']; } return null; } /** * Get the first name of the user * * @return string */ public function getFirstname() { if(array_key_exists('name', $this->userData)) { list($firstname, $lastname) = explode(" ", $this->userData['name']); // TODO: Of course you have to make this smarter return $firstname; } return null; } /** * Get the last name of the user * * @return string */ public function getLastname() { if(array_key_exists('name', $this->userData)) { list($firstname, $lastname) = explode(" ", $this->userData['name']); // TODO: Of course you have to make this smarter return $lastname; } return null; } /** * Get the username * * @return string */ public function getUsername() { if(array_key_exists('screen_name', $this->userData)) { return $this->userData['screen_name']; } return null; } /** * Get the emailaddress * * @return string */ public function getEmailAddress() { return null; } /** * Get the city * * @return string */ public function getCity() { if(array_key_exists('location', $this->userData)) { return $this->userData['location']; } return null; } /** * Get the birthdate * * @return string */ public function getBirthDate() { return null; } /** * Get the gender * * @return string */ public function getGender() { return null; } }You might notice that we have a lot less information than with Google+. Twitter just doesn’t share as much info. For instance, we are missing the email address, while this is one of the most common fields you would like to have within your application.
您可能会注意到,与Google+相比,我们提供的信息要少得多。 Twitter只是分享的信息不多。 例如,我们缺少电子邮件地址,而这是您希望在应用程序中拥有的最常见字段之一。
The only thing you can do is, after a login with Twitter, ask the user to fill in his email address and save it to your database. Other than that, you can try to merge a Twitter account with an already given account like in the previous part of this series.
您唯一可以做的是,在使用Twitter登录后,要求用户填写他的电子邮件地址并将其保存到您的数据库中。 除此之外,您可以尝试将Twitter帐户与一个给定的帐户合并,如本系列前面的部分。
With the knowledge you gathered from the Google+ and Twitter explanation, it should be easy for you to set the Facebook version up. Here you have the full implementation for the login class.
有了从Google+和Twitter解释中收集到的知识,就可以轻松设置Facebook版本。 在这里,您具有登录类的完整实现。
<?php namespace SitePoint\SocialLogin\Facebook; use SitePoint\SocialLogin\Interfaces\SocialLoginInterface; use OAuth\ServiceFactory; use OAuth\OAuth2\Service\Facebook; use OAuth\Common\Storage\Session; use OAuth\Common\Consumer\Credentials; class FacebookLogin implements SocialLoginInterface { /** * Facebook service * * @var string */ protected $service; /** * OAuth client ID * * @var string */ protected $clientId; /** * OAuth key * * @var string */ protected $key; /** * Callback url * * @var string */ protected $callbackUrl; /** * Constructor. * * @param $clientId string * @param $key string * @param $callbackUrl string */ public function __construct($clientId, $key, $callbackUrl) { $this->clientId = $clientId; $this->key = $key; $this->callbackUrl = $callbackUrl; } /** * Initializes our service */ public function init() { $storage = new Session(); $serviceFactory = new ServiceFactory(); $credentials = new Credentials($this->clientId, $this->key, $this->callbackUrl); $this->service = $serviceFactory->createService( 'facebook', $credentials, $storage, array( Facebook::SCOPE_EMAIL, Facebook::SCOPE_USER_BIRTHDAY, Facebook::SCOPE_USER_LOCATION ) ); return $this; } /** * Returns the login url for the social network * * @return string */ public function getLoginUrl() { return $this->service->getAuthorizationUri(); } /** * Handles the login callback from the social network * * @param string $accessCode * * @return SocialUserInterface */ public function loginCallback($accessCode) { $token = $this->service->requestAccessToken($accessCode); // Send a request with it $userData = json_decode($this->service->request('/me'), true); $facebookUser = new FacebookUser($userData); return $facebookUser; } }What you might notice is that I defined some scopes when creating the Facebook service. By defining these scopes, I can get back some extra details from the user. In this case, I am also collecting the email address, birthday and location. Do note that the more data you gather, the more chance you have a user will refuse to log in with your app.
您可能会注意到,我在创建Facebook服务时定义了一些范围。 通过定义这些范围,我可以从用户那里得到一些额外的细节。 在这种情况下,我还将收集电子邮件地址,生日和位置。 请注意,您收集的数据越多,用户拥有拒绝使用您的应用程序登录的机会就越大。
The user class is even easier and doesn’t contain any surprises. When done, it should look like this.
用户类更加容易,并且没有任何惊喜。 完成后,它应该看起来像这样。
<?php namespace SitePoint\SocialLogin\Facebook; use SitePoint\SocialLogin\Interfaces\SocialUserInterface; class FacebookUser implements SocialUserInterface { /** * @var mixed user data */ private $userData; /** * Constructor. * * @param $userData mixed Raw social network data for this particular user */ public function __construct($userData) { $this->userData = $userData; } /** * Get the provider name * * @return string */ public function getProvider() { return "facebook"; } /** * Get the UID of the user * * @return string */ public function getUid() { if(array_key_exists('id', $this->userData)) { return $this->userData['id']; } return null; } /** * Get the first name of the user * * @return string */ public function getFirstname() { if(array_key_exists('first_name', $this->userData)) { return $this->userData['first_name']; } return null; } /** * Get the last name of the user * * @return string */ public function getLastname() { if(array_key_exists('last_name', $this->userData)) { return $this->userData['last_name']; } return null; } /** * Get the username * * @return string */ public function getUsername() { if(array_key_exists('name', $this->userData)) { return str_replace(" ", "_", $this->userData['name']); } return null; } /** * Get the emailaddress * * @return string */ public function getEmailAddress() { if(array_key_exists('email', $this->userData)) { return $this->userData['email']; } return null; } /** * Get the city * * @return string */ public function getCity() { if(array_key_exists('location', $this->userData)) { return $this->userData['location']; } return null; } /** * Get the birthdate * * @return string */ public function getBirthDate() { if(array_key_exists('birthday', $this->userData)) { return $this->userData['birthday']; } return null; } /** * Get the gender * * @return string */ public function getGender() { if(array_key_exists('location', $this->userData)) { return $this->userData['location']['name']; } return null; } }If you want to run a quick test to try out the code, clone the Github repository to your local computer and switch to the branch named part4. Within this branch, you will see a testTwitter.php and testFacebook.php file. You can fill in the API details from both services and run the file within your browser. When requesting the page, you will be redirected to the social media page, requesting you to share information.
如果要运行快速测试以尝试代码,请将Github存储库克隆到本地计算机,然后切换到名为part4的分支。 在此分支中,您将看到一个testTwitter.php和testFacebook.php文件。 您可以从这两个服务中填写API详细信息,然后在浏览器中运行文件。 请求页面时,您将被重定向到社交媒体页面,要求您共享信息。
When clicking accept, you will be redirected back to the page you configured as callback URL, showing your first and last name.
单击接受时,您将被重定向回您配置为回调URL的页面,显示您的名字和姓氏。
In this article we took the base we set in the previous articles and worked further on that. Next to Google+, we can now also log in with Twitter and Facebook. In all cases, we return a normalized user object, which we can add to our own user system. With this article, we’ve come to the end of this series. Did it give you some insight in how to deal with social networks or framework agnostic packages? Feel free to ask any questions in the comments below!
在本文中,我们采用了先前文章中设定的基础,并对此进行了进一步的研究。 现在,在Google+旁边,我们还可以使用Twitter和Facebook登录。 在所有情况下,我们都返回一个标准化的用户对象,可以将其添加到我们自己的用户系统中。 在本文中,我们到了本系列的结尾。 它是否为您提供了一些有关如何处理社交网络或框架不可知软件包的见解? 随时在下面的评论中提出任何问题!
翻译自: https://www.sitepoint.com/social-network-authentication-twitter-facebook/
twitter验证
相关资源:Twitter api使用例子