Ruby 请问如何用 OmniAuth 调用新浪微博和淘宝的 API

blacksource · March 25, 2012 · Last by blacksource replied at March 25, 2012 · 5440 hits

使用 OmniAuth 通过新浪微博和淘宝登录都已经 OK 了,但是在调用 API 的时候总感觉很乱 1.http://rubydoc.info/gems/oa-oauth/OmniAuth/Strategies/Tsina,这个是否可用,如何使用?

  1. consumer = OAuth::Consumer.new(app_key,app_secret,{:site =>'http://api.t.sina.com.cn'}) access_token = OAuth::AccessToken.new(consumer, access_token, access_token_secret) @rsp = access_token.get("/statuses/friends_timeline.json") render :text => @rsp.body 这样可以成功调用,但感觉用的是 OAuth1,OAuth2 如何使用

oauth2 可以直接发请求捎上 access_token weibo 有这么一个 gem,不知能否帮上你的忙https://github.com/ballantyne/weibo

thank you oauth2 调用新浪 api 有例子不?

#2 楼 @blacksource 微博登录 OK 的话说明你可以拿到 access_token(注意!这个 access_token 只是一个字符串),你把这个 access_token 存到数据库里,假设存储为 users 表里的 access_token 字段,当你调用 friends_timeline 这个 api 时可以这样用:

RestClient.get('https://api.weibo.com/2/statuses/friends_timeline.json', {:access_token => current_user.access_token})`

上面的代码应该能够工作,我做过一个新浪微博分享的功能:

def weibo_share(content, pic_url=nil) if pic_url url = 'https://api.weibo.com/2/statuses/upload_url_text.json' else url = 'https://api.weibo.com/2/statuses/update.json' end form = { :access_token => current_account.access_token, :status => content } form.merge!(:url => pic_url) if pic_url begin_rescue do res = RestClient.post(url, form) res = JSON.parse(res.body) 4.times { if res['error_code'] res = RestClient.post(url, form) res = JSON.parse(res.body) else break end } end end

#3 楼 @dxdxdx 通过 REST 来访问,不错,是个好方法,谢谢

You need to Sign in before reply, if you don't have an account, please Sign up first.