2

23andme 网站有一个 API,它们提供以下说明:

使用以下参数发送 POST /token/ 请求(client_id 和 client_secret 在您的仪表板上):

curl https://api.23andme.com/token/
 -d client_id=xxx \
 -d client_secret=yyy \
 -d grant_type=authorization_code \
 -d code=zzz \
 -d "redirect_uri=https://localhost:5000/receive_code/"
 -d "scope=basic%20rs3094315"

如果成功,您将收到 200 JSON 响应,如下所示:

{"access_token":"89822b93d2",
 "token_type":"bearer",
 "expires_in": 86400,
 "refresh_token":"33c53cd7bb",
 "scope":"rs3094315 basic"}

所以,这就是我尝试过的,但没有奏效。我知道 Ruby,但从未使用过 net/http 或 uri。

def self.get_token(code)
    uri = URI.parse("https://api.23andme.com/token")
    https = Net::HTTP.new(uri.host, uri.port)
    https.use_ssl = true

    request = Net::HTTP::Post.new(uri.path)

    request["client_id"]     = 'my client id goes here'
    request["client_secret"] = 'my client secret goes here'
    request["grant_type"]    = 'authorization_code'
    request["code"]          = code
    request["redirect_uri"]  = 'http://localhost:3000'
    request["scope"]         = 'names basic haplogroups relatives'

    response = https.request(request)
    return response.to_s
end
4

2 回答 2

0

我只是想发布有效的代码。感谢拉法。

def self.get_token(code)
    uri = URI.parse("https://api.23andme.com/token")
    https = Net::HTTP.new(uri.host, uri.port)
    https.use_ssl = true
    https.verify_mode = OpenSSL::SSL::VERIFY_NONE

    request = Net::HTTP::Post.new(uri.path,
                initheader = {'Content-Type' =>'application/json'})

    request.set_form_data({"client_id"     => 'my client id',
                           "client_secret" => 'my client secret',
                           "grant_type"    => 'authorization_code',
                           "code"          => code,
                           "redirect_uri"  => 'http://localhost:3000/receive_code/',
                           "scope"         => 'names basic haplogroups relatives'})

    response = https.request(request)
    data = JSON.load response.read_body

    return data["access_token"]
end
于 2014-03-21T03:50:06.820 回答
0

您使用在 POST 请求正文中设置参数curl的选项是正确的。-d但是,对于Net::HTTP::Post对象,语法request["key"] = value用于设置 Http 对象的标头

用于set_form_data将所有参数设置到POST 请求的正文中。

例如,以这种方式使用它:

request.set_form_data({"client_id" => "my client id goes here", "code" => code})

以下将对以上内容进行澄清:

$ > request["client_id"] = 'my client id goes here'
# => "my client id goes here" 
$ > request.body
# => nil # body is nil!!!
$ > request.each_header { |e| p e }
# "client_id"
# => {"client_id"=>["my client id goes here"]} 

$ > request.set_form_data("client_secret" => 'my client secret goes here')
# => "application/x-www-form-urlencoded" 
$ > request.body
# => "client_secret=my+client+secret+goes+here" # body contains the added param!!!
于 2014-03-19T19:39:42.257 回答