twitteroauth icon indicating copy to clipboard operation
twitteroauth copied to clipboard

Failed to Post Tweet, HTTP error code: 404

Open Nisar2001 opened this issue 1 year ago • 9 comments

I am trying to do Tweet via my wordpress, I have created a plugin and in plugin folder, I have used composer to import TwitterOAuth library. Now when I run, I get error Failed to Tweet, and HTTP error code: 404.
404 plugin vendor

here is my code:

<?php

require_once plugin_dir_path(__FILE__) . '/vendor/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;

// rest of the code for Button creating and on Click event, tweetViaOAuth1 will be called. 

function tweetViaOAuth1($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret, $tweet) {
    // Authenticate with Twitter using OAuth 1.0a
    $connection = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
    $tweetStatus = $connection->post('statuses/update', ['status' => $tweet]);

    if ($connection->getLastHttpCode() == 200 && !empty($tweetStatus->id_str)) {
        echo "Tweet posted successfully with ID: " . $tweetStatus->id_str . "\n";
    } else {
        echo "Failed to post tweet.\n";
        if (!empty($tweetStatus->errors)) {
            echo "Error message: " . $tweetStatus->errors[0]->message . "\n";
        } else {
            echo "HTTP error code: " . $connection->getLastHttpCode() . "\n";
        }
    }
}
$consumerKey = '7xxxxxxxxxxxxxxxxxxxxxxxxxxx';
$consumerSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx';
$accessToken = '1xxxxxxxxxxxxxxxxxxxxxxxxxxx';
$accessTokenSecret = '7xxxxxxxxxxxxxxxxxxxxxxxxxxxhU';

$tweet = 'Hello Twitter! This is a test tweet via OAuth 1.0a.';

tweetViaOAuth1($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret, $tweet);

Please guide me on what is the problem and how can i fix.

Nisar2001 avatar Feb 08 '24 18:02 Nisar2001

I don't think Twitter let's people use the old v1 API anymore. Try the v2 API.

I think it would look something like:

$connection->setApiVersion('2'); // only needed if not on the latest version of TwitterOAuth
$result = $connection->post("tweets", ["text" => $text], true);

abraham avatar Feb 11 '24 18:02 abraham

Hello Abraham sir,

