创建应用
APPID 和 相关回调配置
重新设置api key 和 api secret
设置回调和网址 还有 APP的类型
拿到ClientID 和 Client Secret
源码实现
- 获取Twitter 的登录地址
php
public function twitterUrl()
{
global $db,$request,$comId;
require "inc/twitter_client/twitteroauth.php";
// Create TwitterOAuth obj instance
$twitteroauth = new \TwitterOAuth('配置 API key', '配置 API Key Secret');
// Requesting authentication tokens, the parameter is the URL we will be redirected to
$redirectUrl = 'https://tocmodels.com/Twitter';
$request_token = $twitteroauth->getRequestToken($redirectUrl);
// save to mysql 记录token和token_secret
$log = array(
'oauth_token' => $request_token['oauth_token'],
'oauth_token_secret' => $request_token['oauth_token_secret'],
'status' => 0,
'user_id' => 0,
'screen_name' => '',
'dtTime' => date("Y-m-d H:i:s")
);
$db->insert_update("twitter_token_log", $log, "id");
// no error
if($twitteroauth->http_code==200){
// Let's generate the URL and redirect
$loginUrl = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);
$return['code'] = 1;
$return['message'] = '获取成功';
$return['data'] = array();
$return['data']['url'] = $loginUrl;
return json_encode($return,JSON_UNESCAPED_UNICODE);
} else {
// error
return '{"code":0,"message":"Get Twitter login url fail!"}';
}
}
- 回调跳转链接上有两个参数
oauth_verifier
和oauth_token
,通过两个值获取用户标识
php
public function twitterLogin()
{
global $db,$request,$comId;
require "inc/twitter_client/twitteroauth.php";
$oauth_verifier = $request['oauth_verifier'];
if(empty($oauth_verifier)) return '{"code":0,"message":"oauth_verifier 为必传参数"}';
$oauth_token = $request['oauth_token'];
if(empty($oauth_token)) return '{"code":0,"message":"oauth_token 为必传参数"}';
$log = $db->get_row("select * from twitter_token_log where oauth_token = '$oauth_token' and status = 0 ");
if(!$log) return '{"code":0,"message":"无效的 oauth_token "}';
$oauth_token_secret = $log->oauth_token_secret;
//api key 和 api key secret
$twitteroauth = new \TwitterOAuth('配置 api key', 'api key secret ', $oauth_token, $oauth_token_secret);
$access_token = $twitteroauth->getAccessToken($oauth_verifier);
$twitter_uid = $access_token['user_id'];//Twitter 的用户id
$screen_name = $access_token['screen_name'];//Twitter 的用户 名称
$user = $db->get_row("select * from users where twitter_uid = '$twitter_uid' ");
//TODO 剩下就是存入自己的数据和登录逻辑
}