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?

This is just an initial observation / question, but why are you running every step through rawurlencode? Look at the definition of the function - every time you run it on a string it will encode everything non numeric except -_.~ ... so if you run it once and it returns %20 for example and you run it again on that string, that %20 will become like %blah%20 or whatever. If it were me, I would not have any rawurlencode in your sign function. Build your query string in plain ole English, like you are typing into the browser, then right before you send it you encode it. Or better yet use curl_escape.

commented: Yay +12

To generate an OAuth signature for Twitter API calls in PHP:

Install an OAuth library like abraham/twitteroauth.
Set up your Twitter API keys (consumer key, secret, access token).
Generate the OAuth signature using your API keys and request details.
Send the request using the signature for authentication.
Using a library like twitteroauth simplifies the process without needing to manually write the signature code.

commented: He said he didn't want to use any libraries +3
commented: Boo -3

I have found meaningful conversation thanks for sharing.

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.