FarrisFahad 103 Junior Poster Premium Member

Hey, I am trying to connect to Twitter API version 1.0.
I want to post a tweet on Twitter using API.
I don't want to use any libraries because i am trying to learn.
I have written some code with the help of ChatGPT.
I am having issues with the signature.
Here is my PHP function for generating a signature ...

function sign($method, $url, $params, $consumerSecret, $tokenSecret = ''){

  $encodedParams = [];
  foreach($params as $key => $value){
     $encodedParams[rawurlencode($key)] = rawurlencode($value);
  }

  ksort($encodedParams);

  $paramString = http_build_query($encodedParams, '', '&', PHP_QUERY_RFC3986);

  $encodedUrl = rawurlencode($url);
  $encodedParamString = rawurlencode($paramString);
  $signatureBaseString = strtoupper($method) . "&" . $encodedUrl . "&" . $encodedParamString;

  $encodedConsumerSecret = rawurlencode($consumerSecret);
  $encodedTokenSecret = rawurlencode($tokenSecret);
  $signingKey = $encodedConsumerSecret . "&" . $encodedTokenSecret;

  $hash = hash_hmac('sha1', $signatureBaseString, $signingKey, true);

  $signature = base64_encode($hash);

  return $signature;

}

And here is my PHP script ...

<?php

$credentials = array(
   'consumer_key' => 'xxxxxx',
   'consumer_secret' => 'xxxxxx',
   'bearer_token' => 'xxxxxx',
   'token_identifier' => 'xxxxxx',
   'token_secret' => 'xxxxxx'
);

$status = 'Hello World!';

$method = "POST";

$url = "https://api.x.com/1.1/statuses/update.json";

$params = [
   "oauth_consumer_key" => $credentials['consumer_key'],
   "oauth_nonce" => bin2hex(random_bytes(16)),
   "oauth_signature_method" => "HMAC-SHA1",
   "oauth_timestamp" => time(),
   "oauth_token" => $credentials['token_identifier'],
   "oauth_version" => "1.0"
];

$signature = $API->sign($method, $url, $params, $credentials['consumer_secret'], $credentials['token_secret']);

$authHeader = 'OAuth ';

$headerParts = [];

foreach ($params as $key => $value) {
   if (strpos($key, 'oauth_') === 0) {
       $headerParts[] = rawurlencode($key) . '="' . rawurlencode($value) . '"';
   }
}

$authHeader .= implode(', ', $headerParts);

$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => http_build_query(['status' => $status]),
    CURLOPT_HTTPHEADER => [
        'Authorization: ' . $authHeader,
        'Content-Type: application/x-www-form-urlencoded',
    ],
]);

$response = curl_exec($curl);

if (curl_errno($curl)) {
    echo 'Curl error: ' . curl_error($curl);
} else {
    echo 'Response: ' . $response;
}

curl_close($curl);

?>

I am getting the following error ...

Response: {"errors":[{"code":215,"message":"Bad Authentication data."}]}

What am I missing?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.