Twitter API 令牌请求返回 gobbledygook

Twitter API token request returning gobbledygook

我正在尝试使用仅应用程序身份验证,如下所述:

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);

    }

它应该 return JSON 带有令牌,但它 return 是官话,如下图所示:

我确定我错过了一些非常简单的步骤,我哪里出错了?

如果我在没有 headers 的情况下发送 curl 请求,它 return 如预期的那样 JSON 格式错误,所以我的 headers 有问题吗?

您在这里几乎没有选择。不要直接设置 header,而是使用下面的

curl_setopt($ch, CURLOPT_ENCODING, 'gzip');

如果你直接设置header那么你应该使用

print_r(gzdecode($attempt_auth));

另请参阅下面的线程

Decode gzipped web page retrieved via cURL in PHP

php - Get compressed contents using cURL