Monday, 25 June 2018

Twitter API token request returning gobbledygook

I'm trying to use Application Only Authentication, as described here:
https://developer.twitter.com/en/docs/basics/authentication/overview/application-only
I'm using the following PHP code to do so.
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);

    }

It should return JSON with the token in it, but instead it returns gobbledygook, as seen in the image below:
Return from cURL request
I'm sure I'm missing some very simple step, where am I going wrong?
If I send the curl request without the headers, it returns an error in JSON format as expected, so is there something wrong with my headers?


from Twitter API token request returning gobbledygook

No comments:

Post a Comment