2017-06-01 78 views
2

解析URL我是比較新的Rails的網絡開發和編碼一般。我目前正在開發一個Web應用程序,以便從我的Fitbit帳戶中檢索數據。這是通過Fibit API和OAuth2.0完成的。冰壺和Fitbit API

從本質上講,這是我的問題。如Fitbit教程網站https://dev.fitbit.com/apps/oauthinteractivetutorial所示,我需要從Fitbit用戶獲得授權。我試圖做到這一點使用下列正確的URL

<%= link_to "Sign in with Fitbit", "https://www.fitbit.com/oauth2/authorize?response_type=code&client_id=228BT5&redirect_uri=http%3A%2F%2Fwww.builtbyburton.com%2Foauth2%2Fcallback&scope=activity%20location%20profile%20sleep&expires_in=604800" %> 

當這個被調用時,用戶被重定向到以下網址預期:

http://www.builtbyburton.com/oauth2/callback?code=1093d4dc25f0c61acbbf8128a9247b0efd448c35#_=_ 

目前,我需要捕獲段該URL從code=#_=_這部分則需要進行解析。我試着使用嵌入式捲曲做到這一點,如下所示:

<pre class="embedcurl">curl -X POST -i -H 'Authorization: Basic MjI4QlQ1OmU4OWFkZWJmYTUzNTU1MGMyNGUyNjdhOWRjM2MxNzIy' -H 'Content-Type: application/x-www-form-urlencoded' -d "clientId=228BT5" -d "grant_type=authorization_code" -d "redirect_uri=http%3A%2F%2Fwww.builtbyburton.com%2Foauth2%2Fcallback" -d "code=1093d4dc25f0c61acbbf8128a9247b0efd448c35" https://api.fitbit.com/oauth2/token</pre> 

從那裏,我需要解析這將允許我提出要求的響應。總體而言,我只是不確定如何從授權鏈接獲取使用OAuth2.0訪問令牌的請求。謝謝您的幫助!

回答

1

按照Fitbit docs

Fitbit使用OAuth 2.0用戶授權和API認證。 的的OAuth 2.0框架需要你的應用程序時,Fitbit用戶授權您的應用訪問他們的數據,以獲得訪問令牌 。 訪問令牌用於向Fitbit API發送HTTP請求。

你並不需要一個特定的Fitbit庫使用Fitbit網站API。 相反,我們建議您使用市面上最好的OAuth 2.0或HTTP客戶端 庫平臺。如果您沒有收藏夾 OAuth 2。0或HTTP庫呢,我們列出了一些在這裏

沒有什麼紅寶石上市的,但如果你谷歌軌的oauth2,第一主打是:

https://github.com/intridea/oauth2

的例子有看起來很簡單:

gem install oauth2 

軌道相當於將以下添加到您的Gemfile:

gem oauth2 

而這裏的示例代碼:

client = OAuth2::Client.new('client_id', 'client_secret', :site => 'https://example.org') 

client.auth_code.authorize_url(:redirect_uri => 'http://localhost:8080/oauth2/callback') 
# => "https://example.org/oauth/authorization?response_type=code&client_id=client_id&redirect_uri=http://localhost:8080/oauth2/callback" 

token = client.auth_code.get_token('authorization_code_value', :redirect_uri => 'http://localhost:8080/oauth2/callback', :headers => {'Authorization' => 'Basic some_password'}) 
response = token.get('/api/resource', :params => { 'query_foo' => 'bar' }) 
response.class.name 
# => OAuth2::Response 

原來的答覆:

我試着使用嵌入式捲曲做到這一點,如下所示:

在HTML文件中不能有任意代碼。 Rails使用稱爲ERB(或您選擇的另一個解析引擎)的東西來解析位於您的rails項目中特定目錄中的頁面,如page1.html.erb - 但您必須遵循ERB解析規則。你可以使ERB執行任意的ruby代碼,但是一個bash命令,比如curl甚至不是ruby代碼 - 它的代碼是bash

http://www.builtbyburton.com/oauth2/callback?code=1093d4dc25f0c61acbbf8128a9247b0efd448c35#_=_ 

目前,我需要從代碼捕獲URL的段=到 #_ = _

URL的那部分被稱爲查詢字符串。你可以這樣說:

require 'uri' 

url = 'http://www.builtbyburton.com/oauth2/callback?code=1093d4dc25f0c61acbbf8128a9247b0efd448c35#_=_' 

obj = URI(url) 
query_str = obj.query 
puts query_str 

--output:-- 
code=1093d4dc25f0c61acbbf8128a9247b0efd448c35 

你可以得到公正的授權代碼:

name, value = query_str.split '=' 
puts value 

--output:-- 
1093d4dc25f0c61acbbf8128a9247b0efd448c35