Im using this package https://github.com/thujohn/twitter to authorize users. I am able to authorize multiple users and get their data from twitter. I am struggling to post tweets to multiple users twitter accounts. Everytime I try to post it will only tweet to 1 users account. How can I post to multiple users accounts after authorization?
Here is the code I have tried. I save the user's tokens in the database and then grab it and put it in the session. :
Route::get('tweet', function(){
$token = Input::get( 'oauth_token' );
$verify = Input::get( 'oauth_verifier' );
$screen_name = DB::table('profiles')->where('oauth_token', $token)->pluck('screen_name');
$tweet_text = Input::get('tweet_text');
Session::put('oauth_request_token', $token);
Session::put('oauth_request_token_secret', $verify);
Session::get('oauth_request_token');
Session::get('oauth_request_token_secret');
dd( Twitter::postTweet(['status' => $tweet_text, 'format' => 'json']) );
});
I figured out what I was doing wrong incase anyone else runs into this problem. You have two pairs of tokens. The package I used calls them both oauth_token and oauth_token_secret but in two different arrays. I used the wrong pair and so It would only post to the last authenticated account. Make sure you use access_token pair and store them for later use. Which you can then use to post to the right/multiple accounts.
Related
I am creating a Twitter API application(using PHP libray Abraham\TwitterOAuth). when users authenticate the app I can get the oauth_token and oauth_token_secret for that user.
So now where to save those tokens for later use so that users don't have authenticate the app again and again.
Can i save them in cookies ?
UPDATE
#JánHalaša,
Hi, Thanks for your reply. I posted this question at three sites but not get any answer or comment So thanks:). Here is some more detail about the app.
I am using "PHP Abraham\TwitterOauth" Libray (uses Oauth2). My application have "read and write" permissions. It gives users ability to mute or unmute any user. So here is whole process.
I ask user to signin, When user click on signin he asked to authenticate the app by Twitter.
2.Once he authenticate the app. He is redirected to callback url. Where i request the user's oauth_token and oauth_token_secret. And i store those tokens in cookies with little encryption. Some code from callback.php.
$token = $connection->oauth(
'oauth/access_token', [
'oauth_verifier' => $oauth_verifier
]
);
$token['oauth_token']=openssl_encrypt($token['oauth_token'],"AES-128-ECB",$salt);
$token['oauth_token_secret']=
openssl_encrypt($token['oauth_token_secret'],"AES-128-ECB",$salt);
setcookie('oauth_token', $token['oauth_token'],time() + (86400 * 30));
setcookie('oauth_secret', $token['oauth_token_secret'],time() + (86400 *30));
header('location:'mute_now.php');
die();
3.Now i redirect the users to a mute_now.php page. Where i decrypt these cookies and use the oath_token and oauth_secret to get data from twitter on user's behalf. some_code from mute_now.php is
$token['oauth_token'] = openssl_decrypt($_COOKIE['oauth_token'],"AES-128-ECB",$salt);
$token['oauth_token_secret'] = openssl_decrypt($_COOKIE['oauth_token_secert'],"AES-128-ECB",$salt);
$twitter = new TwitterOAuth(
$config['consumer_key'],
$config['consumer_secret'],
$token['oauth_token'],
$token['oauth_token_secret']
);
$user_info = $twitter->get(
"account/verify_credentials"
);
$mutes = $twitter->get(
"mutes/users/list", ['include_entities'=>false,'skip_status'=>true]
);
So now if user come to my website again. I check the cookie. And if cookies are there . He don't need to authenticate the app again i directly redirect hime to mute_now.php and use those cookies to get oauth_token and oauth_token_secert
My main concern is about security. I know user can't use those tokens without the application credentials(consumer_key and consumer_secret). But i still concern about security. Should i use any encryption library like "defuse/php-encryption" before sending cookie. Or any other suggestion Please?
Is it possible to send automatic tweets from laravel like user.
User must be logged by my twitter API, and then can I send tweet as him?Of course he must accept this action. I must know when user tweets my page.
Can it work like facebook share? Is there tools for this?
Sorry for my english.
Thanks for all answer.
PS.
I do not mean this package http://vegibit.com/send-a-tweet-with-laravel/ .
I need send tweets to user table.
I have found the ThuJohn package to be the winner at this type of work.
https://github.com/thujohn/twitter
Simple to use with various options, such as
Send a tweet realtime without media:
Route::get('/send-tweet-no-media', function()
{
return Twitter::postTweet(['status' => 'Laravel is beautiful', 'format' => 'json']);
});
Send a tweet realtime with media:
Route::get('/send-tweet-with-media', function()
{
$uploaded_media = Twitter::uploadMedia(['media' => File::get(public_path('filename.jpg'))]);
return Twitter::postTweet(['status' => 'Laravel is beautiful', 'media_ids' => $uploaded_media->media_id_string]);
});
You can also do various other things, such as login, You can take it an extra level and easily store the users token & secret to your users table and do scheduled posts.
Once you have stored the users token & secret you can tweet scheduled posted for them like this:
//Get the Users token & from your User Table (or where ever you stored them)
$token = $user->token;
$secret = $user->secret;
//This line resets the token & secret with the users
Twitter::reconfig(['token' => $token, 'secret' => $secret]);
//This line posts the tweet as the user
Twitter::postTweet(['status' => 'test', 'format' => 'json']);
Use this https://twitteroauth.com/ package.
Push in your console composer require abraham/twitteroauth
When all installed then you should add
use Abraham\TwitterOAuth\TwitterOAuth; to your class.
Now in function you must create connection with your api.
$connection = new TwitterOAuth(
CONSUMER_KEY, // Information about your twitter API
CONSUMER_SECRET, // Information about your twitter API
$access_token, // You get token from user, when him sigin to your app by twitter api
$access_token_secret// You get tokenSecret from user, when him sigin to your app by twitter api
);
If you created connection then you can send post as user.
For example:
$connection->post("statuses/update", ["status" => "My first post!"]);
I am the owner and admin of a LinkedIn company page: https://www.linkedin.com/company/{id}/.
I want to connect to LinkedIn and get return a JSON-feed with latest 10 posts on my company wall to display on my website so I touch on the service https://api.linkedin.com/v1/companies/{id}/updates?format=json.
The JSON is outputted in linkedin.php. This file is then included in my web page, say index.php.
I have registrered an app at https://developer.linkedin.com. I have entered my Client ID and Client Secret in PHP-LinkedIn-SDK available here https://github.com/ashwinks/PHP-LinkedIn-SDK.
I followed the developer documentation I need to authenticate first. When I run linkedin.php I am redirected to sign into my LinkedIn profile. I have to finish this step in order to touch the service above.
With the current solution my users will have to login into LinkedIn when they access my website.
How can I access a list of my company's LinkedIn posts without prompting my users to sign in?
Thanks.
1. Generate your access token
Follow the documentation https://github.com/ashwinks/PHP-LinkedIn-SDK to create a login link.
2. Save your access token
Once you get it, it will be available for 60 days. Save it into your database.
3. Fetch your company posts
You can use the same access token to fetch company contents
$li = new LinkedIn(...);
$li->setAccessToken(YOUR_ACCESS_TOKEN);
$posts = $li->get('/companies/YOUR_COMPANY_ID/updates/');
4. Manage response
Cache or display the response after parsing it.
Hope that helps,
Use https://packagist.org/packages/linkedinapi/linkedin
$li = new LinkedIn(
array(
'api_key' => 'yourapikey',
'api_secret' => 'yourapisecret',
'callback_url' => 'https://yourdomain.com/redirecthere'
)
);
//Get the login URL - this accepts an array of SCOPES
$url = $li->getLoginUrl(
array(
LinkedIn::SCOPE_BASIC_PROFILE,
LinkedIn::SCOPE_EMAIL_ADDRESS,
LinkedIn::SCOPE_NETWORK
)
);
/*LinkedIn will redirect to 'callback_url' with an access token as the 'code' parameter. You might want to store the token in your session so the user doesn't have to log in again*/
$token = $li->getAccessToken($_REQUEST['code']);
$token_expires = $li->getAccessTokenExpiration();
//Make a request to the API
$info = $li->get('/people/~:(first-name,last-name,positions)');
$li = new LinkedIn(
array(
'api_key' => 'yourapikey',
'api_secret' => 'yourapisecret',
'callback_url' => 'https://yourdomain.com/redirecthere',
'curl_options' => array(
CURLOPT_PROXY => '127.0.0.1:80',
),
)
)
I am able to tweet messages and images to twitter using a single application and one account. Just for testing purposes, I would like to know if there is a way to tweet to multiple accounts using the same application. I was thinking that we should use the access token of every single account and its corresponding secret as well. Can anyone help with this if what I am thinking is possible??
require_once('twitter/codebird-php/src/codebird.php');
\Codebird\Codebird::setConsumerKey("xxx","xxxx");
$cb = \Codebird\Codebird::getInstance();
$cb->setToken("xxxx", "xxxxxxxxx");
$params = array(
'status' => $comments,
'media[]' => 'http://spe.atdmt.com/ds/NMMRTRUMTCRF/Azure_070114/dearazure_banner_hotub_728x90.gif'
);
$reply = $cb->statuses_updateWithMedia($params);
Just change the token after posting (->setToken) and then post again.
I'm using https://github.com/abraham/twitteroauth library. I already created my app on Twitter, the callbacks are working fine (even on localhost), but one thing that is bugging me is HOW the auto-login happens? I know there's "user_id" that is stored in the MYSQL database, along with oauth_token and oauth_token_secret, but how do I obtain user_id as soon as the user enters the site, so I can query the database to see if it already exists and what not, without having to popup the authorize twitter popup then reaching the callback, over and over again?
I've seen a lot of questions like this one, but no one ever answered it in a satisfying way.
The ones that should be saved to be used in verifying the user automatically are the oauth_access_token and oauth_access_secrete . Have you managed to get them from twitter?
The Oauth steos are:
Acquiring a request token
Sending the user to authorization
Exchanging a request token for an access token
Using out-of-band/PIN code mode for desktop & mobile applications
please refer to :
http://dev.twitter.com/pages/auth
actually, it needs to be a mix of PHP own $_SESSION with OAuth callbacks. After the callback, set the current user ID you inserted on the database or query for "user_id" from Twitter OAuth response (that you should ALSO store on the database, along with the username), then use that for future reference, and using $_SESSION containing the registered user data on your own database.
So, for a quick example
function action_login()
{
if ( ! $this->user->is_logged())
{
// Create TwitterOAuth object with our Twitter provided keys
$tOAuth = new TwitterOAuth($this->config->get('consumer_key'), $this->config->get('consumer_secret'));
// Generate request tokens
$requestToken = $tOAuth->getRequestToken(url::site('auth/twitter','http'));
$_SESSION["oauth_token"] = $requestToken["oauth_token"];
$_SESSION["oauth_token_secret"] = $requestToken["oauth_token_secret"];
// Display Twitter log in button with encoded link
$this->view->set('url', $tOAuth->getAuthorizeURL($requestToken["oauth_token"]));
$_SESSION['current_url'] = Request::detect_uri();
}
echo $this->view->render();
}
public function action_twitter()
{
if ( empty($_GET["denied"]) && isset($_GET["oauth_token"]))
{
if ($_GET["oauth_token"] == #$_SESSION["oauth_token"])
{
// Use generated request tokens (from session) to construct object
$tOAuth = new TwitterOAuth($this->config->get('consumer_key'), $this->config->get('consumer_secret'), $_SESSION["oauth_token"], $_SESSION["oauth_token_secret"]);
// Retrieve access token from Twitter
$accessToken = $tOAuth->getAccessToken();
// Check we have valid response
if(is_numeric($accessToken["user_id"])) {
// Remove request token session variables
if ($this->user->loaded() || $this->user->where('user_id', '=', $accessToken['user_id'])->find()->loaded())
{
$this->user->values(array(
'oauth_token' => $accessToken['oauth_token'],
'oauth_token_secret' => $accessToken['oauth_token_secret'],
'screen_name' => $accessToken['screen_name'],
))->update();
}
else
{
$this->user->values(array(
'user_id' => $accessToken['user_id'],
'oauth_token' => $accessToken['oauth_token'],
'oauth_token_secret' => $accessToken['oauth_token_secret'],
'screen_name' => $accessToken['screen_name'],
))->create();
}
unset($_SESSION["oauth_token"]);
unset($_SESSION["oauth_token_secret"]);
echo $this->view->render();
// Redirect to main page
}
}
}
$this->request->redirect($_SESSION['current_url']);
}
so basically, the AUTO LOGIN (like the user is already logged to twitter, and already registered to your website) can't be done without him clicking the LOGIN WITH TWITTER button, unless you set the lifetime of your $_SESSION pretty high (like it happens with twitpic for example).
$this->user->is_logged() is checking for $_SESSION['id'] (auto increment on MYSQL) and $_SESSION['twitter']['user_id'] from twitter info
EDIT: Also, the quickest and cleanest way to do it, is to make an AJAX call on the page load with the Twitter credentials using the Javascript SDK, then set the $_SESSION variables with the info the SDK provided.