Ruby on Rails微信开发4——通过网页授权获取用户的基本信息

来源:互联网 发布:java获取对象内存地址 编辑:程序博客网 时间:2024/06/08 21:20

接着Ruby on Rails微信开发3——自定义菜单的创建,假如“代码是小三”按钮对应了一个我的技术博客的网页链接,该链接只能允许特定的用户打开,此时就需要对用户的身份进行验证。

参照开发者文档网页授权获取用户基本信息对用户身份进行验证

1、网页授权回调域名的配置



2、修改按钮链接,对按钮的链接进行修改

  def create_menu    post_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=#{get_access_token}"    wechat_button_yml = load_yml_file "wechat_button.yml"    post_hash = wechat_button_yml['menu’]    #修改按钮链接    post_hash["button"][0]["sub_button"][0]["url"]=generate_oauth_path post_hash["button"][0]["sub_button"][0]["url"]    Typhoeus::Request.post(post_url, body: generate_post_hash(post_hash))  end  #为按钮生成oauth链接  def generate_oauth_path origin_path    "https://open.weixin.qq.com/connect/oauth2/authorize?appid=#{get_app_id}&redirect_uri=#{origin_path}&response_type=code&scope=snsapi_base#wechat_redirect"  end

因为我在这里只需要获取用户的open_id,scope为snsapi_base,故只需要两步即可:1)、获取code;2)、通过code获取open_id
3、获取code,并且通过code获取open_id


因为按钮对应的链接符合第一步中设置的合法域名,故用户点击按钮后在对应的action中可以获取code参数

  def test    session[:open_id]=get_open_id(params[:code])    respond_to do |format|      format.html { render :layout => "wechat" }    end end
#通过code获取open_id  def get_open_id code    url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=#{get_app_id}&secret=#{get_app_secret}&code=#{code}&grant_type=authorization_code"    JSON.parse(URI.parse(url).read)["openid"]  end
成功获取到open id之后,就可以通过比对当前用户的open id与权限表中存储的open id进行比对,判断用户是否有权限访问啦微笑

0 0