我需要获得推特个人资料。
问题是我在这里没有获得令牌值,但我确实拥有Twitter帐户用户ID。
我们可以根据这些基本数据获得关注者的数量吗?
答案 0 :(得分:0)
无论哪种方式,您都需要令牌,因为需要对Twitter API的所有请求执行身份验证。但要获得该令牌,使用 Application-only authentication 并不复杂。
首先,您需要创建一个 Twitter App 来获取 api密钥和 api secret 。
现在,只需获取持票人令牌:
$encoded_consumer_key = urlencode(CONSUMER_KEY);
$encoded_consumer_secret = urlencode(CONSUMER_SECRET);
$bearer_token = $encoded_consumer_key.':'.$encoded_consumer_secret;
$base64_consumer_key = base64_encode($bearer_token);
$url = "https://api.twitter.com/oauth2/token";
$headers = array(
"POST /oauth2/token HTTP/1.1",
"Host: api.twitter.com",
"User-Agent: Twitter Application-only OAuth App",
"Authorization: Basic ".$base64_consumer_key,
"Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
"Content-Length: 29"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
$header = curl_setopt($ch, CURLOPT_HEADER, 1);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$response = curl_exec ($ch);
curl_close($ch);
$output = explode("\n", $response);
$bearer_token = '';
foreach($output as $line) {
if ($line !== false) {
$bearer_token = $line;
}
}
$bearer_token = json_decode($bearer_token);
$bearer_token = $bearer_token->{'access_token'};
现在您已拥有不记名令牌,您可以使用* user_id *为用户制作lookup:
$url = "https://api.twitter.com/1.1/users/lookup.json";
$formed_url = '?user_id='.$user_id;
$headers = array(
"GET /1.1/users/lookup.json".$formed_url." HTTP/1.1",
"Host: api.twitter.com",
"User-Agent: Twitter Application-only OAuth App",
"Authorization: Bearer ".$bearer_token."",
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url.$formed_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec ($ch);
curl_close($ch);
然后在 $ response (它是 json )中,您拥有所需的一切,包括 followers_count 。