I followed the Simple OmniAuth tutorial (http://asciicasts.com/episodes/241-simple-omniauth), and I can log in with my twitter account on the service. Now I want to access the twitter API and tweet from the app. My code is as follows:
class TwitterController < ApplicationController
def prepare_access_token(oauth_token, oauth_token_secret)
consumer = OAuth::Consumer.new("KEY", "SECRET",
{
:site => "http://api.twitter.com"
})
# now create the access token object from passed values
token_hash =
{
:oauth_token => oauth_token,
:oauth_token_secret => oauth_token_secret
}
access_token = OAuth::AccessToken.from_hash(consumer, token_hash)
return access_token
end
def tweet
# Exchange our oauth_token and oauth_token secret for the AccessToken instance.
@access_token = prepare_access_token(current_user.token, current_user.secret)
@response = @access_token.request(:post, "http://api.twitter.com/1/statuses/update.json", :status => "Tweet pela API")
render :html => @response.body
end
end
The render line does not do anything. Furthermore, if I add
<p><%= @response %></p>
to my view, I get
#<Net::HTTPUnauthorized:0x2ac5149e94f0>
Still, I am able to get the username from the twitter account.
My user model is as follows:
class User < ActiveRecord::Base
def self.create_with_omniauth(auth)
create! do |user|
user.provider = auth["provider"]
user.uid = auth["uid"]
user.name = auth["user_info"]["name"]
user.token = auth['credentials']['token'],
user.secret = auth['credentials']['secret']
end
end
end
What am I doing wrong?
I've figured out the problem and now I feel rather silly. There was a comma on the User Model which shouldn't be there. The model should be
class User < ActiveRecord::Base
def self.create_with_omniauth(auth)
create! do |user|
user.provider = auth["provider"]
user.uid = auth["uid"]
user.name = auth["user_info"]["name"]
user.token = auth['credentials']['token']
user.secret = auth['credentials']['secret']
end
end
end
And now everything works fine.
Rather than coding this up manually., you might want to try using the twitter gem (gem install twitter.) Works for us. Syntax is:
httpauth = Twitter::HTTPAuth.new(twitterName, twitterPass)
client = Twitter::Base.new(httpauth)
client.update(yourTweetText)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With