I tried the code that you gave idea in the above response. It did not work. :(

Can you please share a working code entirely that just Prints a variable value to Twitter,, such as this variable content should be post to my twitter:

$MyTweet = 'This is my first tweet and here is my website, $WebsiteDomain #FollowMe';

Nisar2001 avatar Feb 12 '24 01:02 Nisar2001

Even have tried totally new code:

function tweetViaOAuth2($bearerToken, $tweet) {

    $data = array(
        'text' => $tweet
    );

    $headers = array(
        'Authorization: Bearer ' . $bearerToken,
        'Content-Type: application/json'
    );

    $postFields = json_encode($data);

    $endpoint = 'https://api.twitter.com/2/tweets';

    $ch = curl_init();

    curl_setopt_array($ch, array(
        CURLOPT_URL => $endpoint,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postFields,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HEADER => false
    ));

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    curl_close($ch);

    if ($httpCode == 201) {
        echo "Tweet posted successfully.\n";
    } else {
        echo "Failed to post tweet.\n";
        echo "HTTP error code: " . $httpCode . "\n";
        $errorMsg = 'Error posting tweet: ' . $response;
        auto_tweet_log($errorMsg);
    }
}

$bearerToken = "AxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxGpIjfRMn";
$tweet = 'Hello Twitter! This is a test tweet via OAuth 2.0.';

tweetViaOAuth2($bearerToken, $tweet);

getting this error back :

Error posting tweet: {
  "title": "Unsupported Authentication",
  "detail": "Authenticating with OAuth 2.0 Application-Only is forbidden for this endpoint.  Supported authentication types are [OAuth 1.0a User Context, OAuth 2.0 User Context].",
  "type": "https://api.twitter.com/2/problems/unsupported-authentication",
  "status": 403
}

Nisar2001 avatar Feb 12 '24 02:02 Nisar2001

I don't have any Twitter apps to validate snippets. https://github.com/abraham/twitteroauth/issues/1192#issuecomment-1673101978 is confirming that the following should work though.

$connection->setApiVersion('2');
$result = $connection->post("tweets", ["text" => $text], true);

Bearer tokens are not valid for posting tweets. You have to go through the user oauth flow https://developer.twitter.com/en/docs/authentication/oauth-1-0a/obtaining-user-access-tokens

abraham avatar Feb 12 '24 03:02 abraham

Just try this:

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$connection->setApiVersion('2');
$result = $connection->post('tweets', ['text' => "Hi there!"], true);

echo $connection->getLastHttpCode() == 201 ? "Succes!" : "Failed!";

// get result:
print_r($result);

frankboelen avatar Feb 13 '24 10:02 frankboelen

Just try this:

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$connection->setApiVersion('2');
$result = $connection->post('tweets', ['text' => "Hi there!"], true);

echo $connection->getLastHttpCode() == 201 ? "Succes!" : "Failed!";

// get result:
print_r($result);

received this: Failed!stdClass Object ( [title] => Forbidden [status] => 403 [detail] => Your client app is not configured with the appropriate oauth1 app permissions for this endpoint. [type] => https://api.twitter.com/2/problems/oauth1-permissions )

Nisar2001 avatar Feb 13 '24 17:02 Nisar2001

I suggest to configure your App with the Twitter Dev platform. Remember to regenerate your keys after changing your configuration.

frankboelen avatar Feb 14 '24 09:02 frankboelen

I suggest to configure your App with the Twitter Dev platform. Remember to regenerate your keys after changing your configuration.

I have generated new app after removing old one from my twitter and i am building an wordpress plugin that use my Twitter Auth to send my new posts automatically to my twitter. (I dont want to use any available plugins that do the same, becuase i have something in mind that only can be achieved by custom plugin.)

Nisar2001 avatar Feb 16 '24 04:02 Nisar2001

I would recommend posting to https://devcommunity.x.com/ regarding correct application configuration. Twitter seems to keep changing those.

abraham avatar Feb 18 '24 02:02 abraham

I suggest to configure your App with the Twitter Dev platform. Remember to regenerate your keys after changing your configuration.

I have generated new app after removing old one from my twitter and i am building an wordpress plugin that use my Twitter Auth to send my new posts automatically to my twitter. (I dont want to use any available plugins that do the same, becuase i have something in mind that only can be achieved by custom plugin.)

@Nisar2001 Ensure your app is on version 2 project in twitter dev console before you use the v2 api

josmarh avatar Feb 23 '24 14:02 josmarh

I suggest to configure your App with the Twitter Dev platform. Remember to regenerate your keys after changing your configuration.

I have generated new app after removing old one from my twitter and i am building an wordpress plugin that use my Twitter Auth to send my new posts automatically to my twitter. (I dont want to use any available plugins that do the same, becuase i have something in mind that only can be achieved by custom plugin.)

@Nisar2001 Ensure your app is on version 2 project in twitter dev console before you use the v2 api

v2

I think, its already version 2 project and v2 API.

Nisar2001 avatar Feb 25 '24 01:02 Nisar2001

I think you should test it outside the wordpress app you are working on, i mean setup something basic and test the package following the docs on twitteroauth.com

josmarh avatar Feb 25 '24 21:02 josmarh

Hi guys! I can confirm that the package is working properly with this code:

$this->twitterOAuth = new TwitterOAuth($oConfig->apiKey, $oConfig->apiSecret, $oConfig->accessToken, $oConfig->accessTokenSecret);
$this->twitterOAuth->setApiVersion('2');
$this->twitterOAuth->post("tweets", ["text" => $message]);

You can close the issue, because it's not a bug in the package, but a misconfig of the dev account.

I know because I had the same problem. The issue is due to the "Access Token and Secret" being Created with Read-only permission instead of the correct "Read and write"

image

To fix it, you have to go back to Settings" and run the User authentication set up`.

image

From there, you have to set Read and write... BUT! Before you can save, you have to fill a couple of others mandatory fields. The Callback URL field is mandatory, but not really needed: just input any URL

image

HTH

ZaneCEO avatar Mar 31 '24 16:03 ZaneCEO