QQ oauth2 登陆获取基本信息

网站QQ账号接入并获取基本信息需要用到的四个接口
// Get Authorization Code
下面代码在windows和ubuntu上面运行正常,解决OpenSSL加密的问题。
require “rbconfig”
require ‘net/http’
require ‘net/https’
require ‘uri’
require ‘open-uri’
require ‘rest-client’
require ‘multi_json’

def new_qq
  redirect_to “https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=#{APPID}&redirect_uri=#{REDURL}”
end

def callback_qq
  begin
    if get_system_version == “mingw32″  #针对windows
      http = Net::HTTP.new(‘graph.qq.com’, 443)
      path = ‘/oauth2.0/token’
      http.use_ssl = true
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE #这很重要 
      data = “grant_type=authorization_code&client_id=#{APPID}&client_secret=#{APPKEY}&code=#{params[:code]}&state=1&redirect_uri=#{REDURL}”
      headers = {
        ‘Referer’ => ‘https://graph.qq.com/oauth2.0/token’,
        ‘Content-Type’ => ‘application/x-www-form-urlencoded’
      }
      resp, data = http.post(path, data, headers)
    else #针对linux(测试在ubuntu上)
      conn = Faraday.new(:url => ‘https://graph.qq.com’) do |faraday|
        faraday.request  :url_encoded             # form-encode POST params
        faraday.response :logger                  # log requests to STDOUT
        faraday.adapter  Faraday.default_adapter  # make requests with Net::HTTP
      end
      response = conn.get do |req|   # https://graph.qq.com
        req.url ‘/oauth2.0/token’, :client_id => “#{APPID}”
        req.params[‘state’] = “qq_login”
        req.params[‘client_secret’] = “#{APPKEY}”
        req.params[‘grant_type’] = “authorization_code”
        req.params[‘code’] = “#{params[:code]}”
        req.params[‘redirect_uri’] = “#{REDURL}”
      end
      data = response.body
    end
    access_tocken = data.split(“&”)[0].split(“=”)[1]
    http = Net::HTTP.new(“graph.qq.com”, 443)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE #这很重要 
    http.start do |http|
      req = Net::HTTP::Get.new(“/oauth2.0/me?access_token=#{access_tocken}”)
      response = http.request(req)
      resp = response.body
    end
    resp =~ /.*?\([\s]+(.*)\).*/
    @openid = ActiveSupport::JSON.decode($1)
    auth= “access_token=#{access_tocken}&oauth_consumer_key=#{APPID}&openid=#{@openid[“openid”]}”
    msg = get_user_info(auth)
    @info = ActiveSupport::JSON.decode(msg.to_json)
    unless @info[“nickname”].nil?
      # 获取成功后的处理
    else
      redirect_to :back, notice: “用户信息获取失败, #{msg}”
    end
  rescue Exception => e
    redirect_to :back, notice: “QQ授权失败!#{e.message}”
  end
end
def get_user_info(auth)
  MultiJson.decode(open(GETUSERINFOURL + auth,:ssl_verify_mode => OpenSSL::SSL::VERIFY_NONE).read.force_encoding(‘utf-8′))
end