node.js - 如何刷新 Smartcar 访问 token ?

标签 node.js api oauth oauth-2.0 automotive

我在我的 Tesla ( https://teslaapi.dev/ ) 上使用 Smartcar API 并成功发出了请求,但我认为访问 token 已过期,我不知道如何刷新它。

我遵循了这个指南:https://smartcar.com/docs/integration-guides/express/request/ 它讨论了访问 token ,但没有告诉我如何获取刷新 token 。

// ./index.js

app.get('/vehicle', function(req, res) {
    // TODO: Request Step 2: Get vehicle information
    return smartcar.getVehicleIds(access.accessToken)
      .then(function(data) {
        // the list of vehicle ids
        return data.vehicles;
      })
      .then(function(vehicleIds) {
        // instantiate the first vehicle in the vehicle id list
        const vehicle = new smartcar.Vehicle(vehicleIds[0], access.accessToken);

        return vehicle.info();
      })
    .then(function(info) {
      res.render('vehicle', {
        info: info,
      });
    });
});

这不再有效: { “错误”:“authentication_error”, “消息”:“提供的 token 无效或过期。”

我认为这是因为我需要用刷新 token 替换 accessToken。我该怎么做?

最佳答案

所以您关于需要使用刷新 token 的预感是正确的。

如果您查看 "Request access token" API Reference 部分,它指出访问 token 仅在 2 小时内有效,之后您将需要使用刷新 token 来获取新的访问 token 以供使用。

如果您使用的是 Node SDK,则可以使用 exchangeRefreshToken将刷新 token 交换为一组新 token 的方法。

这是一个集成了所有这些的示例:

// ./index.js

app.get('/vehicle', function(req, res) {
    if (smartcar.isExpired(acccess.expiration)) {
      const 
   }

    // TODO: Request Step 2: Get vehicle information
    return smartcar.getVehicleIds(access.accessToken)
      .then(function(data) {
        // the list of vehicle ids
        return data.vehicles;
      })
      .then(function(vehicleIds) {
        // instantiate the first vehicle in the vehicle id list
        const vehicle = new smartcar.Vehicle(vehicleIds[0], access.accessToken);

        return vehicle.info();
      })
    .then(function(info) {
      res.render('vehicle', {
        info: info,
      });
    });
});

要长期正确实现此功能,您需要使用某种数据库来存储基于车辆 ID 的访问对象。

关于node.js - 如何刷新 Smartcar 访问 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57155430/

相关文章:

node.js - 在 koa 中使用 express 中间件

api - 维基百科 API : how to search for a term in a specific category

javascript - 雅虎财经 API 历史报价

iphone - 在 iPhone 应用程序中验证用户身份的最简单方法?

eclipse - 在 Eclipse 中构建 NodeJs 应用程序

javascript - 简单的 Node.js 应用程序控制流程

java - 我的其余服务无法识别授权 :Bearer

iphone - 使用 Tumblr 时出现 iOS oAuth 错误

mysql - 我无法让 populate() 处理我的 sails.js 项目

r - 有没有办法混淆 R 包中的 API key ?