首页 > 解决方案 > 如何刷新 Smartcar 访问令牌?

问题描述

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

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

// ./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,
      });
    });
});

这不再起作用:{“error”:“authentication_error”,“message”:“提供的令牌无效或过期。” }

我认为这是因为我需要用刷新令牌替换 accessToken。我怎样才能做到这一点?

标签: node.jsapioauthoauth-2.0automotive

解决方案


因此,您对需要使用刷新令牌的预感是正确的。

如果您查看 API Reference 的“请求访问令牌”部分,它会注意到访问令牌仅在 2 小时内有效,之后您将需要使用刷新令牌来获取要使用的新访问令牌。

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

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

// ./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 存储访问对象。


推荐阅读