Ruby使用OAuth登录新浪微博和豆瓣

阅读更多
首先需要安装oauth这个gem包
gem install oauth


新浪微博OAuth
申请新浪微博API key: http://open.t.sina.com.cn/wiki/index.php/%E6%96%B0%E6%89%8B%E6%8C%87%E5%8D%97
require 'rubygems'
require 'oauth'
# your api key here
sina_api_key = ""
# your api key secret here
sina_api_key_secret = ""

@consumer = OAuth::Consumer.new(
  sina_api_key,
  sina_api_key_secret,
  {
    :site=>"http://api.t.sina.com.cn",
  }
)
# 1. get request_token
@request_token = @consumer.get_request_token

# 2. authorize & get oauth_verifier
puts "Copy this url to your browser to authorize,  and get the oauth verifier code:"
puts @request_token.authorize_url
@oauth_verifier = "" # put the verfifier code here

# 3. get access_token
@access_token = @request_token.get_access_token(:oauth_verifier => @oauth_verifier)

# 4. API Example: get current user info
puts @access_token.get "/account/verify_credentials.xml"

# API result:

  
    1835404525
    wendait
    wendait
    11
    1000
    北京
    wenda.it - 做国内最好的IT专业知识问答网站
    http://1
    http://tp2.sinaimg.cn/1835404525/50/1293540256/1
    plzdonttalkwithme
    m
    17
    103
    307
    0
    Thu Oct 21 00:00:00 +0800 2010
    false
    false
    false
    true
    
      Sun Jan 09 10:38:41 +0800 2011
      5087310493
      分享图片
      
        Android客户端
      
      false
      false
      
      
      
      
      http://ww1.sinaimg.cn/thumbnail/6d660cedjw6dd604n2phwj.jpg
      http://ww1.sinaimg.cn/bmiddle/6d660cedjw6dd604n2phwj.jpg
      http://ww1.sinaimg.cn/large/6d660cedjw6dd604n2phwj.jpg
      
    
  


豆瓣OAuth
申请豆瓣API key: http://www.douban.com/service/apikey/apply
require 'rubygems'
require 'oauth'
# your api key here
douban_api_key = ""
# your api key secret here
douban_api_key_secret = ""

@consumer = OAuth::Consumer.new(
  douban_api_key,
  douban_api_key_secret,
  {
    :site=>"http://www.douban.com",
    :request_token_path=>"/service/auth/request_token",
    :access_token_path=>"/service/auth/access_token",
    :authorize_path=>"/service/auth/authorize",
    :signature_method=>"HMAC-SHA1",
    :scheme=>:header,
    :realm=>"http://yoursite.com"
  }
)

# 1. get request_token
@request_token = @consumer.get_request_token

# 2. authorize
puts "Copy this url to your browser to authorize:"
puts @request_token.authorize_url

# 3. get access_token
@access_token = @request_token.get_access_token
@access_token = OAuth::AccessToken.new(
  OAuth::Consumer.new(
    douban_api_key,  
    douban_api_key_secret, 
    {
      :site=>"http://api.douban.com",
      :scheme=>:header,
      :signature_method=>"HMAC-SHA1",
      :realm=>"http://yoursite.com"
    }
  ),
  @access_token.token,
  @access_token.secret
)

# 4. API example: get current user info
puts @access_token.get("/people/%40me")

# API result:


	http://api.douban.com/people/1398276
	hideto
	
	
	
	
	http://wenda.it
	0
	1
	
	Hideto
	http://api.douban.com/people/1398276

你可能感兴趣的:(新浪微博,Ruby,腾讯,Access,rubygems)