0

I’m trying to post tweets with the Twitter API v2 but have an error. I’m using the TwitterAPIExchange.php library, this works fine when I’m trying to search for Tweets for example with GET. But no luck with POST, see code below also the Manage Tweets doc from Twitter: POST /2/tweets | Docs | Twitter Developer Platform

Maybe I’m missing some parameters after the end point.

include ($_SERVER["DOCUMENT_ROOT"] . "/TwitterAPIExchange.php");
 
$settings = array(
    'oauth_access_token' => "xxxx",
    'oauth_access_token_secret' => "xxxx",
    'consumer_key' => "xxxx",
    'consumer_secret' => "xxxx"
    
);

$url = "https://api.twitter.com/2/tweets";
$requestMethod = 'POST';

$postfields = array('status' => 'This is the text to Tweet');

$twitter = new TwitterAPIExchange($settings);
$response = $twitter->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest();

Errors:

{
errors: [
{
parameters: { },
message: "Requests with bodies must have content-type of application/json."
}
],
title: "Invalid Request",
detail: "One or more parameters to your request was invalid.",
type: "https://api.twitter.com/2/problems/invalid-request"
}

TwitterAPIExchange states it is only for v1.1 API calls, so I assume it isn’t capable of doing requests on the V2 API.

I would use TwitterOAuth if I were you, it works well. It’s easy to install via Composer, goes like this:

use Abraham\TwitterOAuth\TwitterOAuth;

$connection = new TwitterOAuth(consumer_key, consumer_secret,
       access_token, access_token_secret);
$connection->setApiVersion('2');
$query = "tweets";
$queryParams['ids'] = "<comma separated ids in a string>";
$response = $connection->get($query, $queryParams);

Thanks for your reply. TwitterAPIExchange works fine with the V2, I’ve been using it to search tweets. I’ll look intoTwitterOAuth.

As mentioned by @antsstyle, I’ve used the Abraham\TwitterOAuth library instead and was able to send a tweet from the tutorial on this page: https://artisansweb.net/tweet-twitter-php/

1 Like

I am following that article/example right now – artisansweb . net/tweet-twitter-php – but I do not see the Tweets in my timeline. I do not see any errors popping up either which is mysterious. How do I know if this approach is working? I’ve only modified the code slightly to use $_ENV variables.

<?php
require_once "vendor/autoload.php";
include('loadenv.php');
 
use Abraham\TwitterOAuth\TwitterOAuth;
 
define('CONSUMER_KEY', $_ENV['OAUTH_CONSUMER_KEY']);
define('CONSUMER_SECRET', $_ENV['OAUTH_CONSUMER_KEY_SECRET']);
define('ACCESS_TOKEN', $_ENV['OAUTH_ACCESS_TOKEN']);
define('ACCESS_TOKEN_SECRET', $_ENV['OAUTH_ACCESS_TOKEN_SECRET']);
 
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);

$status = 'Check out The Gifted: A Positive Tale of Mutation. ';
$post_tweets = $connection->post("statuses/update", ["status" => $status]);

echo 'Tweet Program Ended';

Your first action here should be to echo or error_log the contents of $post_tweets, so you can see what the output was.

The connection->post call will return an error object if it fails, so this can help you figure out what has failed.

Thank you. I did a var_dump of $post_tweets and this is what I came up with.

Post Tweets is

object(stdClass)#50 (1) { [“errors”]=> array(1) { [0]=> object(stdClass)#55 (2) { [“code”]=> int(89) [“message”]=> string(25) “Invalid or expired token.” } } }

This seems to be a persistent error. I went through the process of creating an app, then recording the various keys and tokens. I put these into the .env file to pull them out here in the script. I’m not sure what is going wrong with this process. Why would the token(s) expire?

Other than the access token being incorrect, the likely cause would be that your ENV variables here are not being initialised properly. Check your loadenv.php file for errors.

Test whether this is the case by temporarily replacing the CONSUMER_KEY in this file etc with the actual values, and see if you still get the same error.

OK. I recreated the app and did the substitution. Now I am getting this error.

object(stdClass)#55 (2) { [“request”]=> string(25) “/1.1/statuses/update.json” [“error”]=> string(34) “Read-only application cannot POST.” }

I don’t think I am setting up the app correctly. I set one up as a Web App with v. 2.0. I don’t even know if that is correct. I thought that 2.0 was for reading or sending tweets. Is there a way I can edit the app or do I need to start all over to do this differently? The documentation is really not clear.

Also now I have Client ID and Client Secret. I don’t know what to do with those.

You don’t need to enable OAuth2 to make use of the V2 API, OAuth 1.0a works fine. You need to set your application to be ‘read and write’ in its settings area.

It doesn’t require re-creating the app, you can adjust this at any time in the app settings.

Thank you so much for your help!
Honestly, I stumbled upon just that solution right before I saw you reply and it appears to be working properly now. I just need to go back and reset it to use $_ENV variables.

I had seen the Read & Write Setting before but I must not have clicked the SAVE button as I kept getting the Read Only message. That must be the default. Thank you again!

Michael J. Scharen
Michael’s Book Corner
@Classic_Sci_Fi

1 Like