3

I use the Smartcar API on my Tesla (https://teslaapi.dev/) and successfully made a request before but I think the access token expired and I don't know how to refresh it.

I followed this guide: https://smartcar.com/docs/integration-guides/express/request/ It talks about the access token but it doesn't tell me how to get the refresh 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,
      });
    });
});

This doesn't work anymore: { "error": "authentication_error", "message": "Invalid or expired token provided." }

I think it's because I need to replace the accessToken with a refresh token. How can I do this?

1 Answers1

1

So your hunch about needing to use the refresh token is correct.

If you look at the "Request access token" section of API Reference, it notes that the access tokens are only valid for 2 hours, after that point you'll need to use the refresh token to get a new access token to use.

If you're using the Node SDK, you can use the exchangeRefreshToken method to exchange your refresh token for a new set of tokens.

Here's an example with all of that integrated:

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

For a proper long term implementation of this you'll need to involve some sort of database that stores the access object based on vehicle id.