首页 > 解决方案 > Google Fit Api 暂时不稳定?

问题描述

我开发了一个 MEAN(Mongodb、Express、Angular 和 Node.js)堆栈 Web 应用程序来访问来自 Google Fit 帐户的步骤。但有时它返回步骤(inVal),有时它不返回,这在 Point 数组中没有值。有时它无法获取用户步骤并且 Oauth didin.t 再次重定向到主页。我可以知道为什么吗?这是创建的 api 的片段。

googleRoute.route('/getURLTing/:id').get((req, res, err) => {
    userid = req.params.id;
    
    const oauth2Client = new google.auth.OAuth2(
        // client id
        "42049410831-xxxxxxxx.apps.googleusercontent.com",
        // client secret
        "yjQutKGLr3xxxxxxxxxxV1VL",
        // link to redirect to
        "http://localhost:1234/api/steps"
    );

    const scopes = [ "https://www.googleapis.com/auth/fitness.activity.read profile email openid"];

    const url = oauth2Client.generateAuthUrl({
        access_type: "offline",
        scope: scopes,
        state: JSON.stringify({
            callbackUrl: req.body.callbackUrl,
            userID: req.body.userid
        })
    });

    request(url, (err, res, body => {
        // console.log("error: ", err);
        console.log("statusCode: ", res && res.statusCode);
        // res.send({ url});
        // console.log('URL= ',url);
        console.log("redirect to google auth");
        // var URL = url.toString();
        // res.status(301).redirect(URL);
        return res.json(url);
    }));
});


googleRoute.route('/steps').get(async (req, res) => {

    const queryURL = new urlParse(req.url);
    const acode = queryParse.parse(queryURL.query).code;
    const oauth2Client = new google.auth.OAuth2(
        // client id
        "42049410831-xxxxxxxx.apps.googleusercontent.com",
        // client secret
        "yjQutKGLr3xxxxxxxxxxV1VL",
        // link to redirect to
        "http://localhost:1234/api/steps"
        // "http://localhost:4200/home"
    );

    const tokens = await oauth2Client.getToken(acode);

    var m = getMillis();
    var l = getMillisAtMidnight();
    var initDate = getInitialTImeDateMidnight();

    console.log('initDate = ', initDate);
    
    console.log('Time in milliseconds = ', m);

    let stepArray = [];

    try{
        const result = await axios ({
            method: "POST",
            headers: {
                authorization: "Bearer " + tokens.tokens.access_token
            },
            "Content-Type": "application/json",
            url: `https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate`,
            data: { 
                    "aggregateBy" : [{  
                        dataTypeName: "com.google.step_count.delta",
                        dataSourceId: "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps"    
                    }],    
                    "bucketByTime": { "durationMillis": x }, // This is 24 hours    
                    //"startTimeMillis": 1617033600000,   // Mock start time 
                    "startTimeMillis": initDate,   // Real start time   
                    "endTimeMillis": initDate + x  // End Time     
            }
        });

        stepArray = result.data.bucket;

        for(const dataSet of stepArray){
            for(const points of dataSet.dataset){
                for(const steps of points.point){
                    console.log('Number of steps = ',steps.value[0].intVal);
                    var s = steps.value[0].intVal;

                        User.findById(userid, function(err, user) {
                            if (user) {
                                var temp = user.steps;
                               
                                let data = {
                                    step: s,
                                    date: m,
                                }

                                temp.push(data)
                                
                                let data_steps = {
                                    steps: temp
                                }
                                
                                User.updateOne({ _id: user._id }, data_steps)
                                    .then(result => {
                                        res.redirect('http://localhost:4200/home');
                                    })
                                    .catch(err => {
                                        res.status(404).json({ error: "ERROR: Failed to save data steps" })
                                    })
                            } else {
                                return res.status(404).json({ error: "ERROR: Failed to find user" });
                            }
                        });
                        // })
                        
                        
                }
            }
        }
    } catch (e) {
        console.log(e);
    }

});

我也在 Google Developer 上运行,但仍然没有返回任何值。相信我,一次就好了。然后它没有成功。

在此处输入图像描述

标签: apigoogle-fitfitness

解决方案


推荐阅读