Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
TwitterOAuth
https://twitteroauth.com
Admin
The most popular PHP library for use with the Twitter OAuth REST API.
Tokens:
6,003
Snippets:
63
Trust Score:
8.8
Update:
4 months ago
Context
Chat
Benchmark
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Make a GET Request for Home Timeline Source: https://twitteroauth.com/ Retrieve the user's home timeline using a GET request. This example shows how to specify parameters like count and exclude_replies. ```php $statuses = $connection->get("statuses/home_timeline", ["count" => 25, "exclude_replies" => true]); ``` -------------------------------- ### Make a GET Request using v2 API Source: https://twitteroauth.com/ Access v2 API endpoints by setting the API version. This example demonstrates fetching user data by ID. ```php $connection = new TwitterOAuth(...); $connection->setApiVersion('2'); $response = $connection->get('users', ['ids' => 12]); ``` -------------------------------- ### Make a GET Request for Search Tweets Source: https://twitteroauth.com/ Perform a GET request to search for tweets based on a query. This example searches for tweets containing 'twitterapi'. ```php $statuses = $connection->get("search/tweets", ["q" => "twitterapi"]); ``` -------------------------------- ### Install TwitterOAuth with Composer Source: https://twitteroauth.com/ Use Composer to install the TwitterOAuth library in your project. This is the recommended installation method. ```bash composer require abraham/twitteroauth ``` -------------------------------- ### Bootstrap TwitterOAuth Configuration Source: https://twitteroauth.com/callback Sets up necessary constants for consumer key, secret, and callback URL using environment variables. This is the initial setup before creating a TwitterOAuth instance. ```php require 'vendor/autoload.php'; use Abraham\TwitterOAuth\TwitterOAuth; define('CONSUMER_KEY', getenv('CONSUMER_KEY')); define('CONSUMER_SECRET', getenv('CONSUMER_SECRET')); define('OAUTH_CALLBACK', getenv('OAUTH_CALLBACK')); ``` -------------------------------- ### URL oauth/authorize Source: https://twitteroauth.com/ Builds the URL for user authorization. Used for GET oauth/authorize and GET oauth/authenticate. ```APIDOC ## URL oauth/authorize ### Description Builds the URL for user authorization. Used for GET oauth/authorize and GET oauth/authenticate. ### Method GET ### Endpoint /oauth/authorize ### Parameters #### Query Parameters - **oauth_token** (string) - Required - The request token obtained during the OAuth process. ### Request Example ```json { "example": "$url = $connection->url(\"oauth/authorize\", [\"oauth_token\" => \"EaQLH34YD8pgKkUiSp8RbjjOgNxIYVh7\"]);" } ``` ### Response #### Success Response (200) - **url** (string) - The authorization URL. #### Response Example ```json { "example": "https://api.twitter.com/oauth/authorize?oauth_token=..." } ``` ``` -------------------------------- ### GET v2 users Source: https://twitteroauth.com/ Retrieves user information using the v2 API. Requires setting the API version to '2'. ```APIDOC ## GET v2 users ### Description Retrieves user information using the v2 API. Requires setting the API version to '2'. ### Method GET ### Endpoint https://api.twitter.com/2/users ### Parameters #### Query Parameters - **ids** (integer) - Required - The ID of the user to retrieve. ### Request Example ```json { "example": "$connection = new TwitterOAuth(...);\n$connection->setApiVersion('2');\n$response = $connection->get('users', ['ids' => 12]);" } ``` ### Response #### Success Response (200) - **data** (object) - User object. #### Response Example ```json { "example": "{ \"data\": { ... } }" } ``` ``` -------------------------------- ### Initialize TwitterOAuth Connection Source: https://twitteroauth.com/ Create a new TwitterOAuth connection instance using your consumer keys, access token, and access token secret to start making API requests. ```php $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token_secret); $content = $connection->get("account/verify_credentials"); ``` -------------------------------- ### GET statuses/home_timeline Source: https://twitteroauth.com/ Retrieves the home timeline for the authenticated user. Supports parameters like count and exclude_replies. ```APIDOC ## GET statuses/home_timeline ### Description Retrieves the home timeline for the authenticated user. Supports parameters like count and exclude_replies. ### Method GET ### Endpoint https://api.twitter.com/1.1/statuses/home_timeline.json ### Parameters #### Query Parameters - **count** (integer) - Optional - The number of tweets to retrieve. - **exclude_replies** (boolean) - Optional - Whether to exclude replies from the timeline. ### Request Example ```json { "example": "$statuses = $connection->get(\"statuses/home_timeline\", [\"count\" => 25, \"exclude_replies\" => true]);" } ``` ### Response #### Success Response (200) - **statuses** (array) - A list of tweet objects. #### Response Example ```json { "example": "[Array of tweet objects]" } ``` ``` -------------------------------- ### Generate User Authorization URL Source: https://twitteroauth.com/ Construct the URL where users can authorize your application to access their account. This is used for GET oauth/authorize and GET oauth/authenticate. ```php $url = $connection->url("oauth/authorize", ["oauth_token" => "EaQLH34YD8pgKkUiSp8RbjjOgNxIYVh7"]); ``` -------------------------------- ### Retrieve Access Token from Session Source: https://twitteroauth.com/profile Pulls the user's long-lived access token from PHP session storage. This is a basic example; a production implementation should use a database. ```php $access_token = $_SESSION['access_token']; ``` -------------------------------- ### Make a POST Request to Update Status Source: https://twitteroauth.com/ Post a new tweet to the user's timeline using a POST request. This example updates the status to 'hello world'. ```php $statues = $connection->post("statuses/update", ["status" => "hello world"]); ``` -------------------------------- ### GET search/tweets Source: https://twitteroauth.com/ Searches for tweets based on a query. Uses the v1.1 API. ```APIDOC ## GET search/tweets ### Description Searches for tweets based on a query. Uses the v1.1 API. ### Method GET ### Endpoint https://api.twitter.com/1.1/search/tweets.json ### Parameters #### Query Parameters - **q** (string) - Required - The search query. ### Request Example ```json { "example": "$statuses = $connection->get(\"search/tweets\", [\"q\" => \"twitterapi\"]);" } ``` ### Response #### Success Response (200) - **statuses** (array) - A list of tweet objects matching the query. #### Response Example ```json { "example": "[Array of tweet objects]" } ``` ``` -------------------------------- ### Get Authenticated User Details Source: https://twitteroauth.com/profile Use the 'account/verify_credentials' endpoint to retrieve the authenticated user's account details. Ensure you have an authorized access token. The 'tweet_mode' and 'include_entities' parameters can be set for extended tweet content and entity information. ```php $user = $connection->get('account/verify_credentials', ['tweet_mode' => 'extended', 'include_entities' => 'true']); ``` -------------------------------- ### Get Account Details Source: https://twitteroauth.com/profile Retrieves the authenticated user's Twitter account details using their access token. This method allows fetching extended tweet information and entities. ```APIDOC ## GET /account/verify_credentials ### Description Retrieves the authenticated user's Twitter account details. This endpoint is useful for verifying the identity and profile information of the user associated with the provided access token. ### Method GET ### Endpoint /account/verify_credentials ### Parameters #### Query Parameters - **tweet_mode** (string) - Optional - Specifies the format for Tweet content. Use 'extended' to get the full text of Tweets. - **include_entities** (string) - Optional - Set to 'true' to include entities such as URLs, hashtags, and mentions in the response. ### Response #### Success Response (200) - **id** (integer) - The user's ID. - **id_str** (string) - The user's ID as a string. - **name** (string) - The user's display name. - **screen_name** (string) - The user's unique screen name. - **location** (string) - The user's location. - **description** (string) - The user's profile description. - **protected** (boolean) - Indicates if the account is protected. - **followers_count** (integer) - The number of followers. - **friends_count** (integer) - The number of users the user is following. - **created_at** (string) - The date and time the account was created. - **verified** (boolean) - Indicates if the account is verified. - **statuses_count** (integer) - The number of tweets posted by the user. - **status** (object) - The user's most recent tweet object. ### Request Example ```php $connection->get('account/verify_credentials', ['tweet_mode' => 'extended', 'include_entities' => 'true']); ``` ### Response Example ```json { "id": 12, "id_str": "12", "name": "jack", "screen_name": "jack", "location": "", "description": "#bitcoin", "protected": false, "followers_count": 5033667, "friends_count": 4510, "created_at": "Tue Mar 21 20:50:14 +0000 2006", "verified": true, "statuses_count": 27342, "status": { "created_at": "Sat Dec 26 00:21:17 +0000 2020", "id": 1342626501238276096, "id_str": "1342626501238276096", "full_text": "RT @PowerDNS_Bert: In this post, we'll reverse-engineer the actual mRNA code of the @BioNTech_Group/@pfizer SARS-CoV-2 vaccine, character fβ¦", "truncated": false, "entities": { "hashtags": [], "symbols": [], "user_mentions": [ { "screen_name": "PowerDNS_Bert", "name": "Bert Hubert π©πͺπΊπΈ", "id": 185980279, "id_str": "185980279" }, { "screen_name": "BioNTech_Group", "name": "BioNTech SE", "id": 1060984350995550208, "id_str": "1060984350995550208" }, { "screen_name": "pfizer", "name": "Pfizer Inc.", "id": 56488059, "id_str": "56488059" } ], "urls": [] }, "source": "Twitter for iPhone", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 3680, "favorite_count": 0, "favorited": false, "retweeted": false, "lang": "en" } } ``` ``` -------------------------------- ### Bootstrap TwitterOAuth and Set Credentials Source: https://twitteroauth.com/redirect Include the autoloader, define consumer key, secret, and callback URL, and instantiate the TwitterOAuth class. Ensure environment variables are set for security. ```php require 'vendor/autoload.php'; use Abraham\TwitterOAuth\TwitterOAuth; define('CONSUMER_KEY', getenv('CONSUMER_KEY')); define('CONSUMER_SECRET', getenv('CONSUMER_SECRET')); define('OAUTH_CALLBACK', getenv('OAUTH_CALLBACK')); $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET); ``` -------------------------------- ### Import TwitterOAuth Class Source: https://twitteroauth.com/ Include the Composer autoloader and import the TwitterOAuth class to begin using the library. ```php require "vendor/autoload.php"; use Abraham\TwitterOAuth\TwitterOAuth; ``` -------------------------------- ### POST oauth/access_token Source: https://twitteroauth.com/ Obtains an access token after user authorization. Requires the oauth_verifier parameter. ```APIDOC ## POST oauth/access_token ### Description Obtains an access token after user authorization. Requires the oauth_verifier parameter. ### Method POST ### Endpoint /oauth/access_token ### Parameters #### Query Parameters - **oauth_verifier** (string) - Required - The verifier string obtained during the authorization process. ### Request Example ```json { "example": "$access_token = $connection->oauth(\"oauth/access_token\", [\"oauth_verifier\" => \"nMznkpFRTMCuNMsmALzel9FgPlmWQDWg\"]);" } ``` ### Response #### Success Response (200) - **access_token** (string) - The obtained access token. - **access_token_secret** (string) - The access token secret. #### Response Example ```json { "example": "{ \"access_token\": \"...\", \"access_token_secret\": \"...\" }" } ``` ``` -------------------------------- ### Configure HTTP Proxy for Connection Source: https://twitteroauth.com/ Enable HTTP proxy support for your TwitterOAuth connection by setting proxy options like host, port, and credentials. ```php $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token_secret); $connection->setProxy([ 'CURLOPT_PROXY' => '127.0.0.0', 'CURLOPT_PROXYUSERPWD' => '', 'CURLOPT_PROXYPORT' => 8080, ]); ``` -------------------------------- ### Initialize TwitterOAuth with Request Token Source: https://twitteroauth.com/callback Creates a new TwitterOAuth instance using the consumer credentials and the temporary request token obtained from the session. This instance is used for subsequent API calls. ```php $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $request_token['oauth_token'], $request_token['oauth_token_secret']); ``` -------------------------------- ### Create Authenticated TwitterOAuth Instance Source: https://twitteroauth.com/profile Instantiates TwitterOAuth using consumer keys and the user's specific access token and secret for making authenticated API requests. ```php $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']); ``` -------------------------------- ### Request an OAuth Access Token Source: https://twitteroauth.com/ Obtain an OAuth access token by making a POST request to the oauth/access_token endpoint, providing the oauth_verifier. ```php $access_token = $connection->oauth("oauth/access_token", ["oauth_verifier" => "nMznkpFRTMCuNMsmALzel9FgPlmWQDWg"]); ``` -------------------------------- ### POST direct_messages/events/new Source: https://twitteroauth.com/ Sends a direct message event. Requires JSON payload. ```APIDOC ## POST direct_messages/events/new ### Description Sends a direct message event. Requires JSON payload. ### Method POST ### Endpoint /direct_messages/events/new ### Parameters #### Request Body - **event** (object) - Required - The event object for the direct message. - **type** (string) - Required - The type of event, e.g., 'message_create'. - **message_create** (object) - Required - The message creation details. - **target** (object) - Required - The recipient of the message. - **recipient_id** (string) - Required - The ID of the recipient. - **message_data** (object) - Required - The data for the message. - **text** (string) - Required - The message text. ### Request Example ```json { "example": "$data = [\n 'event' => [\n 'type' => 'message_create',\n 'message_create' => [\n 'target' => [\n 'recipient_id' => $userId\n ],\n 'message_data' => [\n 'text' => 'Hello World!'\n ]\n ]\n ]\n];\n$result = $connection->post('direct_messages/events/new', $data, ['jsonPayload' => true]);" } ``` ### Response #### Success Response (200) - **event** (object) - The created direct message event object. #### Response Example ```json { "example": "{ \"event\": { ... } }" } ``` ``` -------------------------------- ### Build Twitter Authorization URL Source: https://twitteroauth.com/redirect Construct the URL that directs users to Twitter for authorization. This URL includes the request token, allowing Twitter to identify the authorization request. ```php $url = $connection->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token'])); ``` -------------------------------- ### POST tweets (v2) Source: https://twitteroauth.com/ Creates a tweet with media attachments using the v2 API. Requires media to be uploaded first. ```APIDOC ## POST tweets (v2) ### Description Creates a tweet with media attachments using the v2 API. Requires media to be uploaded first. ### Method POST ### Endpoint /2/tweets ### Parameters #### Request Body - **text** (string) - Required - The text content of the tweet. - **media** (object) - Required - An object containing media IDs. - **media_ids** (array) - Required - An array of media ID strings. ### Request Example ```json { "example": "$connection->setApiVersion(2);\n$parameters = [\n 'text' => 'Meow Meow Meow',\n 'media' => ['media_ids' => [$media1->media_id_string, $media2->media_id_string]]\n];\n$result = $connection->post('tweets', $parameters, ['jsonPayload' => true]);" } ``` ### Response #### Success Response (200) - **data** (object) - The created tweet object. #### Response Example ```json { "example": "{ \"data\": { ... } }" } ``` ``` -------------------------------- ### Upload Media Files for Tweets Source: https://twitteroauth.com/ Upload media files (images) using the v1.1 API's media/upload endpoint. Supports both standard and chunked uploads. Ensure your app has Read and Write privileges. ```php $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token_secret); $connection->setApiVersion(1.1); $media1 = $connection->upload('media/upload', ['media' => '/path/to/file/kitten1.jpg']); $media2 = $connection->upload('media/upload', ['media' => '/path/to/file/kitten2.jpg'], ['chunkedUpload' => true]); $connection->setApiVersion(2); $parameters = [ 'text' => 'Meow Meow Meow', 'media' => ['media_ids' => [$media1->media_id_string, $media2->media_id_string]] ]; $result = $connection->post('tweets', $parameters, ['jsonPayload' => true]); ``` -------------------------------- ### POST media/upload Source: https://twitteroauth.com/ Uploads media (e.g., images) to Twitter. This uses the v1.1 API. ```APIDOC ## POST media/upload ### Description Uploads media (e.g., images) to Twitter. This uses the v1.1 API. ### Method POST ### Endpoint /media/upload ### Parameters #### Request Body - **media** (file) - Required - The media file to upload. - **chunkedUpload** (boolean) - Optional - Enables chunked upload for large files. ### Request Example ```json { "example": "$media1 = $connection->upload('media/upload', ['media' => '/path/to/file/kitten1.jpg']);\n$media2 = $connection->upload('media/upload', ['media' => '/path/to/file/kitten2.jpg'], ['chunkedUpload' => true]);" } ``` ### Response #### Success Response (200) - **media_id_string** (string) - The ID of the uploaded media. #### Response Example ```json { "example": "{ \"media_id_string\": \"...\" }" } ``` ``` -------------------------------- ### Store Access Token in Session Source: https://twitteroauth.com/callback Saves the obtained long-lived access token and its secret into the user's session. This allows the application to maintain authentication for future API interactions. ```php $_SESSION['access_token'] = $access_token; ``` -------------------------------- ### Send JSON Data for Direct Messages Source: https://twitteroauth.com/ Send a direct message event by posting JSON data to the direct_messages/events/new endpoint. Requires recipient ID and message content. ```php $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token_secret); $data = [ 'event' => [ 'type' => 'message_create', 'message_create' => [ 'target' => [ 'recipient_id' => $userId ], 'message_data' => [ 'text' => 'Hello World!' ] ] ] ]; $result = $connection->post('direct_messages/events/new', $data, ['jsonPayload' => true]); ``` -------------------------------- ### Retrieve and Verify Request Token from Session Source: https://twitteroauth.com/callback Retrieves the temporary oauth_token and oauth_token_secret from the session. It includes a check to ensure the token matches the one initially sent to Twitter to prevent security issues. ```php $request_token = []; $request_token['oauth_token'] = $_SESSION['oauth_token']; $request_token['oauth_token_secret'] = $_SESSION['oauth_token_secret']; if (isset($_REQUEST['oauth_token']) && $request_token['oauth_token'] !== $_REQUEST['oauth_token']) { // Abort! Something is wrong. } ``` -------------------------------- ### Change TwitterOAuth Timeout Settings Source: https://twitteroauth.com/ Adjust the connect and request timeouts for cURL connections. The first parameter sets the connect timeout, and the second sets the maximum request time. ```php $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token_secret); $connection->setTimeouts(10, 15); ``` -------------------------------- ### POST statuses/update Source: https://twitteroauth.com/ Posts a new tweet. Uses the v1.1 API. ```APIDOC ## POST statuses/update ### Description Posts a new tweet. Uses the v1.1 API. ### Method POST ### Endpoint https://api.twitter.com/1.1/statuses/update.json ### Parameters #### Query Parameters - **status** (string) - Required - The text of the tweet. ### Request Example ```json { "example": "$statues = $connection->post(\"statuses/update\", [\"status\" => \"hello world\"]);" } ``` ### Response #### Success Response (200 or 201) - **id_str** (string) - The ID of the posted tweet. - **text** (string) - The text of the posted tweet. #### Response Example ```json { "example": "{ \"id_str\": \"...\", \"text\": \"hello world\" }" } ``` ``` -------------------------------- ### Store Request Token in Session Source: https://twitteroauth.com/redirect Persist the obtained OAuth token and token secret in the PHP session. This is crucial for subsequent steps in the authorization flow. ```php $_SESSION['oauth_token'] = $request_token['oauth_token']; $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret']; ``` -------------------------------- ### Handle API Request Errors Source: https://twitteroauth.com/ Check the HTTP status code after making a request to determine if the operation was successful. Handle non-2xx codes as errors. ```php $statues = $connection->post("statuses/update", ["status" => "hello world"]); if (in_array ($connection->getLastHttpCode(), [200, 201])) { // Tweet posted successfully } else { // Handle error case } ``` -------------------------------- ### Obtain Access Token from Twitter API Source: https://twitteroauth.com/callback Exchanges the temporary request token for a long-lived access token by making a request to the Twitter API's oauth/access_token endpoint. Requires the oauth_verifier from the request. ```php $access_token = $connection->oauth("oauth/access_token", ["oauth_verifier" => $_REQUEST['oauth_verifier']]); ``` -------------------------------- ### Generate Twitter OAuth Request Token Source: https://twitteroauth.com/redirect Obtain a temporary request token from Twitter's API. This token is short-lived and used for initiating the authorization process. ```php $request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => OAUTH_CALLBACK)); ```