J7mbo / twitter-api-php

The simplest PHP Wrapper for Twitter API v1.1 calls
MIT License
1.82k stars 800 forks source link

Could not authenticate you in DM #257

Open vishnu1991 opened 6 years ago

vishnu1991 commented 6 years ago

Error: 32 Could not authenticate you. To Send Direct messages using "POST direct_messages/events/new (message_create)" Ref: https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-event

$settings = array(
    'oauth_access_token' => "************",
    'oauth_access_token_secret' => "*************",
    'consumer_key' => "************",
    'consumer_secret' => "************"
);

$url = 'https://api.twitter.com/1.1/direct_messages/events/new.json';
$requestMethod = 'POST';
//https://api.twitter.com/1/direct_messages/new.format
$postfields = array (
  'event' => 
  array (
    'type' => 'message_create',
    'message_create' => 
    array (
      'target' => 
      array (
        'recipient_id' => '123456',
      ),
      'message_data' => 
      array (
        'text' => 'Hello World!',
      ),
    ),
  ),
);

/*  Calling TwiiterAPI class */
$twitter = new TwitterAPIExchange($settings);
echo $twitter->buildOauth($url, $requestMethod)
             ->setPostfields($postfields)
             ->performRequest();

P.S : Sending Direct message using "POST direct_messages/new" works fine but "POST direct_messages/events/new (message_create)" throws error

sadlig commented 6 years ago

You need to encode your data to post in json like this : $return_api = $this->twitter->buildOauth($url, $requestMethod)->performRequest(true, [ CURLOPT_HTTPHEADER => array('Content-Type:application/json'), CURLOPT_POSTFIELDS => json_encode($postfields) ]);

But adding optionnal header generates a bug, I fix it in this PR : https://github.com/J7mbo/twitter-api-php/pull/266

khurshid-alam commented 6 years ago

@sadlig Same issue. I tried your solution but getting the same error.

vadim-gutyrchik commented 5 years ago

was getting "Could not authenticate you" issue too when posting tweets with images; however, posting tweet alone worked, and posting images alone worked too

at the end have found out that problem was with media_id

had such fragment of code:

$post_results_decoded = json_decode($post_results, true);
$media_id = $post_results_decoded['media_id'];

if getting media_id this way, it came as a float number, and got rounded; the error message was related to the issue that twitter cannot find if i have right to post media with this rounded media_id

than i have changed the fragment above to:

$post_results_decoded = json_decode($post_results, true, 512, JSON_BIGINT_AS_STRING);
$media_id = $post_results_decoded['media_id'];

and it works now

hopefully, this helps someone...

ZarchiMohammad commented 3 years ago

@vishnu1991 Were you able to solve the problem? I have a similar problem, what should I do? {"errors":[{"code":215,"message":"Bad Authentication data."}]}