短期代码作为查询参数包含在您的redirect_uri 中。在您应用的“设置”页面中,您需要将带有“OAuth 重定向 URL”标签的选项设置为您的服务器的链接。
假设您的网站是 https://www.example.com,您的重定向 URI 可能类似于 https://www.example.com/surveymonkey/oauth,您可以将其保存在应用的设置中。
因此,对于第 1 步,您会将用户发送到:
https://api.surveymonkey.net/oauth/authorize?response_type=code&redirect_uri=https://www.example.com/surveymonkey/oauth&client_id=<your_client_id>&api_key=<your_api_key>
当用户在 OAuth 表单中单击“授权”时,我们会将短期代码作为查询参数发送到您的 redirect_uri。所以用户将被发送到:
https://www.example.com/surveymonkey/oauth?code=<short_lived_code>
通常您不会渲染页面(尽管您可以然后通过 window.location.search 或其他方式检查 JavaScript 中的代码),而是在主机的服务器端从 GET 参数中获取代码(取决于您的语言/框架)并在https://api.surveymonkey.net/oauth/token?api_key=<your_api_key>将该短期令牌交换为长期访问令牌。
一个python示例:
import requests
def surveymonkey_oauth(request):
code = request.GET['code']
post_body = {
"client_secret": "your_client_secret",
"redirect_uri": "https://www.example.com/surveymonkey/oauth",
"grant_type": "authorization_code",
"code": code
}
headers = {
"Content-Type": "application/x-www-form-urlencoded"
}
response = requests.post("https://api.surveymonkey.net/oauth/token?api_key=<your_api_key>", headers=headers, data=post_body)
access_token = response['access_token']
然后,您可以存储该访问令牌,并在您想为该用户向 SurveyMonkey API 发出请求时为该用户获取它。
我有一段时间没有使用 node.js,但让我为你尝试一个 node 示例,因为我看到你有 express 作为标签:
var http = require('http');
var querystring = require("querystring");
app.get('/surveymonkey/oauth', function (req, res) {
var code = req.query.code;
var post_body = querystring.stringify({
"client_secret": "your_client_secret",
"redirect_uri": "https://www.example.com/surveymonkey/oauth",
"grant_type": "authorization_code",
"code": code
});
var options = {
host: 'api.surveymonkey.net',
port: 443,
path: '/oauth/token?api_key=<your_api_key>',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(post_body)
}
}
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (body) {
// Get access_token from body and do what you like with it
});
});
req.write(post_body);
req.end();
});
请注意,如果您只想访问自己的帐户,如果您在凭据部分的应用程序设置页面底部附近向下滚动,则已经为您自己的帐户提供了访问令牌。
另请注意,处于“草稿”模式的应用只能以任何一种方式访问您自己的帐户。