Class: Weibo::Oauth

Inherits:
Object
  • Object
show all
Defined in:
lib/weibo/oauth.rb

Constant Summary collapse

AUTHORIZE_URL =
"https://api.weibo.com/oauth2/authorize"
ACCESS_TOKEN_URL =
"https://api.weibo.com/oauth2/access_token"
API_URL =
"https://api.weibo.com/2/"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(access_token) ⇒ Oauth

Returns a new instance of Oauth.



10
11
12
# File 'lib/weibo/oauth.rb', line 10

def initialize(access_token)
  @access_token = access_token
end

Class Method Details

.authorize_url(options = {}) ⇒ Object



22
23
24
25
# File 'lib/weibo/oauth.rb', line 22

def self.authorize_url(options = {})
  url = AUTHORIZE_URL + "?client_id=#{Config.app_key}&redirect_uri=#{Config.redirect_uri}&response_type=code"
  options.keys.length > 0 ? (url + "&" + options.map {|k,v| "#{k}=#{v}"}.join("&")) : url
end

.get_access_token_by_code(code) ⇒ Object



27
28
29
30
31
# File 'lib/weibo/oauth.rb', line 27

def self.get_access_token_by_code(code)
  response = RestClient.post(ACCESS_TOKEN_URL, :client_id => Config.app_key, :client_secret => Config.app_secret,
                             :grant_type => "authorization_code", :code => code, :redirect_uri => Config.redirect_uri)
  JSON.parse(response)
end

.parse_signed_request(signed_request) ⇒ Object

Parameters:

  • string

    $signed_request 应用框架在加载iframe时会通过向Canvas URL post的参数signed_request



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/weibo/oauth.rb', line 38

def self.parse_signed_request(signed_request)
  encoded_sig, payload = signed_request.split(".")
  sig = Base64.decode64_url(encoded_sig)
  begin
    data = JSON.parse(Base64.decode64_url(payload))
  rescue Exception => e
    return nil
  end
  return nil if data["algorithm"].upcase != "HMAC-SHA256"

  expected_sig = OpenSSL::HMAC.digest("sha256", Config.app_secret, payload)
  (sig != expected_sig) ? nil : data
end

Instance Method Details

#get(path, parameters = {}) ⇒ Object



14
15
16
# File 'lib/weibo/oauth.rb', line 14

def get(path, parameters = {})
  JSON.parse RestClient.get(api_url(path), :params => parameters, :Authorization => "OAuth2 #{@access_token}")
end

#post(path, parameters = {}) ⇒ Object



18
19
20
# File 'lib/weibo/oauth.rb', line 18

def post(path, parameters = {})
  JSON.parse RestClient.post(api_url(path), parameters, :Authorization => "OAuth2 #{@access_token}")
end