我正在使用 BirdElephant 在 Twitter 上发布一些内容。
这是我的职责:
private function postToTwitter($status, $imagePath)
{
$credentials = array(
//these are preset values that you can obtain from developer portal:
'bearer_token' => env('TWITTER_BEARER_TOKEN'), // OAuth 2.0 Bearer Token requests
'consumer_key' => env('TWITTER_CONSUMER_KEY'), // identifies your app, always needed
'consumer_secret' => env('TWITTER_CONSUMER_SECRET'), // app secret, always needed
//this is a value created duting an OAuth 2.0 with PKCE authentication flow:
//'auth_token' => xxxxxx // OAuth 2.0 auth token
//these are values created during an OAuth 1.0a authentication flow:
'token_identifier' => env('TWITTER_CLIENT_ID'), // OAuth 1.0a User Context requests
'token_secret' => env('TWITTER_CLIENT_SECRET'), // OAuth 1.0a User Context requests
);
$twitter = new BirdElephant($credentials);
/*
$image = $twitter->tweets()->upload($imagePath);
$media = (new Media)->mediaIds([$image->media_id_string]);
*/
$tweet = (new Tweet)->text($status);//->media($media);
$response = $twitter->tweets()->tweet($tweet);
if ($response->getLastHttpCode() == 200) {
$tweetId = $response->id_str;
$tweetUrl = "https://twitter.com/{$response->user->screen_name}/status/{$tweetId}";
Log::info("Tweet posted successfully: {$tweetUrl}");
return ['content' => $status, 'url' => $tweetUrl];
} else {
Log::error('Failed to post tweet.', ['response' => $response]);
throw new Exception('Failed to post tweet.');
}
}
运行上面的代码时出现此错误:
Client error: POST https://api.twitter.com/2/tweets resulted in a 401 Unauthorized response:
{
"title": "Unauthorized",
"type": "about:blank",
"status": 401,
"detail": "Unauthorized"
}
我重新生成了所有 Twitter 密钥并将它们正确保存到我的 .env 文件中。
有什么建议我做错了什么吗?