[英]How to get Google Fitness API data using OAuth2 with PassportJS
我在使用 Node 和 Express 從 Google Fitness API 獲取數據以用於我的應用程序時遇到問題。 這是app.js
的一部分:
app.get('/auth/google',
passport.authenticate('google',
{ scope: ['profile', 'https://www.googleapis.com/auth/fitness.activity.write'] }
));
app.get('<callback url>',
passport.authenticate('google'), (req, res) => {
res.json(req.user);
});
如您所見,我要求 2 個不同的范圍。 這是我使用passport-google-oauth20
的策略 這是我對passport.js
的這個特定數據點的策略:
passport.use(
new GoogleStrategy({
clientID: keys.google.clientID,
clientSecret: keys.google.clientSecret,
callbackURL:'<callback url>'
}, (accessToken, refreshToken, profile, done) => {
console.log(profile);
}
)
)
然而問題在於,在控制台中,我只獲得了第一個 scope "profile"
及其所有屬性,但沒有與健身相關的信息。 知道有什么問題嗎? 我應該使用不同的策略實施嗎? 目前,此代碼掛在谷歌登錄和控制台記錄個人資料信息,這是正常的。
有任何想法嗎? 謝謝。
感謝@griFlo
的評論,我想通了。 從身份驗證過程中獲得訪問令牌后,我必須使用此令牌以及生成的所有其他令牌來調用我想要的 api,這是我使用來自策略內request-promise
模塊的請求 promise 完成的。
首先使用npm i request-promise
安裝模塊,並將模塊安裝到應用程序的頂部。 代碼應如下所示:
//other defines
...
const request = require('request-promise');
passport.use(
new GoogleStrategy({
// options for google strategy
clientID: keys.google.clientID,
clientSecret: keys.google.clientSecret,
callbackURL:'<callback url>'
}, (accessToken, refreshToken, profile, done) => {
User.findOne({googleId: profile.id}).then((currentUser) => {
if (currentUser){
// check user
done(null, currentUser);
} else {
//call fitness api
url = keys.google.fitnessUrl;
request.get(url).auth(null, null, true, accessToken)
.then(res=> {
new User({
googleId: profile.id,
....
activity: res
}
).save().then((newUser) => {
done(null, newUser);
});
});
}
});
}));
重要的部分在 mongoose promise 部分中,您在調用 api 之前檢查用戶,以便您可以將獲取的數據添加到預定義的模式中並保存它。
正確的 scope 是: fitness.activity.read
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.