/** * After authorize call back call this method with request parameters to get the Twitter access token * Once the token is recieved, it will be persisted in the session * * @param $oauth_token * @param $oauth_verifier * @return \Abraham\TwitterOAuth\TwitterOAuth * @throws \Abraham\TwitterOAuth\TwitterOAuthException */ public function setAccessToken($oauth_token, $oauth_verifier) { $initialConnection = new \Abraham\TwitterOAuth\TwitterOAuth($this->config['CONSUMER_KEY'], $this->config['CONSUMER_SECRET'], $this->session['twitter_oauth_token'], $this->session['twitter_oauth_token_secret']); $access_token = $initialConnection->oauth("oauth/access_token", ["oauth_token" => $oauth_token, "oauth_verifier" => $oauth_verifier]); $this->session['twitter_access_token'] = $access_token; return $this->setAuthenticatedConnection($access_token); }
/** * fetch the tweets from Twitter using the specified query params in the DB * the query params are specific to the passed in hash * @param string $campaign_hash the md5 hash of the campaign */ static function fetch_tweets_from_twitter($campaign_hash) { $app = \maverick\maverick::getInstance(); $queries = db::table('campaigns AS c')->leftJoin('queries AS q', array('c.id', '=', 'q.campaign_id'))->where('c.campaign_hash', '=', db::raw($campaign_hash))->get(array('c.id', 'c.name', 'c.url', 'q.type', 'q.content'))->fetch(); // build up the query if (count($queries)) { $campaign_id = $queries[0]['id']; $q_parts = array(); foreach ($queries as $q) { switch ($q['type']) { case 'or': $q_parts[] = "OR {$q['content']}"; break; case 'not': $q_parts[] = "-{$q['content']}"; break; case 'hashtag': $q_parts[] = "#{$q['content']}"; break; case 'to': $q_parts[] = "to:{$q['content']}"; break; case 'from': $q_parts[] = "from:{$q['content']}"; break; case 'at': $q_parts[] = "@{$q['content']}"; break; case 'question': $q_parts[] = '?'; break; default: // ands and sentiment as the latter two will have their respective values in the content field $q_parts[] = $q['content']; } } $query = implode(' ', $q_parts); // https://twitteroauth.com/ $connection = new \Abraham\TwitterOAuth\TwitterOAuth($app->get_config('twitter.consumer_key'), $app->get_config('twitter.consumer_secret'), $app->get_config('twitter.access_token'), $app->get_config('twitter.access_token_secret')); $search = $connection->get('search/tweets', array('q' => "#crestonexpo #tweetput", 'result_type' => 'recent', 'count' => 100)); if (!empty($search->statuses)) { foreach ($search->statuses as $status) { $data = array('campaign_id' => $campaign_id, 'iso_lang' => $status->lang, 'user_id' => $status->user->id_str, 'user_name' => $status->user->name, 'user_screen_name' => $status->user->screen_name, 'user_location' => $status->user->location, 'tweet_id' => $status->id_str, 'created_at' => date("Y-m-d H:i:s", strtotime($status->created_at)), 'content' => !empty($status->retweeted_status) ? $status->retweeted_status->text : $status->text, 'source' => $status->source, 'in_reply_to_id' => (int) $status->in_reply_to_user_id_str, 'in_reply_to_screen_name' => $status->in_reply_to_screen_name, 'retweet_count' => $status->retweet_count); $tweet_id = db::table('tweets')->insert($data)->fetch(); var_dump($status, $tweet_id); $data = array(); foreach (array('hashtags', 'urls', 'media') as $entity_type) { if (!empty($status->entities->{$entity_type})) { foreach ($status->entities->{$entity_type} as $entity) { $data[] = array('tweet_id' => $tweet_id, 'entity_type' => rtrim($entity_type, 's'), 'content' => $entity_type == 'hashtag' ? $entity->text : null, 'url' => $entity_type == 'urls' ? $entity->expanded_url : ($entity_type == 'media' ? $entity->media_url_https : null)); } } } $tweet_entities = db::table('tweet_entities')->insert($data)->fetch(); } } } }
/** * @param string $oauth_verifier * @return array */ public function getToken($oauth_verifier) { $connection = new \Abraham\TwitterOAuth\TwitterOAuth($this->app_key, $this->app_secret, $this->session->getData('oauth_token'), $this->session->getData('oauth_token_secret')); $access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $oauth_verifier)); $connection = new \Abraham\TwitterOAuth\TwitterOAuth($this->app_key, $this->app_secret, $access_token['oauth_token'], $access_token['oauth_token_secret']); $credentials = $connection->get('/account/verify_credentials', ['include_entities' => true, 'skip_status' => true, 'include_email' => true]); $access_token['since_id'] = $credentials; return $access_token; }
public function callback() { $oauth_token = $this->session->userdata('twitter_oauth_token'); $oauth = new \Abraham\TwitterOAuth\TwitterOAuth(TWITTER_KEY, TWITTER_SECRET_KEY, $oauth_token, $_GET['oauth_token']); $access_token = $oauth->oauth("oauth/access_token", array("oauth_verifier" => $_GET['oauth_verifier'])); $user_account = array('user_id' => $this->user->id, 'account_id' => $access_token['user_id'], 'type' => 'twitter', 'access_token' => (string) json_encode($access_token)); $this->load->model('user_account_model'); if ($this->user_account_model->save($user_account)) { redirect(base_url() . "main/myaccount/twitter"); } }
/** * Get the API object * * @param array $keys API keys * * @return bool|Abraham\TwitterOAuth\TwitterOAuth */ function socialink_twitter_get_api_object($keys) { $result = false; if (!empty($keys) && is_array($keys)) { $consumer_key = $keys["consumer_key"]; $consumer_secret = $keys["consumer_secret"]; if (isset($keys["oauth_token"]) && isset($keys["oauth_secret"])) { $oauth_token = $keys["oauth_token"]; $oauth_secret = $keys["oauth_secret"]; } else { $oauth_token = null; $oauth_secret = null; } $result = new Abraham\TwitterOAuth\TwitterOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_secret); $proxy_settings = socialink_get_proxy_settings(); if (!empty($proxy_settings)) { $proxy_settings["CURLOPT_PROXYUSERPWD"] = ""; $result->setProxy($proxy_settings); } } return $result; }
public static function updateTwitterPosts() { $connection = new \Abraham\TwitterOAuth\TwitterOAuth(Config::get('laravel-social-feeder::twitterCredentials.consumerKey'), Config::get('laravel-social-feeder::twitterCredentials.consumerSecret'), Config::get('laravel-social-feeder::twitterCredentials.accessToken'), Config::get('laravel-social-feeder::twitterCredentials.accessTokenSecret')); $params = array('screen_name' => Config::get('laravel-social-feeder::twitterCredentials.screen_name'), 'count' => 10); $lastTwitterPost = \SocialPost::type('twitter')->latest('published_at')->limit('1')->get()->first(); if ($lastTwitterPost) { $params['since_id'] = $lastTwitterPost->social_id; } try { $tweets = $connection->get('statuses/user_timeline', $params); } catch (Exception $e) { $tweets = array(); } foreach ($tweets as $tweet) { if (!is_object($tweet)) { continue; } $newPostData = ['type' => 'twitter', 'social_id' => $tweet->id_str, 'url' => 'https://twitter.com/' . $params['screen_name'] . '/status/' . $tweet->id_str, 'text' => $tweet->text, 'show_on_page' => 1, 'published_at' => date('Y-m-d H:i:s', strtotime($tweet->created_at))]; $newPostEntity = new \SocialPost(); $newPostEntity->fill($newPostData)->save(); } return true; }
public static function getEntriesByHashtag() { //Start - get all hashtags from the database $sql = rex_sql::factory(); $hashtags = $sql->getArray('SELECT `hashtag`, `twitter_next_id` FROM `' . rex::getTablePrefix() . 'socialhub_twitter_hashtag`'); unset($sql); if (empty($hashtags)) { return false; } //End - get all hashtags from the database //Start - get all accounts from the database $sql = rex_sql::factory(); $accounts = $sql->getArray('SELECT * FROM `' . rex::getTablePrefix() . 'socialhub_twitter_account` ORDER BY `id` ASC'); unset($sql); if (empty($accounts)) { return false; } //End - get all accounts from the database //Start - get entries by hashtag from twitter foreach ($hashtags as $hashtag) { $connection = new Abraham\TwitterOAuth\TwitterOAuth($accounts[0]['consumer_token'], $accounts[0]['consumer_secret_token'], $accounts[0]['access_token'], $accounts[0]['secret_token']); if ($hashtag['twitter_next_id'] != 0) { $response = $connection->get("search/tweets", ['q' => '#' . $hashtag['hashtag'], 'since_id' => $hashtag['twitter_next_id']]); } else { $response = $connection->get("search/tweets", ['q' => '#' . $hashtag['hashtag']]); } foreach ($response->statuses as $data) { $lastId = $data->id; if (empty($data->retweeted_status)) { $sql = rex_sql::factory(); $sql->setTable(rex::getTablePrefix() . 'socialhub_entry_hashtag'); $sql->setValue('source', 'twitter'); $sql->setValue('source_id', $data->id); $sql->setValue('caption', urlencode($data->text ? addslashes($data->text) : '')); if (!empty($data->entities->media)) { $sql->setValue('image', $data->entities->media[0]->media_url); } $sql->setValue('created_time', date('Y-m-d H:i:s', strtotime($data->created_at))); $sql->setValue('author_id', $data->user->id); $sql->setValue('author_name', $data->user->screen_name); $sql->setValue('query', $hashtag['hashtag']); try { $sql->insert(); } catch (rex_sql_exception $e) { echo rex_view::warning($e->getMessage()); } unset($sql); } } //Start - update next_id $sql = rex_sql::factory(); $sql->setTable(rex::getTablePrefix() . 'socialhub_twitter_hashtag'); $sql->setWhere('hashtag = "' . addslashes($hashtag['hashtag']) . '"'); $sql->setValue('twitter_next_id', $lastId); try { $sql->update(); } catch (rex_sql_exception $e) { echo rex_view::warning($e->getMessage()); } unset($sql); //End - update next_id } //End - get entries by hashtag from twitter }
}); $app->post('/authTwitter', function () { session_start(); $request = \Symfony\Component\HttpFoundation\Request::createFromGlobals(); $_SESSION['image'] = $request->request->get('photo'); $_SESSION['text'] = $request->request->get('text'); $connection = new \Abraham\TwitterOAuth\TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET); $request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => TWITTER_OAUTH_ENDPOINT)); $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret']; $authURL = $connection->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token'])); $response = new \Symfony\Component\HttpFoundation\JsonResponse(['url' => $authURL]); $response->send(); }); $app->get('/shareTwitter', function () { session_start(); $request = \Symfony\Component\HttpFoundation\Request::createFromGlobals(); $_SESSION['oauth_token'] = $request->query->get('oauth_token'); $_SESSION['oauth_verifier'] = $request->query->get('oauth_verifier'); $connection = new \Abraham\TwitterOAuth\TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']); $access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $_SESSION['oauth_verifier'])); $_SESSION['oauth_token'] = $access_token['oauth_token']; $_SESSION['oauth_token_secret'] = $access_token['oauth_token_secret']; $_SESSION['twitter_user_id'] = $access_token['user_id']; $connection = new \Abraham\TwitterOAuth\TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']); $imageURL = $_SESSION['image']; $photo = $connection->upload('media/upload', ['media' => $imageURL]); $statues = $connection->post("statuses/update", ['status' => $_SESSION['text'], 'media_ids' => $photo->media_id]); $response = new \Symfony\Component\HttpFoundation\RedirectResponse('https://twitter.com'); $response->send(); }); $app->run();
public function loginbytwitter() { $connection = new Abraham\TwitterOAuth\TwitterOAuth('5Gd9l295ZAkm6TP9HbTApXYb6', 'y7rXUAv2aqszUsn1O4t3SCmDlcJnWUuXqpj3kmgs3c10W9QIKV', '908751325-nW0w5sfktt4yzXlJ6ZoZTU9INTCKqsA78WWw8lON', 'jc9VcvyFDpYl9lxFpw4s44wv2dMpWEntIMNhsHS7UpYhQ'); $request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => 'http://acquire.social/register/twittercallback')); $_SESSION['oauth_token'] = $request_token['oauth_token']; $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret']; $url = $connection->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token'])); redirect($url); }
* This example is made for myself, if I loose my code */ session_start(); require_once __DIR__ . '/../vendor/autoload.php'; //Edit the following config variables $consumer_key = 'consumer_key'; $consumer_secret = 'consumer_secret'; //callback url. In this example it is using current url $callback = "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s://" : "://") . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; if (isset($_SESSION['oauth_token'])) { $oauth_token = $_SESSION['oauth_token']; unset($_SESSION['oauth_token']); $connection = new Abraham\TwitterOAuth\TwitterOAuth($consumer_key, $consumer_secret); //necessary to get access token other wise u will not have permision to get user info $params = array("oauth_verifier" => $_GET['oauth_verifier'], 'oauth_token' => $_GET['oauth_token']); $access_token = $connection->oauth('oauth/access_token', $params); //now again create new instance using updated return oauth_token and oauth_token_secret because old one expired if u dont u this u will also get token expired error $connection = new Abraham\TwitterOAuth\TwitterOAuth($consumer_key, $consumer_secret, $access_token['oauth_token'], $access_token['oauth_token_secret']); $content = $connection->get('account/verify_credentials'); //Printing the profile data print_r($content); } else { //this code will return your valid url which u can use in iframe src to popup or can directly view the page as its happening in this example $connection = new Abraham\TwitterOAuth\TwitterOAuth($consumer_key, $consumer_secret); $temporary_credentials = $connection->oauth('oauth/request_token', array("oauth_callback" => $callback)); $_SESSION['oauth_token'] = $temporary_credentials['oauth_token']; $_SESSION['oauth_token_secret'] = $temporary_credentials['oauth_token_secret']; $url = $connection->url('oauth/authenticate', array('oauth_token' => $temporary_credentials['oauth_token'])); // REDIRECTING TO THE URL header('Location: ' . $url); }
<?php require "../bootstrap.php"; $twitteroauth = new Abraham\TwitterOAuth\TwitterOAuth('kcUhArVLnK6xzDpVJU85r7FJj', 'dekH6UMluN2ZCCJ0v1q95w3DaIMeczsP1l3wAEjRwbn16G43aV', $_SESSION['access_token']['oauth_token'], $_SESSION['access_token']['oauth_token_secret']); header("Content-Type: application/json"); if ($_GET['action'] == 'followers') { $data = $twitteroauth->get("followers/list"); echo json_encode($data); } else { if ($_GET['action'] == 'mentions') { $data = $twitteroauth->get("statuses/mentions_timeline"); echo json_encode($data); } else { if ($_GET['action'] == 'retweets') { $data = $twitteroauth->get("statuses/retweets_of_me"); echo json_encode($data); } else { if ($_GET['action'] == 'search') { $data = $twitteroauth->get("search/tweets", array("q" => $_GET['q'])); echo json_encode($data); } } } }
<?php require "../bootstrap.php"; $twitteroauth = new Abraham\TwitterOAuth\TwitterOAuth('kcUhArVLnK6xzDpVJU85r7FJj', 'dekH6UMluN2ZCCJ0v1q95w3DaIMeczsP1l3wAEjRwbn16G43aV', $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']); $access_token = $twitteroauth->oauth("oauth/access_token", array("oauth_verifier" => $_GET["oauth_verifier"])); if ($access_token) { $_SESSION['access_token'] = $access_token; var_dump($access_token); } else { session_destroy(); } header("Location: index.php");
<?php require_once __DIR__ . '/../bootstrap.php'; $options = getopt('f:'); if (empty($options['f'])) { exit('Must pass in a file with the f parameter.'); } $client = new Abraham\TwitterOAuth\TwitterOAuth($config->twitter->consumer_key, $config->twitter->consumer_secret, $config->twitter->access_token, $config->twitter->access_token_secret); $client->setDecodeJsonAsArray(true); $idList = []; $handle = fopen(__DIR__ . '/' . $options['f'], 'r'); while ($row = fgets($handle)) { array_push($idList, trim($row)); if (count($idList) == 100) { $tweetLookup = $client->get('statuses/lookup', ['id' => implode(',', $idList), 'trim_user' => true]); foreach ($tweetLookup as $tweet) { $uniqueTweetCheck = $db->getRead()->fetchOne("SELECT `metadata` FROM `jpemeric_stream`.`twitter` WHERE `tweet_id` = :tweet_id LIMIT 1", ['tweet_id' => $tweet['id_str']]); if ($uniqueTweetCheck !== false) { if ($uniqueTweetCheck['metadata'] != json_encode($tweet)) { $db->getWrite()->perform("UPDATE `jpemeric_stream`.`twitter` SET `metadata` = :metadata WHERE `tweet_id` = :tweet_id", ['metadata' => json_encode($tweet), 'tweet_id' => $tweet['id_str']]); } continue; } $dateTime = new DateTime($tweet['created_at']); $dateTime->setTimezone(new DateTimeZone('America/Phoenix')); $db->getWrite()->perform("INSERT INTO `jpemeric_stream`.`twitter` (`tweet_id`, `datetime`, `metadata`) " . "VALUES (:tweet_id, :datetime, :metadata)", ['tweet_id' => $tweet['id_str'], 'datetime' => $dateTime->format('Y-m-d H:i:s'), 'metadata' => json_encode($tweet)]); } $idList = []; } } fclose($handle);
public function post_twitter($twitter_access_token, $status) { $result = array('success' => false); try { $access_token = json_decode($twitter_access_token); $connection = new \Abraham\TwitterOAuth\TwitterOAuth(TWITTER_KEY, TWITTER_SECRET_KEY, $access_token->oauth_token, $access_token->oauth_token_secret); $content = $connection->post("statuses/update", ["status" => $status]); if (isset($content->id_str)) { $result['success'] = true; $result['link'] = "https://twitter.com/" . $content->user->screen_name . "/status/" . $content->id; } } catch (Exception $e) { $result['message'] = $e->getMessage(); } return $result; }
<?php require_once __DIR__ . '/../bootstrap.php'; $client = new Abraham\TwitterOAuth\TwitterOAuth($config->twitter->consumer_key, $config->twitter->consumer_secret, $config->twitter->access_token, $config->twitter->access_token_secret); $client->setDecodeJsonAsArray(true); try { $recentTweets = $client->get('statuses/user_timeline', ['screen_name' => 'jpemeric', 'count' => 50, 'trim_user' => true]); } catch (Exception $e) { $logger->addError($e->getMessage()); exit; } if (isset($recentTweets['errors'])) { $logger->addError($recentTweets['errors'][0]['message']); exit; } foreach ($recentTweets as $tweet) { $uniqueTweetCheck = $db->getRead()->fetchOne("SELECT `metadata` FROM `jpemeric_stream`.`twitter` WHERE `tweet_id` = :tweet_id LIMIT 1", ['tweet_id' => $tweet['id_str']]); if ($uniqueTweetCheck !== false) { if ($uniqueTweetCheck['metadata'] != json_encode($tweet)) { $db->getWrite()->perform("UPDATE `jpemeric_stream`.`twitter` SET `metadata` = :metadata WHERE `tweet_id` = :tweet_id", ['metadata' => json_encode($tweet), 'tweet_id' => $tweet['id_str']]); } continue; } $dateTime = new DateTime($tweet['created_at']); $dateTime->setTimezone(new DateTimeZone('America/Phoenix')); $db->getWrite()->perform("INSERT INTO `jpemeric_stream`.`twitter` (`tweet_id`, `datetime`, `metadata`) " . "VALUES (:tweet_id, :datetime, :metadata)", ['tweet_id' => $tweet['id_str'], 'datetime' => $dateTime->format('Y-m-d H:i:s'), 'metadata' => json_encode($tweet)]); }
<?php require "../bootstrap.php"; $twitteroauth = new Abraham\TwitterOAuth\TwitterOAuth('kcUhArVLnK6xzDpVJU85r7FJj', 'dekH6UMluN2ZCCJ0v1q95w3DaIMeczsP1l3wAEjRwbn16G43aV'); $request_token = $twitteroauth->oauth("oauth/request_token", array('oauth_callback' => 'http://api1.papangping.com/twitter/oauthcallback.php')); $_SESSION['oauth_token'] = $request_token['oauth_token']; $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret']; // If everything goes well.. if ($request_token['oauth_token']) { // Let's generate the URL and redirect $url = $twitteroauth->url("oauth/authorize", array("oauth_token" => $request_token['oauth_token'])); header('Location: ' . $url); } else { // It's a bad idea to kill the script, but we've got to know when there's an error. die('Something wrong happened.'); }
$accessToken = session('access_token'); if (!session()->has('twitter_account')) { $connection = new Abraham\TwitterOAuth\TwitterOAuth(env('TWITTER_CONSUMER_KEY'), env('TWITTER_CONSUMER_SECRET'), $accessToken['oauth_token'], $accessToken['oauth_token_secret']); $twitterAccount = $connection->get("account/verify_credentials"); session(['twitter_account' => $twitterAccount]); } $twitterAccount = session('twitter_account'); return view('twitter.index', compact('twitterAccount')); }); Route::post('/twitter-status', ['as' => 'twitter_status_update', function (Illuminate\Http\Request $request) { $connection = new Abraham\TwitterOAuth\TwitterOAuth(env('TWITTER_CONSUMER_KEY'), env('TWITTER_CONSUMER_SECRET'), session('access_token.oauth_token'), session('access_token.oauth_token_secret')); $statues = $connection->post("statuses/update", ["status" => $request->input('status')]); if ($connection->getLastHttpCode() == 200) { return redirect('twitter-profile')->with("message", "Update status success!")->with("success", true); } return redirect('twitter-profile')->with('message', 'Error: can"t update status')->with('success', false); }]); Route::post('/twitter-send-message', ['as' => 'twitter_send_message', function (Illuminate\Http\Request $request) { $connection = new Abraham\TwitterOAuth\TwitterOAuth(env('TWITTER_CONSUMER_KEY'), env('TWITTER_CONSUMER_SECRET'), session('access_token.oauth_token'), session('access_token.oauth_token_secret')); $fields = ['message' => $request->input('message'), 'to' => $request->input('to')]; $request = $connection->post("direct_messages/new", $fields); if ($connection->getLastHttpCode() == 200) { return redirect('twitter-profile')->with('message', "Message sent to @" . $request->input('to'))->with('success', true); } return redirect('twitter-profile')->with('message', "Send message failed!")->with('success', false); }]); Route::get('/logout', ['as' => 'logout_path', function (Illuminate\Http\Request $request) { session()->forget('twitter_account'); session()->forget('access_token'); return redirect(route('login_path')); }]);