I have gathered the following code in an attempt to post to X:
$api_key='xx';
$api_secret="yy";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.twitter.com/oauth2/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/x-www-form-urlencoded',
]);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $api_key.':'.$api_secret);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
$response = curl_exec($ch);
curl_close($ch);
$response=json_decode($response);
$access_token=$response->access_token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.twitter.com/2/tweets');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer '.$access_token,
'Content-Type: application/json',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"text":"Hello, world!"}');
$response = curl_exec($ch);
curl_close($ch);
print_r($response);
I’m getting the access_token but in the end I’m presented the following error: “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].”
Any idea to what I’m doing wrong?