April
30th, 2009
Letting your users “Sign In With Twitter” with OAuth
UPDATE: You can watch me on GitHub, view documentation or fork the project.
Twitter recently added a feature to their API that let’s you allow users to sign into your site with their twitter username and password. I recently wrote a blog post on how to use Twitter’s OAuth API. This feature is a natural progression in allowing Twitter users to securely sign into your site.
Experience how it works
I’ve set up a basic example on this site. Try it out here. The files used in this example are available for download and should work on your server if you follow the steps.
Getting up to date
If you experience any problems then make sure you are using the latest version of the code. It’s available on Github.
Setting up your application on Twitter
The first step is to set up your application on Twitter. You can add an application on Twitters OAuth clients page. Click on register a new application and fill out all the fields. The two important fields are:
* Callback URL: The location of confirm.php on your server (http://yourdomain.com/confirm.php)
* User Twitter for login: Check this!
Once you’ve created your application you will need to copy and paste your consumer key and secret into secret.php.
Seeing it all in action
That’s it. Browse to start.php on your server and follow the flow. You’ll be asked to log in to twitter if you’re not already. Once you log in, Twitter will confirm that you want to allow your application access to your account. Clicking confirm will take you back to your callback url along with a request token. You’ll exchange your request token for an access token which you can use to authenticate as yourself (or whoever is going through flow). For the sake of this exercise we are saving the access token to a cookie. We use the access token to retrieve your profile and place a link to another page. This other page will use the access token from your cookie and get a listing of all your friends.
The beauty of this is that once a user allows your application access to their account they don’t have to do it again. This means that the next time they visit your site and click on the link to sign in with twitter, it will immediately redirect them to your callback page with the request token. It’s all very seamless because from the user’s perspective if they are logged into Twitter they are logged into your site. Very cool.
A look at the code
Every file loads in the dependencies. These are the includes at the top of each page.
include 'EpiCurl.php'; include 'EpiOAuth.php'; include 'EpiTwitter.php'; include 'secret.php';
Anytime you want to make requests to Twitter you need to instantiate the EpiTwitter class. The constructor takes a minimum of two parameters: your consumer key and consumer secret.
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
To obtain the authenticate url which starts the flow you simply call the correct function.
$authenticateUrl = $twitterObj->getAuthenticateUrl();
Once the user authenticates with Twitter they are redirected back to your callback url along with a request token. We need to exchange the request token for an access token. For simplicity we will save the access token to a cookie so we can make subsequent calls. On this page we will use the setToken method to set the access token and secret. As we will see on the next page, these can be passed in as parameters to the constructor as well.
$twitterObj->setToken($_GET['oauth_token']);
$token = $twitterObj->getAccessToken();
$twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
setcookie('oauth_token', $token->oauth_token);
setcookie('oauth_token_secret', $token->oauth_token_secret);
Since we saved the access token in a cookie we can make calls to twitter on behalf of the user for as long as the cookies are valid.
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret,
$_COOKIE['oauth_token'], $_COOKIE['oauth_token_secret']);
$twitterInfo= $twitterObj->get_statusesFriends();
try{
foreach($twitterInfo as $friend) {
echo $friend->screen_name;
}
}catch(EpiTwitterException $e){
echo $e->getMessage();
}
Update: If you don’t access any of the response variables then there is no guarantee that the call completes. This should also be done in a try/catch block since a non-200 response will throw an exception.
That’s all! If you’re still interested in learning more about OAuth then the following links are invaluable.
- http://wiki.github.com/jmathai/twitter-async
- http://apiwiki.twitter.com/Twitter-API-Documentation
- http://oauth.net/core/1.0/
- http://www.hueniverse.com/hueniverse/2008/10/beginners-gui-1.html
Comments are closed on this post. If you find a bug, please open an issue on GitHub.
and living in Sunnyvale, CA.
May 5th, 2009 at 1:24 am
Great article, thanks.
Do you have an example where a user clicks decline, or does not authenticate the request?
Is their a simple check for a decline / deny?
May 5th, 2009 at 7:28 am
@Harry, I hadn’t really tried the decline / deny flow. Unfortunately, it turns out that the user ends up on twitter’s site with a message and no link back to the referring site.
I posted to the Twitter Development Talk group about ways to better handle the decline / deny flow.
http://groups.google.com/group/twitter-development-talk?hl=en
May 6th, 2009 at 1:36 am
I have seen the post you added. Thanks for that.
So at present, if the user returns with an ‘oauth_token’ then the user has always authorised?
May 6th, 2009 at 11:25 pm
@Harry, correct. If the user returns with an oauth token then they’ve authorized you to use their account. Remember to trade in the authorized request token for an access token which you’ll use from there on out to make calls on behalf of that user.
May 9th, 2009 at 7:00 pm
jaisen could you please tell me how can i access the details provided by verify_credentials.xml, do we have a function for it?? n how can we access a particular field.
Thanks in advance.
May 9th, 2009 at 7:11 pm
@mandar, it would look something like
Full documentation is available here: http://wiki.github.com/jmathai/twitter-async.
May 9th, 2009 at 7:15 pm
thanks a lot jaisen, but
doesnt work n it actually has to be
which i found on your site only :)…thanks a lot dude u r doing a wonderful job. I’ll definitely refer my readers to your blog…
May 11th, 2009 at 9:08 am
hi, how do i send a status to twitter with this?
May 12th, 2009 at 2:12 pm
Just created this: http://bit.ly/whoiblock (simple app that lists the user you block on Twitter) using the sample. Thanks :)
Once I wrap it up a bit, I will publish the code on Git.
May 13th, 2009 at 5:54 pm
This is very cool thank you. I got it working very quick then I altered the way things flow just a bit and cookied the tokens. Now that I’m authenticated how to reuse my legacy twitter app code that needs to know the users password?
May 13th, 2009 at 6:01 pm
@eduardo you can use the access token and follow the docs here: http://wiki.github.com/jmathai/twitter-async.
@Colleen, it really depends on your application. Basically, the access token is a replacement for the user’s username and password. If you’re using “sign in with twitter” you can store the access token to a cookie for their session.
May 13th, 2009 at 9:24 pm
Thank u jaisen (actually on twitter im @tixrus) The legacy code feeds a twitter name: password to the original rest twitter URLS when it needs to do things. I do have the tokens in a cookie. So ur telliing me I just substitute the token for the name/pw directly?
May 13th, 2009 at 9:41 pm
@Colleen (aka @tixrus) the oauth flow is quite a bit different than Twitter’s basic auth (which you’re currently using). Sign in with Twitter is a part of the OAuth API.
I wrote a blog post about using OAuth here: http://www.jaisenmathai.com/blog/2009/03/31/how-to-quickly-integrate-with-twitters-oauth-api-using-php/.
Also, feel free to look at the documentation I referred @eduardo to that shows how to use the Twitter OAuth libraries I created for the examples.
May 19th, 2009 at 11:22 am
Jaisen, this is a great tool, thanks for writing and releasing. I have been going round in circles for a few days trying to upload a profile image. I’m getting a 403 error and wondering if you have had any success?
I am able to upload profile images using basic authentication and curl, but I think the issue with OAuth lies in using multipart/form-data messages. It appears this has been resolved in ruby, but no examples in php yet. Wondering if you have any ideas? here’s a link to the ruby thread
http://code.google.com/p/twitter-api/issues/detail?id=368
May 20th, 2009 at 12:07 am
@Chris, I know EpiTwitter does not support multipart api calls at the moment. Not sure when I’ll be able to add it to the library.
I created an issue to track it: http://github.com/jmathai/twitter-async/issues/#issue/4
May 20th, 2009 at 6:40 am
Hello jaisen. I ‘m using the EpiTwitter api to login to twitter, but when I try to reconnect using the oauth tokens I ‘m getting an empty response, and no actions can be made (like updating status). Do I have to get the access tokens every time I want to reconnect? Or there is simething wrong with my code?
May 28th, 2009 at 9:48 am
@jaisen: Really can’t thank you enough for putting in this hard work and sharing it. Scripts are just what I was looking for.
And now, a question about error trapping during the exchange of the request token for an access token (e.g. confirm.php in your demo files).
When a user is redirected back to my callback url the request token is up in the query string, I setToken, get the access token, and all is great in the world.
HOWEVER, if the user reloads that page with the request token still in the address bar, the whole thing chokes.
I think I get why it’s happening (Twitter won’t give a second set of access tokens for the same request token) but I can’t for the life of me figure out how to trap for the “error.”
Any help greatly appreciated.
Todd
http://PhishTwit.com
May 28th, 2009 at 11:50 pm
Hey Jaisen Awesome stuff!!!
i was on my way to follow th steps but when i allowed the credentials it was looking for my call back url but it didn’t found it, what can be the reason? I tried with IP address but registration didnt accepted as valid url i have given my servers name, and then two folder and then confirm.php likewise
(Note: Its not the real name of server. its an example for what callback i have given)
http://abc.digi-corp.com:XX/twitterpd/twittest/confirm.php
Can u suggest me something?
May 31st, 2009 at 12:31 pm
Hi Jaisen!
I need to find a way to check if a token is still available to use. WHen i try to use an invalid token, it will raise a fatal error, but how can I just pass this error to a variable to avoid raising error messages to the public?
Thanks Jaisen!
May 31st, 2009 at 1:12 pm
I am trying to get confirm to work (start does fine) and keep getting a fatal error that the token has expired. Any ideas what is going here?
June 1st, 2009 at 2:13 am
HI jaisen. When are you planning to put support for upload profile image on your api library?
June 1st, 2009 at 8:25 pm
Sorry about slacking on replying to everyone! I’ve been swamped with work.
I probably won’t be able to help with specific questions about why certain things are not working for your app. For general questions such as adding image support to the library…I hope to get to that soon. However, no guarantees.
@alon sent along a working php example: http://code.google.com/p/php-twitter/source/browse/trunk/class.twitter.php if anyone wanted to beat me to the punch :)
June 2nd, 2009 at 1:56 am
@Todd You could use try catch syntax
try { // code that might error } catch(Exception $e){}That will catch any error and prevent it showing. Use it carefully!
As for users refreshing the page with the token in the url, I would suggest processing the token immediately and redirecting to remove the token.
June 2nd, 2009 at 6:36 am
Harry, thanks for the reply.
I’ve never really been too familiar with the try / catch syntax.
But I tried your suggestion and it’s money! Not even really sure I’m using it “right” but my object is now failing gracefully for this particular use case (i.e. trying to re-use the request token on reload).
Meanwhile, it seems like there’s some good stuff in the EpuiAuth.php file but I can’t really figure out how to hook into it programmatically…
class EpiOAuthBadRequestException extends EpiOAuthException{} class EpiOAuthUnauthorizedException extends EpiOAuthException{}Long story shory, thank you so much for the idea to use try/catch. Probably obvious to most but not to me :)
Now, if someone can help me get an jsonp AJAX function going with the POST method I’ll be on cloud nine!
Take care all,
Todd
P.S. If you like the band Phish, my Phish Twitter aggregator should be jumping off come show-time tonight… http://PhishTwit.com
June 2nd, 2009 at 6:42 am
Think I just figured out the how to hook into the EpiOAuth error messages, and it’s fantastically simple.
Here’s my code, which probably won’t be helpful to most since it’s part of a larger object and calls a function but anyway…
if(array_key_exists('oauth_token', $_GET)){ try { // try to exchange request token for access token $this->signedIn = $this->authenticate($_GET['oauth_token']); } catch(Exception $e){ $this->statusMessage = 'Caught exception: ' . $e->getMessage(); } }And my status message works like a champ… “Caught exception: /oauth/access_token Invalid / expired Token”
Not something I’d really show to users, but good enough for now!
Again, thanks for the help.
TL
June 2nd, 2009 at 10:39 am
OK Your OAuth examples are great. One question. I am not finding much out there with the variables that I will need for the OAuth. It keeps logging me out so I have to re-authenticate every time I want to view my app. Is there a way to prevent the time out and expire at least through one session?
June 3rd, 2009 at 9:57 pm
i’m getting the same as Netlatch:
( ! ) EpiOAuthUnauthorizedException: {”request”:”\/account\/verify_credentials.json”,”error”:”Invalid \/ expired Token”} in /var/www/blah/twitter-async/EpiOAuth.php on line 272
June 3rd, 2009 at 10:33 pm
@Netlatch, @deitrich, Are you making additional calls on confirm.php or just the one from the example?
@Juanita, to do anything past the confirmation you’ll need to store the access tokens for use with subsequent calls.
June 3rd, 2009 at 10:38 pm
@Todd, that’s it. More specifically you can catch and handle different errors differently.
try{ // try to exchange request token for access token $this->signedIn = $this->authenticate($_GET['oauth_token']); }catch(EpiOAuthBadRequestException $e){ // bad request exception do something $this->statusMessage = ‘Caught exception: ‘ . $e->getMessage(); }catch(EpiOAuthUnauthorizedException $e){ // bad authorization..probably bad tokens, do something different $this->statusMessage = ‘Caught exception: ‘ . $e->getMessage(); }catch(EpiOAuthException $e){ // uh oh, unknown oauth exception }You probably don’t want to get that detailed in general, but you have the option :)
June 4th, 2009 at 5:54 am
@jaisen: Not THAT’S the good stuff!
Thank you so much.
TL
P.S. What’s the trick to getting the code sample in the comment?
June 4th, 2009 at 6:26 am
@jaisen i was using your code from github, which is not a complete example. once i found your zip with the complete sample, i got it working in no time flat. thanks very much.
i’d recommend putting a complete working code listing on the github wiki page.
cheers!
-d
June 9th, 2009 at 4:35 pm
Several of you had asked about uploading profile/background images. I’ve added image support and committed it to a separate branch on GitHub.
It’s currently at: http://github.com/jmathai/twitter-async/tree/multipart and docs are available as well: http://wiki.github.com/jmathai/twitter-async#multipart.
I have two unit tests for it but would like more usage before I merge it into master. Let me know if you get a chance to try it out.
June 11th, 2009 at 10:16 pm
Hi Jaisen, thanks for the work on this code. I can’t seem to get dynamic oauth_callback to work which has been turned back on with oauth 1.0a
The latest versions in ruby are passing the oauth_callback parameter with the getRequestToken rather than within the actual authorization url. Is there any way of doing this with your code?
June 11th, 2009 at 10:55 pm
@Hone, I need to add it. I’ll familiarize myself with the dynamic callback tomorrow and add in support if it’s not already there.
June 13th, 2009 at 1:47 am
Hey Jaisen, I was looking for the dynamic callback url support i think there is no such thing prsent in your Code.. Can u throw some light!!!
June 14th, 2009 at 3:51 am
[...] order by starting with an example and explaining it afterwards. If you are interested in using “Sign in with Twitter” then read my other blog [...]
June 14th, 2009 at 12:05 pm
Hey Jaisen, I can’t seem to get the statuses of my friends. I’m guessing i’m missing something simple. This is the code i’m using:
My authentication seems to be working as i’m able to get my twitter profile, but this is failing me. I get:
object(EpiTwitterJson)#18 (1) { ["resp:private"]=> object(EpiCurlManager)#19 (2) { ["key:private"]=> string(15) "Resource id #16" ["epiCurl:private"]=> object(EpiCurl)#5 (6) { ["mc:private"]=> resource(13) of type (curl) ["msgs:private"]=> NULL ["running:private"]=> NULL ["requests:private"]=> array(2) { ["Resource id #14"]=> resource(14) of type (curl) ["Resource id #16"]=> resource(16) of type (curl) } ["responses:private"]=> array(0) { } ["properties:private"]=> array(4) { ["code"]=> int(2097154) ["time"]=> int(3145731) ["length"]=> int(3145743) ["type"]=> int(1048594) } } } }Any ideas??
June 14th, 2009 at 10:17 pm
Romeo, read the docs here: http://wiki.github.com/jmathai/twitter-async#response
June 15th, 2009 at 7:40 am
Ha! I knew i was just staring at things too long. Thanks! I was blatantly obvious i looked at your link
June 16th, 2009 at 7:28 pm
Got another question for ya jaisen. Today Twitter had scheduled down time and as such was not accessible. As a result, attempting to make any calls to the twitter api caused everything to lock up and my apache instance had to be killed off. Is there some sort of timeout that can be set to prevent this from happening again??
Thanks for all your help with this!!
June 16th, 2009 at 8:35 pm
Romeo, Several people have requested this. It’s a long overdue feature. I created an issue on GitHub for it: http://github.com/jmathai/twitter-async/issues/#issue/10.
June 22nd, 2009 at 9:12 pm
Jaisen–you rock!! Thanks so much for putting this out there.
I have one issue I am trying to resolve…it’s probably something simple, but the solution is eluding me. If anyone could help I’d appreciate it!
I am using the nifty OAuth code here, but I’ve included it on the same page as the callback page (i.e., you come to my site on index.php, there’s be a button on the page to sign in with Twitter, clicking it takes you to Twitter’s auth, you log in, and are redirected BACK to index.php. But I get the error below when I come to the page after authenticating on the twitter page. I am checking to see if the oauth_token is either a get var or a cookie, and if not, I put up the authorize link, if so, I want to display another button instead, but I get the error below when it comes back from twitter. Any ideas?
Thanks so much in advance!
——————–
Fatal error: Uncaught exception ‘EpiOAuthUnauthorizedException’ with message ‘ /oauth/access_token Invalid / expired Token ‘ in /home/public_html/site/EpiOAuth.php:299 Stack trace: #0 /home/public_html/site/EpiOAuth.php(278): EpiOAuthException::raise(’__get(’oauth_token’) #2 {main} thrown in /home/public_html/site/EpiOAuth.php on line 299
June 23rd, 2009 at 12:13 pm
Piet -
I think the solve for my problem is the same as yours.
See above…
http://www.jaisenmathai.com/blog/2009/04/30/letting-your-users-sign-in-with-twitter-with-oauth/#comment-516
http://www.jaisenmathai.com/blog/2009/04/30/letting-your-users-sign-in-with-twitter-with-oauth/#comment-520
… for reference.
TL
June 23rd, 2009 at 12:14 pm
Is there a way to create a logout link that will log people out if they want to and/or allow them to sign into a different twitter ID?
June 23rd, 2009 at 12:30 pm
Piet: here’s a code listing of doing it all in a single page.
http://dietrich.notchill.com/test_twitter.phps
June 23rd, 2009 at 12:30 pm
> Is there a way to create a logout link
> that will log people out if they want to
> and/or allow them to sign into a different
> twitter ID?
I just link to my callback page with ?signout as the querystring.
Test on that, and if so wipe the cookies and present the “Sign In” button on that page load.
That way they’re signed out of your site (in a manner of speaking) but not out of Twitter.
Won’t do exactly what you want b/c if they click sign in again without signing out of twitter, it’ll redirect back to your callback URL immediately.
But if they log out of Twitter in the mean time they can then sign in to your site with a different account.
Seems like you could call end session (http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-account%C2%A0end_session) to really sign them out if you need to go the extra mile…
TL
http://PhishTwit.com/
June 24th, 2009 at 10:55 am
Todd and Dietrich–thanks so much! That solved it for me.
July 5th, 2009 at 7:23 pm
Hi all, first just want to thank Jaisen for the code! It really helped with reducing the coding time. Second I was wondering if anyone has gotten accountEnd_session to work? I tried it but doesn’t seem to be working. Any advice would be appreciated!
July 8th, 2009 at 3:36 pm
Mike, I haven’t tested that endpoint yet. It should work but I’ll have a look at it and add some tests to make sure it’s functioning correctly.
July 12th, 2009 at 12:36 am
Hi Jaisen. The greatest thing that attracts me to your code is how it is structured. I think that’s the greatest point about it. IMHO it’s masterpiece. Your approach seems universal. Any plans on applying it to other APIs?
But my real question is much simpler - do you plan to add basic username/password authentication mechanism to Twitter library? I mean some people do not use oAuth exclusively. For example I have to implement my own calls in such case, which leaves some duplicating feeling in me, which I do not like :(
July 14th, 2009 at 12:27 pm
Jaisen, I believe I am having the same problem as “Ted”, I have an error to go with though:
Call to a member function setToken() on a non-object in /misc/25/000/217/449/1/user/web/orbzorbz.com/Twitter.php on line 6
Here is the code, it is on my callback page, where I am exchanging for access code.
setToken($_REQUEST['oauth_token']);
***********************
$token = $twitterObj->getAccessToken();
$twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
setcookie(’oauth_token’, $token->oauth_token);
setcookie(’oauth_token_secret’, $token->oauth_token_secret); ?>
$Token=$_REQUEST["oauth_token"];
I seperated line 6 with ***
Any idea what’s up?
July 14th, 2009 at 4:59 pm
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$twitterObj->setToken($_COOKIE['oauth_token'], $_COOKIE['oauth_token_secret']);
$twitterInfo= $twitterObj->$selection;
foreach($twitterInfo as $Info) {
I have tested values of cookies and $selection, they are fine… $twitterInfo comes up empty! anybody know what it is I am doing wrong?
July 18th, 2009 at 7:03 am
One random note that may help a few other n00bs: cookies are PATH-SPECIFIC, which means that you can’t easily locate the twitter functionality in it’s own path and then redirect elsewhere. If you get one query out of your token and then it suddenly becomes “invalid / expired”, this could be why.
July 23rd, 2009 at 6:33 pm
Okay, having another error trapping issue and everyone was so helpful last time.
This time the error I’m getting is…
Fatal error: Uncaught exception ‘EpiOAuthException’ with message ‘{”request”:”\/account\/verify_credentials.json”,”error”:”Too many requests in this time period. Try again later.”}’
… but I can’t figure out how / where I’m supposed to trap for it.
Any help appreciated.
TL
July 24th, 2009 at 4:30 am
Todd, you’re reaching your API rate limit. The default is 150/hour unless you’re whitelisted. You should wrap your calls inside a try/catch block because EpiTwitter throws an exception for non 200 series responses. The response you’re receiving is a 400 series (401 I believe). You can call account/rate_limit_status to see where you’re at. More information at the links below.
http://apiwiki.twitter.com/Rate-limiting
http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-account%C2%A0rate_limit_status
July 27th, 2009 at 12:42 am
Hi Jaisen,
Did you add the callback url option into epicode?
Thanks,
Harry
July 27th, 2009 at 9:26 am
@Harry, the callback url option is available in twitter-async. I moved the twitter libraries out of EpiCode and into their own project. If you checkout the latest revision it has support for callback urls. Plus there have been numerous bug fixes since twitter-async was forked.
http://github.com/jmathai/twitter-async/tree/master
July 28th, 2009 at 12:06 pm
I’m having a problem, I’m using the updated epi files and trying to get this example working on my server but the second page (random.php) just says “your friends are:” but then is blank, I know I am authenticating correctly as I get my information on the confrim page. Any ideas?
July 28th, 2009 at 12:42 pm
Here’s the error I’m getting when trying to display friends
Fatal error: Allowed memory size of 262144 bytes exhausted (tried to allocate 22414 bytes) in /home/bobforthejob/twitistan/EpiCurl.php on line 73
I can’t imagine that that much memory is needed…. any other ideas?
July 28th, 2009 at 12:47 pm
@Bob, I haven’t run into that problem. I’m not sure how much memory is generally required. Are you able to increase memory allocation? Perhaps using ini_set?
July 29th, 2009 at 7:53 am
Awesome classes. I have been using it for weeks and now every time I try to make a tweet through it. I get this error:
Fatal error: Uncaught exception ‘EpiOAuthUnauthorizedException’ with message ‘{”request”:”\/statuses\/update.json”,”error”:”Incorrect signature”}’ in /home/mojo/public_html/twitter/EpiOAuth.php:299 Stack trace: #0 /home/mojo/public_html/twitter/EpiTwitter.php(123): EpiOAuthException::raise(’{”request”:”\/s…’, 401) #1 /home/mojo/public_html/tweet.php(131): EpiTwitterJson->__get(’response’) #2 /home/mojo/public_html/tweet.php(73): tweetit() #3 {main} thrown in /home/mojo/public_html/twitter/EpiOAuth.php on line 299
I would really appreciate any help with this!
Thanks again. :)
July 29th, 2009 at 7:57 am
@Lee, could you provide a code sample of what causes this error? Please include the status you’re trying to post and let me know if you’re running the latest version from GitHub.
July 29th, 2009 at 8:01 am
Thank you for the reply. :)
This is how I am using it:
include './twitter/EpiCurl.php'; include './twitter/EpiOAuth.php'; include './twitter/EpiTwitter.php'; $consumer_key = 'mykey'; $consumer_secret = 'mysecret'; $twitterObj = new EpiTwitter($consumer_key, $consumer_secret); $twitterObj->setToken($_SESSION['oauth_token']); $success = $twitterObj->post_statusesUpdate(array('status' => "$twitter_message ".$tweetmojoURL.$tweet_key)); return $success->response['id'];The status I sent was: “How Adobe Products Support Windows Vista”. To be honest, anything I say gives me this exception!
This use to work perfectly, maybe not the best php code but it worked. Would appreciate on how I can solve this problem and maybe some suggestions on code improvement.
I am just checking if this is the latest from GitHub. Actually, I will over write my files to make sure I have the latest.
Thanks again.
July 29th, 2009 at 8:04 am
Sorry for being a noob. I do not know how to wrap in code tags.
I can confirm that I am now using the latest code.
July 29th, 2009 at 8:14 am
@Lee, you need to pass token and secret into the setToken function. Twitter patched their API yesterday which fixed a security hole where they accepted invalid signatures. That’s most likely why your code previously worked without setting the token secret.
July 29th, 2009 at 8:26 am
I did not know that happened (I really need to subscribe to their blog). I have updated to your latest classes and I have added an extra parameter to the setToken function like so:
However, I still get that same error! Is there anything else I am missing or I can try to debug this problem?
Thank you for any more help.
July 29th, 2009 at 8:29 am
@Lee, EpiOAuth::getAccessToken returns an object with token and token_secret member variables. You’ll need the token_secret from that to pass into setToken (not your consumer secret).
July 29th, 2009 at 8:44 am
SUCCESS! Thank you very much Jaisen! I did as you said and it worked perfectly. Thank you very much. :)
July 29th, 2009 at 3:08 pm
Hello again. I am trying to make some “unauthorized” API calls with your library but can’t quite get it to work… (The goal is to allow non-Twitter users to see certain information.)
I just want to get information from a url such as: http://twitter.com/statuses/user_timeline.xml?user_id=19636275 (Note that this works without any login, etc.)
The original code doesn’t seem to work unless the user has an valid Twitter token, but the following hack works. (This is obviously just a temporary hack.)
if(empty($this->consumerKey)) { $query = 'user_id=19636275'; //$query = isset($args) ? http_build_query($args) : ''; $url = "{$this->apiUrl}{$path}?{$query}"; //$url = "{$this->searchUrl}{$path}?{$query}"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout); return new EpiTwitterJson(EpiCurl::getInstance()->addCurl($ch), self::EPITWITTER_AUTH_BASIC); }Any thoughts?
July 29th, 2009 at 3:24 pm
Quick update…
It seems that there is a difference between the following URLs:
http://twitter.com/statuses/user_timeline.xml?19636275
http://twitter.com/statuses/user_timeline.xml?user_id=19636275
The first requires a authentication, but the second does not. Weird…
July 29th, 2009 at 4:47 pm
Nathan, EpiTwitter doesn’t officially support unnamed parameters. I’ve never actually tried it myself, but if you can specify the parameter as a named one, I’d go with that :).
August 1st, 2009 at 6:46 am
I’m having problems with the friendships/create/$id.json?follow=yes
I’m not really sure how i’d go about it, as I was parameters and $id.json
Any advice?
August 1st, 2009 at 6:22 pm
@Sam, you’ll need to call a variable method name. There’s an example in the documentation.
http://wiki.github.com/jmathai/twitter-async#methodnames
August 4th, 2009 at 9:45 am
Hello i have a problem with sign in with twitter, in my old server all works fine, i change my hosting and i have problems with the buton “Sign in With Twitter” the link of this buton is “http://twitter.com/oauth/authorize?oauth_token=” i have not oauth_token, What is the problem? i
be extremely grateful to receive a response.
sorry, my English is not good :-S
August 5th, 2009 at 1:46 pm
hi,im trying to list all tweets made by a certain user. my code is:
setToken($_GET['oauth_token']); $token = $twitterObj->getAccessToken(); $twitterObj->setToken($token->oauth_token, $token->oauth_token_secret); $_COOKIE['oauth_token']; $_COOKIE['oauth_token_secret']; $twitterInfo= $twitterObj->get_accountVerify_credentials(); $twitterInfo->response; echo "profile_image_url}\">"; echo "Name: {$twitterInfo->screen_name}"; echo "URL: {$twitterInfo->url}"; echo "Location: {$twitterInfo->location}"; echo "Tweets: {$twitterInfo->statuses_count}"; echo ""; $tweets = $twitterObj->get_statusesUser_timeline(); foreach($tweets as $tweet) { echo ''.strftime("%A, %d. %B %Y - %H:%M:%S", strtotime($tweet->created_at)),''; echo $tweet->text.''; } $tok = file_put_contents('tok', $token->oauth_token); $sec = file_put_contents('sec', $token->oauth_token_secret); ?>but it shows me only the last tweet of the first page, even thoug i have an foreach. can anybody help me out?
August 5th, 2009 at 1:47 pm
how can i post sourcecode?
there are some parts missing at the beginning…
August 6th, 2009 at 7:08 am
Hi All, I’m sure you’ve noticed the twitter outage. I just implemented Jaisen’s code last night (it was working when I went to bed) and now this morning it was broken.
This is the error I was getting:
“Fatal error: Maximum execution time of 30 seconds exceeded in /home/enroller/public_html/hopchart/lib/EpiCurl.php on line 64″
I just added a try/catch to EpiCurl line 64 to about 74. I’m sure there’s a more elegant solution but I needed something quick and thought maybe someone else did too.
p.s. Huge props for the great work Jaisen!
August 6th, 2009 at 7:13 am
@elteto, could you email me what resonseText contains?
@mo, I’ll look into the problem you’re having.
@Akai, the latest version of the code form github contains a curl timeout which defaults to 30 seconds. That should help as well.
August 6th, 2009 at 10:06 am
Hello again Jaisen,
Today, I noticed a lot of errors in my error log and they were in this form:
thrown in /home/mojo/public_html/twitter/EpiOAuth.php on line 327
[06-Aug-2009 10:28:36] PHP Fatal error: Uncaught exception ‘EpiOAuthException’ in /home/mojo/public_html/twitter/EpiOAuth.php:327
Stack trace:
#0 /home/mojo/public_html/twitter/EpiOAuth.php(304): EpiOAuthException::raise(NULL, 0)
#1 /home/mojo/public_html/twitter/EpiOAuth.php(38): EpiOAuthResponse->__get(’oauth_token’)
#2 /home/mojo/public_html/header.php(5): EpiOAuth->getAuthenticateUrl()
#3 /home/mojo/public_html/view.php(39): require_once(’/home/mojo/publ…’)
Some times the following is displayed in my browser:
Fatal error: Uncaught exception ‘EpiOAuthException’ in /home/mojo/public_html/twitter/EpiOAuth.php:327 Stack trace: #0 /home/mojo/public_html/twitter/EpiOAuth.php(304): EpiOAuthException::raise(NULL, 0) #1 /home/mojo/public_html/twitter/EpiOAuth.php(38): EpiOAuthResponse->__get(’oauth_token’) #2 /home/mojo/public_html/header.php(5): EpiOAuth->getAuthenticateUrl() #3 /home/mojo/public_html/view.php(39): require_once(’/home/mojo/publ…’) #4 {main} thrown in /home/mojo/public_html/twitter/EpiOAuth.php on line 327
Any idea
August 6th, 2009 at 10:20 am
Ah I see - it was because of a serious outage at Twitter.
Regardless, I need to introduce some excpetion catching, any advice?
Or shall I just wrap everything in try and catch blocks?
Thanks
August 6th, 2009 at 10:43 am
@Lee, you should definitely put the code inside of a try/catch block. Refer to a previous comment on how that might look.
http://www.jaisenmathai.com/blog/2009/04/30/letting-your-users-sign-in-with-twitter-with-oauth/#comment-520
August 6th, 2009 at 11:19 am
hey thanks jaisen. dont know why, but today its working somehow.
didnt change anything. now i get the whole first page. what if i want all, or at least 3200 of my tweets displayed? is there a way?
August 6th, 2009 at 2:49 pm
Hey, nice of you to be answering people’s questions.
I was working with EpiTwitter yesterday (before all of today’s Twitter OAuth problems) trying to change the background image. The problem is, it only worked sometimes! If the only call I had was to update the profile background, it wouldn’t work (wouldn’t fail, just return successful but create no change). However if I added a couple extra things like a status update and that snippet of code to list all usernames of friends, it would suddenly work. Do you know what this could be?
August 6th, 2009 at 2:53 pm
@busted, for all of your calls do you access one of the response values (i.e. ->responseText)? You need to do that in order to ensure the call completes. If you’re not, then you can have sporadic behavior.
On a side note, I haven’t use the update image API much. I know there are some bugs open with it but it’s likely that the problem might be that the calls aren’t always completing as mentioned above.
August 6th, 2009 at 3:13 pm
@jaisen Thanks for the quick response! You’re gonna have to bare with me as I’m a total newb when it comes to web programming :)
Would a way to do this be:
(running gets seems to be very slow right now)
Your library is the only one in PHP at the moment that guarantees multipart image uploading I believe.
August 6th, 2009 at 7:44 pm
@Busted, yes. But you’ll need to do that for every api call you make.
August 7th, 2009 at 6:57 am
the library isn’t working for me as of yesterday. I imagine that may be due to the outage. Even your demo of sign in with twitter returns a blank page. My epitwitter calls don’t return anything from twitter, no error message, etc. Anyone else have epitwitter working today?
August 8th, 2009 at 2:57 pm
Awesome library. I saw that you added support for oauth callback, but I can’t for the life of me figure out how to use it. I’m using the example you posted online, where do I add the callback? I’m guessing somewhere on start.php?
?
Any help is much appreciated. Thanks!
August 9th, 2009 at 11:03 am
Firs of all thank you for the great library and for the great explanation. It didn’t take me a long time to understand the usage.
The code works, but I’m trying to test the exceptions, and I don’t know why I can’t catch any. I’m disconnecting the server to get an exception and using the following code:
try{ $this->twitterObj = new EpiTwitter($GLOBALS['consumer_key'], $GLOBALS['consumer_secret'], $this->ttoken, $this->tsecret); } catch(EpiOAuthBadRequestException $e){ return false; } catch(InvalidArgumentException $e){ return false; } catch(EpiOAuthUnauthorizedException $e){ return false; } catch(EpiOAuthException $e){ return false; }I’m not very good in catching exceptions, but I don’t know what am I doing wrong. The error message I get is:
Fatal error: Uncaught exception ‘EpiOAuthException’ in /media/WWW/EpiOAuth.php:251 Stack trace: #0 /WWW/EpiTwitter.php(103): EpiOAuthException::raise(NULL, NULL) #1 /WWW/EpiTwitter.php(66): EpiTwitterJson->__get(’__obj’) #2 /WWW/twitter.php(127): EpiTwitterJson->getIterator() #3 /WWW/chatbot.php(168): Twitter->statuses() #4 /WWW/cro.php(7): include(’/WWW/chatbot.php’) #5 {main} thrown in /WWW/EpiOAuth.php on line 251
Can you please help?
August 9th, 2009 at 12:10 pm
@Marko, the exceptions are not thrown when the object is instantiated. You should wrap the part of your code where you make the call and access the response in the try/catch (similarly to what you’ve done here).
Generally speaking, the exception is thrown when accessing the response.
August 9th, 2009 at 1:32 pm
Thanks for the help jaisen.
Once OAuth came back up I got it all working perfectly. Thanks too for the great library.
August 11th, 2009 at 2:23 pm
I just thought I would let you know of a question I asked on stackoverflow: http://stackoverflow.com/questions/1263270/dealing-with-twitters-ups-and-downs-api
I also wanted to ask, I thought the classes were asynchronous but if twitter is down and I make a request, the request hangs and it stops from my page loading. The call to your class is right at the top.
I probably misunderstood things!
August 11th, 2009 at 4:50 pm
@Abs, replied on stack overflow. You can call setTimeout.
Regarding the asynchronous nature of the library. Parallel calls is more accurate. Before the php script is completed it waits for any responses if you block for them.
August 11th, 2009 at 9:52 pm
Very useful post. But how would I go about posting a status update? Can someone share the code with me?
I have this, but it doesn’t seem to work.
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret, $_COOKIE['oauth_token'], $_COOKIE['oauth_token_secret']); $twitterObj->post_statusesUpdate(array('status' => 'Getting some work done.'));August 11th, 2009 at 9:55 pm
@Giles,
Try this. Note the 3rd line which is required to complete the call.
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret, $_COOKIE['oauth_token'], $_COOKIE['oauth_token_secret']); $response = $twitterObj->post_statusesUpdate(array('status' => 'Getting some work done.')); echo $response->responseText;August 11th, 2009 at 10:01 pm
Whoah! Was not expecting such a speedy reply. :)
Thanks, Jaisen. I’ve been working on integrating OAuth and the Twitter API into our website for a few days now, and I’ve finally got it thanks to you.
Really appreciate it! Now we’ll hopefully be able to launch phase 2 monday! Thanks again!
August 11th, 2009 at 11:25 pm
Sorry, one more thing…
I’m using
to grab the users twitter username, is there a way to grab the users name?
i.e. http://twitter.com/gilesvangruisen - Username is gilesvangruisen, but on the right-hand side, it says my name, Giles Van Gruisen
Thanks for the help
August 12th, 2009 at 1:17 am
Many thanks Jaisen.
I will implement it when I get home. :)
I will be adding a credits page to my site and you and your classes will be noted.
Thank you once again.
August 12th, 2009 at 10:19 am
I seem to have found a small bug that prevented me from passing my Callback URL to twitter. Since there’s been some chatter about this here, I figured I’d post it. All I needed to do was add the $params argument to the getRequestToken function (which, tellingly, is already prepared to receive it).
Question for Jaisen — am I likely to break anything with this change? I dont think so, but haven’t tested.
public function getAuthenticateUrl($token = null, $params = null) { //$params argument added to this function so that the callback url is honored by Twitter $token = $token ? $token : $this->getRequestToken($params); $addlParams = empty($params) ? '' : '&'.http_build_query($params); return $this->getUrl($this->authenticateUrl) . '?oauth_token=' . $token->oauth_token . $addlParams; }August 12th, 2009 at 10:30 am
@Nathan, not sure I’m able to stop the change. Does this differ from the latest version @ github?
http://github.com/jmathai/twitter-async/blob/a46c330d1ae75eae860d087df2d38c44cc07aa2e/EpiOAuth.php
August 13th, 2009 at 7:03 pm
Is there any way to access the status header codes that Twitter is sending in its replies?
August 13th, 2009 at 7:10 pm
Just saw it in your tweet :) great. http://twitter.com/jmathai/status/3297807026
August 13th, 2009 at 7:34 pm
I am afraid thats not working (sorry for the third comment in a row). $result->request is undefined.
August 13th, 2009 at 9:42 pm
@Patrick, Thanks for pointing that out. It should be ->response instead of ->request.
When you say status header do you mean the headers sent back from Twitter or just the HTTP code? The HTTP code is ->response->code. Adding in the headers would just require a few modifications to the curl handle in EpiOAuth. Let me know if that’s what you’re after.
August 14th, 2009 at 12:09 am
@jaisen thank you. I will test that one.It would be good to have the accompanying text, according to http://apiwiki.twitter.com/HTTP-Response-Codes-and-Errors it could contain useful information when your requests are denied. Also as far as I understand, they are sending lots of x-headers. Not that I need them right now, the status code is enough :)
August 14th, 2009 at 8:13 am
How can i make so i can post a new status message from a form textarea?
August 15th, 2009 at 4:09 pm
Hi,
I’ve installed this today, and its working perfectly on my test box, but on my production box I’m getting an error. Here is the error
Fatal error: Uncaught exception ‘EpiOAuthException’ in /var/www/vhosts/gotwitr.com/httpdocs/sites/all/modules/phpTwit/EpiOAuth.php:338 Stack trace: #0 /var/www/vhosts/gotwitr.com/httpdocs/sites/all/modules/phpTwit/EpiTwitter.php(131): EpiOAuthException::raise(NULL, 0) #1 /var/www/vhosts/gotwitr.com/httpdocs/sites/all/modules/phpTwit/EpiTwitter.php(96): EpiTwitterJson->__get(’__obj’) #2 [internal function]: EpiTwitterJson->count() #3 /var/www/vhosts/gotwitr.com/httpdocs/krumo/class.krumo.php(1070): count(Object(EpiTwitterJson)) #4 /var/www/vhosts/gotwitr.com/httpdocs/krumo/class.krumo.php(760): krumo::_object(Object(EpiTwitterJson), ‘…’) #5 /var/www/vhosts/gotwitr.com/httpdocs/krumo/class.krumo.php(582): krumo::_dump(Object(EpiTwitterJson)) #6 [internal function]: krumo::dump(Object(EpiTwitterJson)) #7 /var/www/vhosts/gotwitr.com/httpdocs/krumo/class.krumo.php(1276): call_user_func_array(Array, Array) #8 /var/www/vhosts/gotwitr.com/httpdocs/sites/all/modules/phpTwit/phpTwit.module(66): krumo(Object(EpiTwitterJson)) #9 /v in /var/www/vhosts/gotwitr.com/httpdocs/sites/all/modules/phpTwit/EpiOAuth.php on line 338
This is happening when I call friendshipcreate…
$create = $twitterObj->post_friendshipsCreate(array('id' => "$user_b"));Any ideas, the only thing I know is that my test box has php 5.2.9 and my production box has php 5.2.4
August 16th, 2009 at 6:56 am
I updated my production box to 5.2.6 (latest in YUM for FC7) and still have same issure.
August 16th, 2009 at 11:09 am
Still trying to get this to work. I now have php 5.2.10 on my production fedora server at godaddy, but sill getting oauth exception when adding a friend.
I’m going to test some of hte other calls to see if this is a post vs get issues, or an issue on all secured twitter resources
August 16th, 2009 at 12:05 pm
Well I got this fixed finally ,and since it was weird, I thought I’d share the solution. In my friend routine, I was passing $user_a and $user_b as parameters.
In my call to friend I had $user_b in quotes as follows
$create = $twitterObj->post_friendshipsCreate(array('id' => "$user_b"));I had the remove the quotes to make this work. Not sure why this worked on one machine vs the other, but at least its working now.
$create = $twitterObj->post_friendshipsCreate(array('id' => $user_b));Thanks
Jim
August 16th, 2009 at 5:14 pm
@Jim, could you email me the output of $create->responseText?
August 16th, 2009 at 6:17 pm
Wonderful Library. Is there any updated/code samples for 1.0a support? It seems like the library is generic enough already that it could be used for 1.0a, but a code sample for oauth_callback support would be awesome.
August 16th, 2009 at 10:26 pm
@Stephen, I updated the docs and the library to properly support it. Previously, I had added support but never fully tested it because I never required it. Please update to the latest revision and let me know if the documentation is okay.
http://wiki.github.com/jmathai/twitter-async#oauthcallback
August 17th, 2009 at 12:03 pm
Thank you Jaisen,
Great example files. But I can’t find documentation about get_statusesFriends and the methods available under EPITwitter class. Is there a link to all methods available?
Thank you,
Vanleurth
August 17th, 2009 at 12:59 pm
All of the endpoints can be found here: http://apiwiki.twitter.com/Twitter-API-Documentation
Adding it to the end of the blog post as well.
August 18th, 2009 at 10:33 am
I’ve moved everything to a new server we’re using and Twitter sign in stopped working. Same files and all. Getting this:
Parse error: syntax error, unexpected T_CONST, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’
I did remember to change the callback url in the Oauth client on twitter.com. Am I doing something wrong?
I think it might be some server settings. I am using PHP 5.
August 18th, 2009 at 10:44 am
@Giles, PHP 5.2? If so, what line of what file is it complaining about?
August 18th, 2009 at 10:52 am
@Jaisen, Ah, I suppose I should ahve included that. It’s “EpiCurl.php on line 4″
I’m using Media Temple hosting.
August 18th, 2009 at 10:54 am
Agh! I cannot believe I did this… I thought I switched the PHP version on the domain to PHP 5 in my Media Temple account center, but I actually didn’t.
I just switched it to PHP 5, and it worked great. (Sorry for taking up your time, Jaisen. Thanks tons for this code!)
August 20th, 2009 at 6:50 am
@Jaisen, I used this class last month and it worked fine. However, today I’m getting this error message.
Fatal error: Uncaught exception ‘EpiOAuthUnauthorizedException’ with message ‘{”request”:”\/statuses\/followers.json?id=tee”,”error”:”Incorrect signature”}’ in /Users/bhappy/localhost/experiments/twitter/site/bin/includes/EpiOAuth.php:336 Stack trace: #0 /Users/bhappy/localhost/experiments/twitter/site/bin/includes/EpiTwitter.php(131): EpiOAuthException::raise(’{”request”:”\/s…’, 401) #1 /Users/bhappy/localhost/experiments/twitter/site/bin/services/processStep.php(15): EpiTwitterJson->__get(’response’) #2 {main} thrown in /Users/bhappy/localhost/experiments/twitter/site/bin/includes/EpiOAuth.php on line 336
I’ve downloaded the latest classes from the repo and this is how I’m using it.
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret); $twitterObj->setToken($_REQUEST['tok'], $_REQUEST['sec']); $resp = $twitterObj->get_statusesFollowers(array('@id' => $_REQUEST["screen_name"])); json_encode($resp->response);Please help.
Thanks.
Tee
August 20th, 2009 at 7:29 am
@Tee, You need to remove the ‘@’ sign from in front of the id. That’s reserved for multipart calls (i.e. image uploads).
Also, no need to json_encode the response. That’s already available as responseText.
August 20th, 2009 at 8:19 am
@Jaisen: Thanks that works.
August 21st, 2009 at 7:51 am
@Jaisen, I’m having another issue with multipart post.
Error message is as follow
/Users/bhappy/localhost/experiments/twitter/site/bin/services/avatar.jpg
Fatal error: Uncaught exception ‘EpiOAuthException’ in /Users/bhappy/localhost/experiments/twitter/site/bin/includes/EpiOAuth.php:338 Stack trace: #0 /Users/bhappy/localhost/experiments/twitter/site/bin/includes/EpiTwitter.php(131): EpiOAuthException::raise(NULL, 0) #1 /Users/bhappy/localhost/experiments/twitter/site/bin/services/processStep.php(36): EpiTwitterJson->__get(’response’) #2 {main} thrown in /Users/bhappy/localhost/experiments/twitter/site/bin/includes/EpiOAuth.php on line 338
I used to have this working using the following code:
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret); $twitterObj->setToken($_REQUEST['tok'], $_REQUEST['sec']); $file = dirname(__FILE__) . "/" . $avatar . ".jpg"; $twitterObj->post_accountUpdate_profile_image(array('@image' => "@{$file}")); $resp->response;Please help.
Thank you.
Tee
August 21st, 2009 at 5:37 pm
@Tee, You need to post the output of $resp->responseText. This is the raw response from Twitter. Also, you should wrap your calls inside a try/catch block.
try{ $twitterObj = new EpiTwitter($consumer_key, $consumer_secret); $twitterObj->setToken($_REQUEST['tok'], $_REQUEST['sec']); $file = dirname(__FILE__) . "/" . $avatar . ".jpg"; $twitterObj->post_accountUpdate_profile_image(array('@image' => "@{$file}")); $resp->response; } catch(EpiOAuthException $e) { echo $e->getMessage(); }August 23rd, 2009 at 6:36 am
Does anyone have an example of using the callback url option that they woldn’t mind sharing? It seems to be the only thing I can’t figure out and it’s driving me nuts–more so because I’m certain Jaisen has made it incredibly easy to do. Thanks!
August 23rd, 2009 at 8:22 am
@drbigfresh, I recently added an example in the documentation.
http://wiki.github.com/jmathai/twitter-async#oauthcallback
August 24th, 2009 at 10:55 pm
What about creating friendships? (Making the user follow someone)
http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-friendships%C2%A0create
How do I implement this so after the user logs in it follows us (if they check the checkbox of course, but I know how to do that). Just need to know the method(?) name.
Thanks for the help
August 24th, 2009 at 10:59 pm
@Giles, Determining the method names are documented here: http://wiki.github.com/jmathai/twitter-async#methodnames.
It would be post_friendshipsCreate111111(array(’id’=>222222)) to have user 111111 follow user 222222.
August 25th, 2009 at 1:39 pm
Hey Jaisen. Great tips/advice here. I’m a newb with Twitter API but found it very simple to configure.
After the first hour of running it live my entire site crashed. Turns out twitter was down, which caused the obvious problem. I looked over the suggestions here for that and I hope I’ve resolved it so that if/when there is an outage or error with twitter it will merely skip the twitter API, and load my website.
I didn’t edit the EpiOAuth.php file rather edited my PHP script with the following:
try { $twitterObj = new EpiTwitter($consumer_key, $consumer_secret); $globes->twitter_auth = $twitterObj->getAuthenticateUrl(); } catch(EpiOAuthException $e) { echo $e->getMessage(); } ################# ## Check 4 twitter.. if($_GET['oauth_token']) { try { $twitterObj->setToken($_GET['oauth_token']); $token = $twitterObj->getAccessToken(); $twitterObj->setToken($token->oauth_token, $token->oauth_token_secret); // save to cookies setcookie('oauth_token', $token->oauth_token); setcookie('oauth_token_secret', $token->oauth_token_secret); } catch(EpiOAuthException $e) { echo $e->getMessage(); } } ######################### Will this work? Or should I just modify EpiOAuth.php at around line 249 where it says: switch($code) { case 400: throw new EpiOAuthBadRequestException($message, $code); case 401: throw new EpiOAuthUnauthorizedException($message, $code); default: throw new EpiOAuthException($message, $code); }Thanks.
August 26th, 2009 at 2:32 pm
This library is GREAT. I’ve been playing with seach today. I’ve made some alteration to let me do geocode search using Twitter. (I got Lat / Long from google api.
Anyway this is working great, but I can’t get paramters to work correctly. I need to get 100 results instead of default 15. Here is code
$twitterObjBasic = new EpiTwitter(); $resp = $twitterObjBasic->get_search(array('geocode' => $search_string, 'rpp' => 100)); return($resp);The geocoding is working but the 2nd parameter (rpp) is not. Here is what the query looks like when I hack into EpiTwitter line 36
geocode=30.0700179%2C-81.8879884%2C25mi&rpp=100
Any ideas on getting the seach to work with extra params, I need to add rpp, and show_user param
August 26th, 2009 at 3:13 pm
OK, to fix the search, I had to replace lin 36 with
that should be the default of how http_build_query works, but cleary is not in php 5.10
August 31st, 2009 at 7:53 am
I am new to twitter, i searched many way to show my twitter status on my site. but not get any hint. plz help
I need to show my ad status on my site
September 1st, 2009 at 12:51 am
@Jim, Thanks for the heads up. I submitted a patch including your suggestion plus a few other instances.
http://github.com/jmathai/twitter-async/commit/1912d06bcf41b6b49db7a5162a6f548129b17a58
September 3rd, 2009 at 2:51 am
@jaisen - Jason saw your latest patch, just wanted to let you know my server is at php 5.2.10 not 5.10, I use Drupal which does not yet support 5.3, but I have latest version of 5.2, your patch is good, but wanted folks to know that it’s not a patch needed only in older version of php. Sorry for my type on ver in orig post.
Jim
September 6th, 2009 at 10:58 am
Hi Jaisen,
Is this library only useful for OAuth based Twitter signup? Can this be used for basic authentication as well? Sometimes for backend processing (e.g. running some cron jobs) you need basic Twitter authentication. I liked your generic Twitter API calling methods, so can I use them with basic Authentication? Any suggestions?
September 6th, 2009 at 8:51 pm
@Aditya, Right now the library supports unauthenticated calls but not yet basic auth. This would be fairly trivial to add, I just need to figure out what how it should be exposed through the caller.
September 7th, 2009 at 4:46 pm
Hi Jaisen,
Thanks for your reply. Sure, library does support unauthenticated calls, but only with search API. As in EpiTwitter class you’re using $this->searchUrl for $url construction. For some Rest based APIs, you don’t need authentication (e.g. users/show) and you want to use $this->apiUrl.
It will be great if you can add support with additional parameter in __call function. May be $api_type. By default $api_type will be ’search’, but you can override it with ‘rest’. And based $api_type value, you can use different URL for $url construction when calls are unauthenticated.
Hope this make this library more flexible.
I’ll make temporary implementation in my environment, but will appreciate if you can support it officially.
Thanks,
Aditya
September 7th, 2009 at 5:03 pm
Hi Jaisen,
I added this part in EpiTwitter function -
in __call function added this -
$search_api = preg_match('/search|trends/', $name);and in if statement for unauthenticated calls, added this -
$api_url = $search_api ? $this->searchUrl : $this->apiUrl; $url = "{$api_url}{$path}?{$query}";And this works fine for me for all unauthenticated calls.
Let me know if you see any issue.
Thanks,
Aditya
September 10th, 2009 at 6:45 am
Hi Jaisen,
Is there an example with this library of using a text to post user status updates after they sign in using Oauth?
Thanks in advance,
Jaime
September 10th, 2009 at 6:56 am
Sorry, Just to clarify the last post, it should have said - using a text form to post user status updates
thanks,
Jaime
September 10th, 2009 at 1:46 pm
@Jaime, you just need to pass $_POST['fieldname'] into the status update function. It takes a “text” parameter in the array.
September 10th, 2009 at 5:38 pm
Hi Jaisen,
Worked Perfectly, Thanks!,
Jaime
September 10th, 2009 at 6:40 pm
@ADitya - why do you think basic auth is needed for cron jobs, etc?
I have found that when you store the users secret tokens, it is just as easy and a fast to login with those as it is with basic, both are a single call to authenticate, you only need to do the oauth handshaking the first time to get the users credentials, once you have their credentials, you can login on their behalf easily.
I’m just curions when I’d ever want to have to capture the users password to support a cron type job. I am doing some cron jobs but only for a few accounts now, if there is a good reason to use basic auth, I’d be interesting in learning more.
Thanks
JimF
September 10th, 2009 at 6:46 pm
@jason Russo - How did your check for twitter code above work? I find Twitter is down a lot, and i need to determine.
1. How to test if Twitter is avail.
2. How to let my users know when a call fails - gracefullly.
Right now I have generic try / catch to preven the fatal errors, but I’m not really showing the user what is happening, since I have not added any granularity to my error checker. If anyone has a good way to trap and display errors, I’d like to see their example.
September 13th, 2009 at 7:26 am
@Jim Fulford I need cron jobs to fetch public feeds based on keyword or some category interest, and not necessarily from any signed-in user. In that case there is no user who is authenticating to fetch his tweets. I fetch them if they are public, and relevant to my topic of interest.
September 14th, 2009 at 3:23 pm
Im missing something, and I cannot seem to figure it out — Ive been everywhere reading about this, and for some reason my mind isn’t ‘tracking’.
So, I can sucessfully (using this library) authenticate a user, get the app authorized, etc…
So, when I store the user specific secret/token in my userdb along with their twitter ID number, how does that help me over simply storing this information inside a single session cookie?
I mean, once I have all that in the db, if they return to my website again without being signed into twitter first, they will then get sent to the authentication URL over at twitter to authenticate, and the tokens again are returned when they are sent back to the callback correct?
I guess I just am not able to understand the advantages of storing the tokens/secrets inside my userDB if the user must first authenticate anyhow.
Can someone help me understand?
September 14th, 2009 at 6:27 pm
@lee,
You only have to do the Twitter initial authentication one time. One you store their tokens, you can sign in on their behalf. For example, let’s say a user visits your site after you have stored their tokens, and you want to show them their latest tweet, etc. You just need to make 2 calls
First you pass your keys and their keys, this signs them into Twitter (they don’t have to be signed in before they come to your site)
Then you get their latest status
$twitterUser = $twitterObj->get_usersShow(array('id' => $tid));As another example, on my site, I use the sign in with twitter methods to let users sign into my site with twitter. This does the twitter handshaking, etc. Then during their session, and they interact with Twitter, I just use the signle call above to make all the requests on their behalf. It works very well, (as long as Twitter is not over capacity)
Jim
September 14th, 2009 at 6:59 pm
@jim(thanks for the response):
In the first scenario (they don’t have to be signed into twitter prior to coming in to the site) that would then require them to have a separate username/password combination associated with my site which then would key to their twitterid and tokens, so I could then auth them, and do the requests.
Maybe Im over thinking this… I’ll give a bit of an overview of what my ‘model’ (theoretical) is, and see if the Sign in with twitter methods (which I think is what Im needing) are truely what I need.
1) User comes to my site - never been here before, clicks the “Signin with twitter” button (url is the authorize() url, so that it first prompts them to allow, second time, simply redirects back to callback (if logged in to twitter, otherwise prompts for login then redirects))
2) user comes in and creates some things which I HAVE to store in a database (ie a list of items, all assigned back against their ID)
3) User publishes said list (well a link to it) to their twitter acct. (but its state is stored in my db for future access/modification)
4) user signs out.
So I guess what Im struggling with is in the scenario Im using, what storing the tokens will do when the user comes back. If they’ve signed out (session destroy) or the cookie from my site has expired, the request will have to go through all over again and returns the user tokens again…
September 14th, 2009 at 7:44 pm
@lee,
Let me tell you a bit about how my site works, which may give you some ideas. I’ve built a Drupal site that does all kind of stuff with Twitter. Here is what I do.
1. When user comes to my site, I have sign in with twitter button. They hit this and I either sign them in, or create a new account on my site and sign them in. What is really cool, is I don’t have to have them type in anything to register for my site. I get everything I need from twitter.
2. When they join / register. I wrirte all their twitter profile data, and their tokens into a MySQL table. I don’t worry about storing it to session variables at all. Everything that is returned from verify credentials gets stored.
3. When they login with Twitter, I do the same thing, I update their profile on my site with everything from the verify credientals. So I always have their # of followers, latest tweet, bio, etc.
4. While on my site, they can look at their timeline, follow people, purge people that are not following them back, Follow Local people, follow based on keyword search, LOTS of cool Twitter tools. On all of these calls, I just use the tokens stored in the database to authenicate and act on their behalf.
5. I don’t reauthenticate them if they stay on my site 1 min or 10 hours, they can keep using the Twitter services.
6. (This is what may interest you). At 2:00 am my server contacts the twitter server to get a list of all friend and follower ids, for all of my users, and looks to see how many people started following them since the day before, by comparing yesterday’s ids. I just load their tokens from the database and login on their behalf and get the data (plus send automated tweeets, etc.) this is done with the databae tokens, and does not require authentication again.
7. Last thing, User can login to My Drupal site with my normal credentials, then I can act on behalf of the user w/o using Login with Twitter at all. This is how most Twitter services work on the net today, tweetdeck, tweetlater, hootsuite, etc. You create a login on their account, then give them your twitter id and passowrd. Then they act on your behalf. The Twitter signin / oauth lets you do the same things as these twitter services w/o haveing to get a password from the user. They just need to approve your app when they signin with twitter the first time.
I hope this helps.
Jim
September 14th, 2009 at 8:24 pm
@jim
That does help alot. The part where you’re not asking them to reauth after signing into your site using twitter (thereby creating the drupal account based on the twitter info) is being handled by never expire cookies?
Ive pretty much got it figured out…. A good way to do this is (from what I have with ALL your help)
1) Have user login with twitter
2) Store their tokens after getting them
3) Store a unique encrypted value into a cookie (never expired) which will identify them to my site forever (until they clear cookies anyhow)
4) Now, any time the user comes to the site, I use the cookie to identify the request, so they never have to sign in.. otherwise in the case of a non-existing cookie, they have to reauth. and thats desired.
September 15th, 2009 at 2:11 pm
So, one thing of note @All (file this away so you dont have the issue ive had which stopped development completely for me)…
IF you are developing, and need to change the system time on the server for some reason (test db timestamps in my case) —— TURN IT BACK BEFORE MAKING CALLS TO TWITTER.
Otherwise, you’ll end up as I did - Unable to get request tokens, when everything at work and at home match (two diff dev machines)…
*SIGH*
September 18th, 2009 at 4:37 pm
@Aditya, I added support for basic auth. Please check out the latest code from github.
http://wiki.github.com/jmathai/twitter-async#basic_vs_oauth
http://github.com/jmathai/twitter-async
September 19th, 2009 at 2:39 pm
I think I’m going this right, but it doesn’t seem to return anything for me other than the object information….
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret); $UserResults = $twitterObj->get_usersShow(array('screen_name' => 'xxxyyyzzz'));this is where I’m getting it from:
# screen_name. Specfies the screen name of the user to return. Helpful for disambiguating when a valid screen name is also a user ID.
Example: http://twitter.com/users/show.xml?screen_name=101010
September 19th, 2009 at 3:24 pm
@DrBigFresh, what you’re doing is correct. You need to access the response to ensure that the call completes. Line #3 below is all you need.
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret); $UserResults = $twitterObj->get_usersShow(array('screen_name' => 'xxxyyyzzz')); echo $UserResults->screen_name;September 23rd, 2009 at 3:46 pm
Hello jaisen,
I have a problem with this code:
I can update my status but when I have to get the public time line, I get this error:
/public/timeline.json
Could not authenticate you.
Thanks
September 23rd, 2009 at 4:18 pm
@kik3, are you using the latest version of the library from github?
The public timeline doesn’t require authentication. You can make an unauthenticated call using the following (right now it’s timing out for me).
Requires the latest version that included basic auth.
September 24th, 2009 at 5:58 am
@jaisen, I have the version on a pull from your repository on github, when i pull again, i get the message “already up to date”
i get the same error in this code
—-
/friends/timeline.json Could not authenticate you.
September 24th, 2009 at 9:08 am
@kik3, I never really looked at the documentation before responding. Looks like your method names are incorrect.
Determining method names is documented here: http://wiki.github.com/jmathai/twitter-async#methodnames
September 24th, 2009 at 9:18 am
@jaisen thx!
September 25th, 2009 at 6:19 pm
@jaisen - I’ll be launching a site next week that uses your lib, and I am writing blog to credit the authors, etc. Here is the article I’m working on, let me know what page you would like the article to link back too. I’ll be posting this on Drupal.org about Wed, and it will get some activity when I make the posting.
http://www.gotwitr.com/content/gotwitr-site-built-drupal
September 28th, 2009 at 8:42 am
@Jim, feel free to link directly to the documentation page. http://wiki.github.com/jmathai/twitter-async. Thanks.
September 28th, 2009 at 3:49 pm
@jaisen, have you looked at the Twitter Streaming API http://apiwiki.twitter.com/Streaming-API-Documentation#ParsingResponses
September 28th, 2009 at 11:42 pm
Hello Jaisen,
Following is code that i am using to set update but it is not updating. and no error message is show….whats wrong here.
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret, $_COOKIE['oauth_token'], $_COOKIE['oauth_token_secret']); $twitterInfo = $twitterObj->post_statusesUpdate(array('status' => 'Getting some work done.'));September 28th, 2009 at 11:47 pm
What is stored in twitterinfo->response after the call?
September 28th, 2009 at 11:55 pm
thanks for reply…following is the response
Fatal error: Uncaught exception ‘EpiOAuthUnauthorizedException’ with message ‘{”request”:”/statuses/update.json”,”error”:”Read-only application cannot POST”}’ in /home/content/c/a/r/carlsys123/html/ranosys/client/jtwitter/EpiOAuth.php:249 Stack trace: #0 /home/content/c/a/r/carlsys123/html/ranosys/client/jtwitter/EpiTwitter.php(100): EpiOAuthException::raise(’{”request”:”/st…’, 401) #1 /home/content/c/a/r/carlsys123/html/ranosys/client/jtwitter/random.php(18): EpiTwitterJson->__get(’response’) #2 {main} thrown in /home/content/c/a/r/carlsys123/html/ranosys/client/jtwitter/EpiOAuth.php on line 249
September 28th, 2009 at 11:59 pm
Your Twitter app is set to read only mode so you cannot post status from it. Log onto Twitter go to osuth clients and pick the read and write access radio button
jimf
September 29th, 2009 at 12:02 am
i have changed it radio button…i set it read and write….but still same error is showing….will it take time to update application information???
September 29th, 2009 at 12:09 am
When you approved the oauth you only approved read access so that is what tou have with that login. Easy to fix. Go to Twitter connections and revoke your app. Them login and approve it again. This will grant rw access to your Twitter account.
September 30th, 2009 at 10:08 pm
@jaisen In one of your comments about you’ve mention the timeout for CURL call is 30 seconds, but in the library its 3 seconds. Just wanted to let you know about the discrepancy.
October 1st, 2009 at 6:58 am
@Aditya, You might have an older version of the library. The current version defaults to 30 seconds. See line 19: http://github.com/jmathai/twitter-async/blob/master/EpiOAuth.php
October 2nd, 2009 at 8:57 am
Hello to you all!
Thanks to @jaisen for this great lib. I found a solution to my problem here.
I have this question about twitter ‘follow’… What happens if you try to follow someone twice or many times? Does twitter punish for that?
How can I use this Lib to check if I’m already following someone?
My next question is critical.
I plan to store the tokens in a db and use them later. The question is, if someone revokes access, how am I going to know so as to update my db? Anyone help please.
Thanks so much
October 2nd, 2009 at 11:14 am
@enstine, Twitter doesn’t punish you for checking if a friendship exists and actually provides an api for it. To check if credentials are valid you want the verify credentials api.
$twitterObj->get_accountVerify_credentials(); $twitterObj->get_friendshipsExists(array('user_a' => 123, 'user_b' => 456));http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-account%C2%A0verify_credentials
http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-friendships-exists
October 3rd, 2009 at 12:50 am
Hi Jaisen,
Thanks for the response.
If I understand well, users are said to be friends if they both follow each other
$twitterObj->get_friendshipsExists(array('user_a' => $id_a, 'user_b' => $id_b));What I’d like to find out is if I’m already following the user in question.
I was wondering if twitter punishes for trying to follow the same user multiple times….
Thanks
October 5th, 2009 at 8:15 am
I really still do not understand this Catch Exception aspect. I have tried yet … no possitive results
October 5th, 2009 at 6:20 pm
@enstine, per the documentation the friendships/exists api tells if one user is following the other.
“Will return true if user_a follows user_b, otherwise will return false.”
The exceptions are standard php exceptions. For more information see: http://php.net/exceptions.
October 5th, 2009 at 6:22 pm
All, I’ve pushed a major update to the twitter-sync library (version 2.0) to github. It should be 100% backwards compatible except for re-factored exceptions. It also supports a debug mode which includes headers in the exception message. If you’re able to test it then please give it a try.
http://github.com/jmathai/twitter-async/tree/2.0
October 6th, 2009 at 12:45 am
HI @jaisen, thanks for this very helpful information. Please what happens if a user revokes access? how is this handled?
I have a system where I get the token and store in the db. I should be able to remove these entries if the user revokes access.
October 6th, 2009 at 11:38 am
@enstine, you’ll receive an exception. You can check by calling the verify credentials api.
$response = $twt->get_accountVerify_credentials(); try { $response->id, $response); } catch(EpiTwitterException $e) { // check $e->getMessage() for some text // remove from database }With the new exceptions from the 2.0 branch you can specifically catch the EpiTwitterNotAuthorizedException to make sure that it’s invalid credentials that threw the exception and not worry about checking $e->getMessage().
October 6th, 2009 at 4:15 pm
@jaisen, I’ve been using the new 2.0 branch and things are working pretty well. The one question I have for you is changes to the exception handler.
In the past, with my try / catch logic, my users would not see a twitter error, it was all handled by my code. Now, I’m getting the browser window filled with the exception as if I did not have a try catch loop. Here is a sample of the code.
function GetUser($uid,$tid) { $consumer_key = variable_get('twitter_consumer_key', ''); $consumer_secret = variable_get('twitter_consumer_secret', ''); $account = load_twitter_account($uid); $twitterObj = new EpiTwitter($consumer_key, $consumer_secret, $account[token], $account[secret]); $twitterUser = $twitterObj->get_usersShow(array('id' => $tid)); return $twitterUser; }code in question here….
$friend = GetUser($user->uid, $screen_name); try { db_query("insert into {gotw_friends} (uid, twitter_id, screen_name, name, description, profile_image_url, url, friend_group) values (%d, %d, '%s', '%s', '%s', '%s', '%s', %d)", $user->uid, $friend[id], $friend[screen_name], $friend[name], $friend[description], $friend[profile_image_url], $friend[url], $form_state['values']['friend_group']); twitter_log($user->uid, 'GetUser', 'Friend Add Form', $friend); //success } catch (EpiOAuthException $e) { twitter_log_error($user->uid, 'Friend Add Form', $e); //failure }Now what I should get is an entry in the database if all goes well, or an entry in my error log if I get an error. But instead I’m halting on the error with the error text from twitter on the browser as if I had no try catch.
October 6th, 2009 at 4:57 pm
@Jim, Thanks for testing it out. Your code is correct but the EpiOAuthException isn’t what you want to catch anymore.
If you want to catch all exceptions thrown by EpiTwitter, then use EpiException. If you want to catch an exception where Twitter returned a non 200 or 300 response code, then use EpiTwitterException. If you’d like to catch a specific response, then you can use one of the following listed under “Proposed exceptions”.
http://wiki.github.com/jmathai/twitter-async/seeking-input-for-exception-refactoring
October 8th, 2009 at 1:32 am
Hi Jaisen,
$response = $twt->get_accountVerify_credentials(); try { $response->id, $response); } catch(EpiTwitterException $e) { // check $e->getMessage() for some text // remove from database }an error within the try block?
October 8th, 2009 at 2:04 am
Hi @Jais2n,
I still get this error
Here is my code…
try { echo $twitterInfo->id; } catch(EpiTwitterNotAuthorizedException $e) { echo $e->getMessage(); }Here is the error I get
An exception occurred in EpiTwitter The response is {”request”:”/account/verify_credentials.json”,”error”:”Could not authenticate you.”}
Fatal error: Uncaught exception ‘EpiTwitterNotAuthorizedException’ with message ‘An exception occurred in EpiTwitter The response is {”request”:”/account/verify_credentials.json”,”error”:”Could not authenticate you.”} ‘
October 9th, 2009 at 4:33 am
hello everyone,
I got it figured out. I’m smiling now
Thanks
October 10th, 2009 at 1:16 am
Jaisen, I have an interesting issue with the new lib, it’s not a bug, but I thought I’d bounce an idea off of you.
Twitter Error handing it a pain when people hit follower limits, etc. I have to inspect the text that I get from Twitter and then do someting for the user. So I’ve done this in the past. In my catch loop, I call this twitter_log_error function that decodes the message.
function twitter_log_error($uid, $request, $error) { $er_obj = json_decode($error->getMessage()); db_query("insert into {gotw_api} (uid, status, request, response_code, response_text, timestamp) values (%d, '%s','%s',%d, '%s', now())",$uid , $request ,$er_obj->request , $error->getCode(), $er_obj->error); }This lets me get the error code, and the text returned from Twitter. This stopped working with the update due to this code
// $message = "An exception occurred in EpiTwitter\n" // . "The response is {$response->data}\n"; $message = $response->data;Anyway, I commented out your nice helpful code so that I could run json_decode on the error response, but I know when I get your next update, it won’t work until I change your code again. (I don’t like making hacks to source, ever)
Another option would be for me to do a substr() and remove your text, but I was wondering if you had a better idea. How is the best way for me to get the actual error reponse from twitter so I can check it and respond to my users appropriately.
Jim
October 10th, 2009 at 6:58 am
@Jim, Good suggestions. I pushed some changes to the 2.0 branch which makes the exception message a json encoded string. you can json_decode and access any of these properties: text, response, headers.
Headers are only available if you call the setDebug method and pass in true.
The response is json_encoded so you’ll need to decode it first.
Hope that helps.
try { $twt->id; }catch(EpiTwitterException $e){ $messageArray = json_decode($e->getMessage(), 1); print_r($messageArray); }October 10th, 2009 at 9:07 am
Hi Jaisen. I am updating my status through the below code and first time it works perfectly. The next time I update the status with another App (another consumer_key and consumer_secret), I don’t get it to work.
When dumping the response I get the older status’s App name and data.. Newer is not updating on twitter and dumped data.
$consumer_key = 'blahblah'; $consumer_secret = 'blhablah'; $twitterObj = new EpiTwitter($consumer_key, $consumer_secret); $twitterObj->setToken($_GET['oauth_token']); $token = $twitterObj->getAccessToken(); $twitterObj->setToken($token->oauth_token, $token->oauth_token_secret); $twitterInfo= $twitterObj->get_accountVerify_credentials(); $tok = file_put_contents('tok', $token->oauth_token); $sec = file_put_contents('sec', $token->oauth_token_secret); $twitterStatus = $twitterObj->post_statusesUpdate(array('status' => 'blah!')); print_r($twitterStatus->response); //words perfectly for the first time, but not getting newer apps dataPlease help me in solving this issue!
Thanks
October 10th, 2009 at 9:55 am
Well when I delete my first update, i can successfully update my new status..
means first time i update the status from an app, it appears on twitter, next time after ONLY deleting that update, i can post another update from another app..
what can be the reason? i can’t afford everytime deleting the updates for posting new update from my another app.
October 10th, 2009 at 11:53 am
@jaisen - works great, thanks! JF
October 11th, 2009 at 4:37 pm
@Kalpesh, could you email me more of the code you’re using?
Basically, each call has a response code and the library works in such a way that you do one of the following:
1) Access the code or results and it’s 200 - all good.
2) Access the code or results and it’s non-200 and an Exception is thrown
3) You don’t access the code or results, and no one will ever know what happened
October 11th, 2009 at 6:53 pm
After a long process I have finally rolled oauth out on my site and would love for you all to take a look and let me know how it’s working.
http://PhishTwit.com (sound plays automatically)
You can basically sign in and post to Twitter right from the page, but the difference is I’m using an iframe so the entire page (which is heavy) doesn’t have to reload.
I also rigged it up so the Tweet includes a link back to my site though you can deselect that option before you post.
The one thing I’m still not 100% on is the exceptions (esp around rate limits and Twitter going down). I’m sure if either of those occur the site will crash and burn but I plan to look at that in more detail at a later time.
Thanks to everyone in this comment thread for their helpful questions and especially their helpful answers. And mega thanks to Jaisen of course.
Take care all,
Todd
October 12th, 2009 at 1:01 pm
@Jaisen. Its working now as it should, without changing any code. May be it was some problem on Twitter side that time?
October 13th, 2009 at 9:32 am
Hi,
I have a couple issues:
first of all, I’m using the copy of the library that came with the above blog post, which works fine. However, whenever I try to use the current version of the library from github, it just times out on oAuth errors… Is anyone else experiencing this?
Secondly, I’m trying to make some unauthenticated calls using the library. Whenever I do that, I get 401 errors about an expired token. Even though I’m not even asking to be authenticated. Here’s my code:
$twitterObj = new EpiTwitter(); /* Run unauthenticated request */ $followers = $twitterObj->get_followersIds(array('id' => '77252038')); try{ echo $followers->responseText; }catch(EpiOAuthException $e){ echo 'We caught an EpiOAuthException'; echo $e->getMessage(); }catch(Exception $e){ echo 'We caught an unexpected Exception'; echo $e->getMessage(); }What am I doing wrong here?
October 13th, 2009 at 9:50 am
@Michael, I haven’t seen any issues with the current version from github. I would definitely suggest using it over the one linked to from this blog post (I’ve been meaning to replace the link to the zip with a link to github).
I tested with the latest version and it works ok for me.
jmathai@[~/Y/twitter-async]: cat z.php < ?php include 'EpiCurl.php'; include 'EpiOAuth.php'; include 'EpiTwitter.php'; $twitterObj = new EpiTwitter(); /* Run unauthenticated request */ $followers = $twitterObj->get_followersIds(array('id' => '77252038')); try{ echo $followers->responseText; }catch(EpiOAuthException $e){ echo 'We caught an EpiOAuthException'; echo $e->getMessage(); }catch(Exception $e){ echo 'We caught an unexpected Exception'; echo $e->getMessage(); } echo "\n"; jmathai@[~/Y/twitter-async]: php z.php [79773418,79519740,79527579,79395859,65456543,39671474,16435117,77328211,21732157,20404999,15972892]October 14th, 2009 at 1:03 pm
Hi Jaisen
Me again and I have another question on StackOverFlow - no one seems to be able to answer it and I am hoping you can help me with it. http://bit.ly/prSK4
Simply, every time I get a user that submits a message with an apostrophe in it, Twitter escapes it when I status update via their API using your awesome classes.
I understand the need to escape characters but I need to know how to get twitter to accept apostrophes, single quotes and quotes without escaping them!
Thanks
October 14th, 2009 at 1:10 pm
@Abs, I replied on stack overflow.
October 14th, 2009 at 1:23 pm
Thanks for the reply Jaisen - I repped you on there just for writing this library.
Someone managed to let me know I had magic_quotes_gpc - epic failure that I didn’t think of this as there is nothing wrong with your library and twitter (sometimes) so it must be me!
Thank you once again. :)
October 15th, 2009 at 10:17 pm
Hi Jaisen,
While using oauth_callback parameter, have you tried any localhost url as callback url?
This will be very handy for local dev setup.
I tried using it, and apparently it worked for 3-4 calls, then after that it stopped working. Now Twitter redirects to my default callback url that I mentioned in the application settings page. Also, if I mention any non-localhost url, i.e. with some .com extension, which is different from my default callback url, Twitter redirects me to that url.
Can you comment if you have tried this, or throw some light why this weird issue is happening?
BTW, how do you do your local dev testing with oauth requirements? Your inputs will be appreciated!
October 15th, 2009 at 10:25 pm
@Aditya, I can’t comment on using localhost. I read about some issues with opera but not sure if they extend beyond that.
I do local development by aliasing a top level domain (i.e. my.example.com) in my hosts file.
Add something like:
127.0.0.1 my.example.com
to your hosts file and set that up as a virtual host in apache.
I haven’t had any issues using this method.
October 16th, 2009 at 6:35 am
Hi Jaisen,
Thanks for a quick reply. I tried above options, but unfortunately its not working. BTW, Twitter is now redirecting to localhost callback url, but there is some issue with how I handle urls as its getting redirected to default callback. I’ll debug this - sorry for bothering you.
-Aditya
October 18th, 2009 at 11:03 pm
Hi Jaisen, all:
Thanks for providing this library - it definitely appears to be the most active PHP OAuth client for Twitter.
I too am having difficulty getting the profile image upload to work. I have seen threads on Twitter’s APIWiki suggesting that passing the type info either one of the following ways can help:
Do you or anyone else reading this thread recommend one or the other, or better yet, a slightly modified approach that actually works? :) I’ve got a great site built all around giving users custom avatars but I’m having trouble getting this last bit to work.
Also - anyone know why the “Expect:” header found in all the CLI curl examples is so crucial? Looks like EpiOAuth adds this so I imagine client code should be good to go?
Thanks!
funkminsta
October 18th, 2009 at 11:12 pm
@funkminsta, The image uploading has been working well in the library for some time now. Questions:
1) Are you using the latest version from GitHub?
2) What do you get if you access the response (a required step with twitter-async)?
Regarding the expect header. Not sure why but Twitter returns an error if you give them an expectation. This is handled in the library though.
October 18th, 2009 at 11:36 pm
@jaisen
1) yes - I pulled down from github via git clone a couple of hours ago
2) I had not been trying to access the response; didn’t realize this was required. Adding that now, I get an empty string.
thnx,
funkminstsa
October 19th, 2009 at 10:09 am
@Jaisen: I’ve confirmed that php unit tests run to completion without error and I’ve tried changing my code to match.
I noticed that the unit tests make 2 calls in a row to post_accountUpdate_profile_image(), I’ve tried to replicate this as well.
Although I see HTTP 200 response codes from the calls themselves, I still receive the access denied messages when trying to access the new profile images by visiting Twitter:
http://a0.twimg.com/profile_images/Freddie.png
returns:
similar to what other users have been seeing when they don’t pass the image mime/type. So I think the unit test works in the sense that we get a 200 response but I suspect it actually fails to update the test user’s profile image :/
I humbly suggest that the unit tests be updated to try a different image, try passing the mime/type and perhaps try a blocking curl request of the profile image URL returned in the response from Twitter.
Cheers & thanks again for all your help,
funkminsta
October 19th, 2009 at 10:43 am
More information:
Finally some degree of success! I tried images of different mime types and found that gif, jpg upload & display successfully but that png images will not.
I suspect this is an issue on Twitter’s end and will file a bug accordingly.
Can anyone else confirm this behavior?
thnx,
funkminsta
October 19th, 2009 at 10:59 am
I’ve confirmed it with the unit test by adding the mime type. There’s a bug that Twitter marked fixed but should be reopened.
http://bit.ly/496Hn3
October 19th, 2009 at 11:30 am
Excellent API, very nice. I have a quick question. I’m having trouble with the create favorites call.
I’m able to update statuses, delete them, delete direct messages, reply, etc. But for some reason favoritesCreate eludes me.
It just seems to vanish into thin air!
Any help would be appreciated.
October 19th, 2009 at 12:25 pm
@patrick, Are you accessing the response? You need to do that else it will potentially vanish. Also, what does $response->responseText contain?
October 19th, 2009 at 12:34 pm
@jaisen
I got it, I looked at your other blog post from march and found the solution.
$method = “post_favoritesDestroy{$id}”;
$response = $toauth->$method();
Thanks anyway, though!
October 20th, 2009 at 1:46 pm
So recently I noticed that with Twitter unreachable, my site hangs as well. This because I’m either showing a request link or doing an accountVerify call to Twitter when the page loads. I understand how to wrap my accountverify call in a try and catch, i’m just wondering if I can do the same with my requestlink, and if so, what kind of error structure you would propose… I currently simply have:
$request_link = $twitterObj->getAuthenticateUrl(null,array(’oauth_callback’ => ‘http://path.to/index.php’));
Your help is much appreciated!
October 20th, 2009 at 2:46 pm
So I more or less figured out the request_link questions above.. I believe the only error that could occur there is an EpiOAuthException, correct? I simulated that by changing the oAuth URLs in EpiTwitter.php and it correctly caught the exception.
NOW, I’m trying to try..catch my get_accountVerify_credentials(); call… I currently have it set up as follows:
/* Run request on twitter API as user. */ $credentials = $twitterObj->get_accountVerify_credentials(); try { $credentials->id; }catch(EpiOAuthException $e) { $type="loginfail"; print_bcc_header(); print_bcc_error($type); print_footer(); exit; }catch(EpiTwitterNotAuthorizedException $e) { $type="authorizefail"; print_bcc_header(); print_bcc_error($type); print_footer(); exit; }catch(EpiTwitterException $e) { $type="unknown"; print_bcc_header(); print_bcc_error($type); print_footer(); exit; }Is there an exception type I’m missing here or not explicitly identifying?
Thank you so much for your help!
October 20th, 2009 at 2:53 pm
@Michael, That looks correct. In theory you could still receive an EpiOAuthException there. It’s a little messed up and you can always catch the base Exception if you wanted to be sure.
I’ve proposed a new set of exceptions that make a lot more sense. This is already present in the 2.0 branch of the code and will eventually get merged into master.
http://wiki.github.com/jmathai/twitter-async/seeking-input-for-exception-refactoring
October 20th, 2009 at 2:57 pm
@Michael, At some point I added a timeout parameter to solve the hanging issue. It defaults to 30 seconds. If your calls are hanging for longer than that, then you’ll want to grab a newer version from Github.
You can set the timeout to something different by calling:
October 20th, 2009 at 3:02 pm
Thank Jaisen.
I’m already using the new set of exception you list on the wiki, as I’m using the 2.0 branch of the code.
What I’m confused by I guess is when I look at EpiTwitter, at the bottom I only see 1 exception defined: class EpiTwitterException extends Exception {}
And in EpiOAuth.php, I see a few:
case 400: throw new EpiOAuthBadRequestException($message, $code); case 401: throw new EpiOAuthUnauthorizedException($message, $code); default: throw new EpiOAuthException($message, $code);This doesn’t sync up with what you’ve written on the wiki:
case 400: throw new EpiTwitterBadRequestException($this->__resp->data, $this->__resp->code); case 401: throw new EpiTwitterNotAuthorizedException($this->__resp->data, $this->__resp->code); case 403: throw new EpiTwitterForbiddenException($this->__resp->data, $this->__resp->code); case 404: throw new EpiTwitterNotFoundException($this->__resp->data, $this->__resp->code); default: throw new EpiTwitterException($this->__resp->data, $this->__resp->code);As I don’t see those EpiTwitter[*something*]Exceptions defined anywhere?? Just EpiTwitterException
Moreover, I don’t understand the priority of these exceptions. In the Wiki you have for instance EpiTwitterNotAuthorizedException which gets thrown with a 401 HTTP code… However looking at EpiOAuth.php, you have EpiOAuthUnauthorizedException which also gets thrown with a 401 HTTP error???
When does which error get thrown?
Again, truly appreciate your help ;)
October 20th, 2009 at 3:07 pm
@Michael, You’ll find those in EpiTwitter.php.
http://github.com/jmathai/twitter-async/blob/2.0/EpiTwitter.php#L188
October 20th, 2009 at 3:13 pm
INDEED! So here’s what happened… I was on github and switched the branch to 2.0 and hit download, assuming it would download the 2.0 files… however I just noticed that apparently it always downloads the master branch files, even when you’re looking at the 2.0 branch… so I was still on the latest version of the master branch… switching to 2.0 now.
Just one final question re Exceptions for the same HTTP error code.
I assume that OAuthExceptions only get thrown as part of the authorization process and that any request to an API endpoint resulting in a 401 error for instance, will throw a EpiTwitterNotAuthorizedException and not a EpiOAuthUnauthorizedException… If that’s correct, then I think all my questions are answered ;)
October 20th, 2009 at 3:18 pm
@Michael, Correct! OAuthExceptions are only going to be thrown for:
* getAccessToken()
* getAuthenticateUrl()
* getAuthorizeUrl()
* getAuthorizationUrl()
* getRequestToken()
October 21st, 2009 at 12:08 am
For some reason I’m getting this error when trying your code: Fatal error: Call to undefined function curl_multi_init() in C:\wamp\www\memozu\EpiCurl.php on line 21 Any ideas? Thanks.
October 21st, 2009 at 12:19 am
@Dom, this library uses multi curl which doesn’t seem to be available on your system.
October 23rd, 2009 at 12:38 am
A note that anyone using the twitter-async library can follow @apiclient on Twitter for automatic updates anytime code gets pushed to github.
http://twitter.com/apiclient
October 23rd, 2009 at 2:48 am
Hi @Jaisen
I’m using this piece of code to update user status from within my site
$Twitter = new EpiTwitter($consumer_key, $consumer_secret); $Twitter->setToken($_SESSION['oauth_token'],$_SESSION['oauth_token_secret']); try { $status=$Twitter->post_statusesUpdate(array("status" => $Txt)); $status->response; } catch(EpiTwitterException $e) { // check $e->getMessage() for some error }It will work for a user just once. If you try again, you get no error and the status not updated. IF you delete the post from your twitter profile and try again, it works. Is there a problem with the code or it’s twitter trick to fight spamming?
October 23rd, 2009 at 4:30 am
@enstine…
Are you trying to post the same text as the new status update?
Twitter won’t let you post the same update twice in a row, which sound like it could be the “problem.”
One way to know is to inspect the status id returned from the call to post_statusesUpdate. It will send you the previous id instead of a new one if this is happening.
Hope this is your solve because it’s really not a problem — it’s the expected behavior.
TL
October 23rd, 2009 at 4:39 am
Hi @Todd, you are certainly right. I’ll diversify the text and see what happens
October 27th, 2009 at 3:12 am
Please, help me!
I see the following code on my index page:
Fatal error: Uncaught exception ‘EpiOAuthException’ in /home/c/1/0/27524/27524/public_html/includes/EpiOAuth.php:347 Stack trace: #0 /home/c/1/0/27524/27524/public_html/includes/EpiOAuth.php(324): EpiOAuthException::raise(NULL, NULL) #1 /home/c/1/0/27524/27524/public_html/includes/EpiOAuth.php(39): EpiOAuthResponse->__get(’oauth_token’) #2 /home/c/1/0/27524/27524/public_html/index_ok.php(49): EpiOAuth->getAuthenticateUrl() #3 {main} thrown in /home/c/1/0/27524/27524/public_html/includes/EpiOAuth.php on line 347
Why? How could I solve this?
October 27th, 2009 at 3:37 am
If I comment the line 347 throw new EpiOAuthException($message, $code);
the oauth_token is null.
Please, help me!
October 28th, 2009 at 10:41 pm
Hi jaisen. I am not able to post Non-English characters with oAuth.
I researched lot and found that we have to encode status in UTF-8 to get it to work. I tried utf8_encode function to encode status and sending POST request but its not working.
Can you please explain where should I use utf8_encode in order to post any Non-English characters in status? I am using it like this:
$result = $twitterObj->post_statusesUpdate(array('status'=>utf8_encode($status))); print_r($result->responseText); //it shows 'incorrect signature'.. for english characters is works fineOctober 29th, 2009 at 2:11 am
I was just wondering, how can I retrieve the status_id after submitting the twitter status?
November 1st, 2009 at 9:38 am
Could anyone help me out with my above “Non-English Characters” query?
Thanks
November 2nd, 2009 at 10:13 pm
Hi Jaisen - I noticed you published some “hacks” to enable lists etc with the paths with usernames in them etc. Would you mind publishing a couple lines on this blog re usage? Also - I see you only updated the main branch and not 2.0?
November 2nd, 2009 at 11:05 pm
The only modification needed is this line: http://github.com/jmathai/twitter-async/blob/master/EpiTwitter.php#L32
Usage can be seen from the unit tests here: http://github.com/jmathai/twitter-async/blob/master/tests/EpiTwitterTest.php#L305
I pushed the 2.0 branch with the hack to Github for now, but will implement a better solution before merging to master.
November 3rd, 2009 at 5:10 am
I managed to find bug and now everything is working flawlessly. I think I was only getting such type of error as no one here was replying.
November 4th, 2009 at 9:00 pm
@Kalpesh, could you let me know what you fixed so I can include it in the library?
November 8th, 2009 at 12:12 am
Wanted to let everyone know that the 2.0 version of the library is available on Github. Here are the release notes: http://wiki.github.com/jmathai/twitter-async/twitter-async-20-release-notes
The documentation is updated as well: http://wiki.github.com/jmathai/twitter-async
November 8th, 2009 at 11:18 pm
Hi Jaisen,
I’m using latest 2.0 version, and everytime I try to access the response for any api request, it gives me Notice for the first response parameter I try to access.
E.g.
If I have following,
$user_info = $twitter_obj->get_basic(’/users/show.json’, array(’screen_name’ => $screen_name));
echo $user_info->id;
echo $user_info->name;
I get following Notice message only for the ‘id’ parameter - Notice: Undefined index: id in /path/to/lib/EpiTwitter.php on line 217
And then it prints ID and Name values correctly. Why does it give notice?
November 9th, 2009 at 12:21 am
Hi Jaisen,
I’m getting this error randomly for users/show api request -
{”request”:”/1/users/show.json?screen_name=somename”,”error”:”Not found”}
It’s taking API Version = 1, but I guess it’s not taking API Versioned URL?
But if I run this request in forloop, not all API requests throw this error, but a specific screen_name throws that error.
I don’t set API Version explicitly. It uses the default one. Do you know what’s wrong going on?
November 11th, 2009 at 10:46 pm
Hi Jaisen,
I’m trying to use statuses/update method from your latest code version. I’ve sign-in action working fine, and OAuth Token and OAuth Secret are saved in database properly.
Here is how I’m using them -
$twitter_api = new EpiTwitter($consumer_key, $consumer_secret, $user->getOauthToken(), $user->getOauthSecret); $update = $twitter_api->post_statusesUpdate(array('status'=>$text)); $status_id = $update->response['id'];And it keeps giving me following error message -
500 | Internal Server Error | EpiTwitterNotAuthorizedException
{”request”:”/1/statuses/update.json”,”error”:”Invalid / expired Token”}
What can be the issue? I tried signing-out and signing-in back again to see if the token is really expired. But nothing worked.
Any inputs will be appreciated.
November 12th, 2009 at 12:12 am
@Aditya, could you try again tomorrow. Twitter was blowing up today with errors and that might have been the cause.
http://status.twitter.com/post/240542434/working-on-high-number-of-errors
November 12th, 2009 at 2:28 am
Hi to all
I have been trying to upload images to my twitter profile with the method ‘post_accountUpdate_profile_image’ without success. I have followed all the post, comments, issues I found and coding all the suggestions (specifing mime types, different formats etc…) but nothing. The method does’nt give error but the image is not updated to the profile on Twitter. Some advance on this topic?
I’m sure that I’m using the last version of twitter-async.
My code is very simple and based on this tutorial:
post_statusesUpdate(array('status' => $statusText)); echo $resp->code; $file = dirname(__FILE__) . '/sampleimage.png'; $resp = $twitterObj->post_accountUpdate_profile_image(array('@image' => '@{$file}')); //THIS NOT echo $resp->code; ?>Thanks!
November 12th, 2009 at 2:48 am
The code here:
include 'EpiCurl.php'; include 'EpiOAuth.php'; include 'EpiTwitter.php'; include 'secret.php'; $twitterObj = new EpiTwitter($consumer_key, $consumer_secret, $_COOKIE['oauth_token'], $_COOKIE['oauth_token_secret']); $statusText = "Testing Updating Status"; //THIS WORKS! $resp = $twitterObj->post_statusesUpdate(array('status' => $statusText)); echo $resp->code; $file = dirname(__FILE__) . '/sampleimage.png'; $resp = $twitterObj->post_accountUpdate_profile_image(array('@image' => '@{$file}')); //THIS NO echo $resp->code;November 12th, 2009 at 9:39 am
@Jesus, there are known bugs on Twitter’s end with PNGs. Try using a JPEG and see if that works.
November 12th, 2009 at 10:55 pm
Thanks for your response jaisen.
I’tried with jpeg, png and gif and nothing works. anyone has an example that works?
November 22nd, 2009 at 4:48 pm
Hello everyone,
I’m currently receiving an EpiOAuthUnauthorizedException in my callback page but only when supplying an oauth_callback url in the getAuthenticateUrl() method.
On the callback page, when I echo out the $token from the getAccessToken() method I get “/oauth/access_token Invalid oauth_verifier parameter.” I can see that Twitter is supplying the oauth_verifier in the querystring on the callback page but it doesn’t appear to have any effect.
The weird thing is that the callback page works fine if the getAuthenticateUrl() is called with no arguments. (ie: no oauth_callback parameter)
Is anyone else experiencing this or would have an idea of what I may be doing wrong?
$authenticateUrl = $twitterObj->getAuthenticateUrl(null, array(’oauth_callback’ => $callbackUrl));
(where $callbackUrl = “http://SERVER_NAME/functions/twitterOAuth.php?mode=$mode”)
Regards,
- Jeremy
November 23rd, 2009 at 1:34 am
@Jeremy, are you following the instructions here completely?
http://wiki.github.com/jmathai/twitter-async#oauthcallback
December 1st, 2009 at 8:54 pm
Hi Jaisen,
Ahh yes, have found my mistake. Was missing the extra arguments in the getAccessToken method.
Thanks :) Works beautifully!
- Jeremy
December 2nd, 2009 at 11:29 am
Jaisen,
I have a problem that I can’t seem to work out.
When I use this:
$responses[] = $twitterObj->post_direct_messagesNew( array (’user’ => $bccrecip["twid"], ‘text’ => stripslashes($directmsg)));
if $directmsg is a string containing an ampersand, the string gets broken off at the ampersand and only the part before the ampersand gets posted to Twitter.
I’ve tried urlencode, htmlspecialchars, htmlentities and utf8_encode on $directmsg, and none of those seem to fix the problem. What should I be doing??
Thanks!!
December 2nd, 2009 at 1:49 pm
Please ignore my question above… I hope I haven’t wasted your time… The problem was that I wasn’t escaping the javascript variable in the js that was passing it as an ajax post to my php.. the ampersands never made it to PHP ;)
December 2nd, 2009 at 1:53 pm
I hadn’t got around to looking into it yet :). Glad it’s working.
December 3rd, 2009 at 3:09 pm
Jaisen,
Is it possible that the version downloaded from github is not the same as the one displayed on github? When I look at EpiTwitter.php on github, it has a line: protected $isAsynchronous = false; (line 26). When I then click download (regardless of when I choose ZIP or TAR), the downloaded version of EpiTwitter.php does NOT contain that line…
How’s that possible?
December 3rd, 2009 at 3:10 pm
Also, the files in the ZIP/TAR have a file date of November 4, vs. displayed on GitHub of November 6… it seems they are really out of sync and your most current version is not avail for download???
December 3rd, 2009 at 3:18 pm
@Michael, their download link seems to be out dated. It actually references the commit from Nov 4th instead of the latest one. I’ve never used that link so I haven’t noticed. I’d use git to pull the repository down.
December 3rd, 2009 at 3:21 pm
OK - i’ll try that…
Any reason why I would be getting “response”:”{\\”request\\”:\\”\\/1\\/statuses\\/retweet.json\\”,\\”error\\”:\\”Not found\\”
when I’m trying to retweet using:
$pub_response = $twitterObj->post_statusesRetweet( array (’id’ => $rt));
where $rt is a valid tweet ID ?
December 3rd, 2009 at 3:46 pm
Not sure what those weird double escapes were.. I just upgraded to your most current version using Git as you suggested, but I still get : {”request”:”/1/statuses/retweet.json”,”error”:”Not found”}
on trying to retweet using the code above… $rt is absolutely a valid tweet id…
any thoughts?
December 3rd, 2009 at 4:30 pm
Any idea?
December 3rd, 2009 at 4:48 pm
Using
$pub_response = $twitterObj->post('/statuses/retweet.json', array('id' => $rt));I still get the same error all the time…
December 3rd, 2009 at 7:20 pm
The retweet endpoint is /statuses/retweet/{$id}.json instead of /statuses/retweet.json?id={$id}.
December 3rd, 2009 at 10:56 pm
Thanks Jaisen - I totally did not know that… Gotta love @twitterapi’s consistent API design…. :|
December 6th, 2009 at 9:27 pm
when we try to get the followers for some twitter user,
the next_cursor we got is in scientific format, and is not usable for next request.
here is the code:
$twitter_obj = new EpiTwitter(); $search = $twitter_obj->get_basic('/statuses/followers.json' , array('screen_name' => $this->target_screen_name, 'cursor' => intval ($this->cursor))); $followers = array_reverse($search->users); $this->cursor = (string) $search->next_cursor;when dump the $search object , we got
[next_cursor] => 1.32063884154E+18
and in textResponse, it is ok:
“next_cursor”:1320638841537822006, “previous_cursor”:0
seems the lib is converting this value into scientific format.
Can you help to debug and fix this?
thx
Harry
December 6th, 2009 at 9:34 pm
This is a problem with PHP’s max integer value being exceeded. My suggestion is to convert the integers returned in the response to be strings prior to json_decode’ing. Replace line 214 in
http://github.com/jmathai/twitter-async/blob/master/EpiTwitter.php#L214 with the following.
$this->responseText = preg_replace('/"(next|previous)_cursor":(-?[0-9]+)/', "\"$1_cursor\":\"$2\"", $this->__resp->data);I’ve been running with this in production for a couple months with no issues. Haven’t yet considered adding it to the library as a patch.
December 6th, 2009 at 9:38 pm
Fyi, I’m going to close comments on this post. It’s already got 256. If you have questions regarding the library please redirect them to Github by opening an issue.
http://github.com/jmathai/twitter-async/issues