我打算弄微博的 OmniAuth,但是不知道 https://github.com/ballantyne/weibo 这个怎么用,没找到文档,搜了一下都是一些比较老的文章。
而且看到微博开发文档上写还有 Oauth2,不知道有什么 Rails 的解决方案。谢谢
新注册的 app 应该都是 oauth2 了 没有合适的 gem 的话可以先用 RestClient 也挺方便的
ps 没通过审核的 app access_token 24 小时过期 通过后的为一周
登录验证用 omniauth-weibo-auth2 sdk 用 weibo2 就行,每次获取 access_token 的时候会有个 expires_at 的 timestamp 告诉你 atoken 什么时候过期,希望帮到你
#5 楼 @hlcfan 用 'omniauth-oauth2'
require 'omniauth-oauth2'
module OmniAuth
module Strategies
class Weibo < OmniAuth::Strategies::OAuth2
# Give your strategy a name.
option :name, "weibo"
# This is where you pass the options you would pass when
# initializing your consumer from the OAuth gem.
option :client_options, {
:site => 'https://api.weibo.com',
:authorize_url => '/oauth2/authorize',
:token_url => '/oauth2/access_token'
}
option :token_params, {
# SET :parse because weibo oauth2 access_token response with "content-type"=>"text/plain;charset=UTF-8",
# and when you use ruby 1.8.7, the response body was not a valid HASH (see: https://github.com/intridea/oauth2/issues/75)
# :body=>"{\"access_token\":\"2.001FOK5CacB2wCc20a59773d0uSGnj\",\"expires_in\":86400,\"uid\":\"2189335154\"}"}
:parse => :json
}
# These are called after authentication has succeeded. If
# possible, you should try to set the UID without making
# additional calls (if the user id is returned with the token
# or as a URI parameter). This may not be possible with all
# providers.
uid { raw_info['id'] }
info do
{
:nickname => raw_info['screen_name'],
:name => raw_info['name'],
:location => raw_info['location'],
:avatar_url => raw_info['avatar_large']
}
end
extra do
{
'raw_info' => raw_info
}
end
def raw_info
# SET :mode because by default it will use :header option, and send out header like
# opts[:headers]={"Authorization"=>"Bearer 2.001FOK5CacB2wCc20a59773d0uSGnj"}
# this doesn't align with weibo API (see: http://open.weibo.com/wiki/2/account/get_uid)
access_token.options[:mode] = :query
access_token.options[:param_name] = 'access_token'
@uid ||= access_token.get('/2/account/get_uid.json').parsed["uid"]
@raw_info ||= access_token.get("/2/users/show.json", :params => {:uid => @uid}).parsed
end
end
end
end
initializers 中 omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
require 'weibo'
provider :weibo, Setting.weibo_key, Setting.weibo_secret
end