我正尝试使用“仅应用程序身份验证”,如此处所述:
https://developer.twitter.com/en/docs/basics/authentication/overview/application-only
我正在使用以下PHP代码这样做。
if(empty($_COOKIE['twitter_auth'])) {
require '../../social_audit_config/twitter_config.php';
$encoded_key = urlencode($api_key);
$encoded_secret = urlencode($api_secret);
$credentials = $encoded_key.":".$encoded_secret;
$encoded_credentials = base64_encode($credentials);
$request_headers = array(
'Host: api.twitter.com',
'User-Agent: BF Sharing Report',
'Authorization: Basic '.$encoded_credentials,
'Content-Type: application/x-www-form-urlencoded;charset=UTF-8',
'Content-Length: 29',
'Accept-Encoding: gzip'
);
print_r($request_headers);
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, 'https://api.twitter.com/oauth2/token');
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
$attempt_auth = curl_exec($ch);
print_r($attempt_auth);
}
它应该返回其中包含令牌的JSON,但相反,它返回gobbledygook,如下图所示:
我确定我错过了一些非常简单的步骤,我在哪里出错了?
如果我发送不带标头的curl请求,它会按预期返回JSON格式的错误,那么我的标头有问题吗?
答案 0 :(得分:1)
您这里的选择很少。与其直接设置标题,不如在下面使用
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
如果直接设置标题,则应该使用
print_r(gzdecode($attempt_auth));
也请参见以下主题