Bartłomiej Lechowski
Frontend Developer
Magdalena Jackiewicz
Reviewed by a tech expert

Using Smartcar with React Native for connected vehicles

#Sales
#Sales
#Sales
#Sales
Read this articles in:
EN
PL

When building apps for use with connected vehicles, Smartcar is an attractive choice. Why? It’s a standardized API that works across multiple car brands and models, simplifying the development process and reducing the need to create separate integrations for different vehicle manufacturers.

However, even though the Smartcar API offers support for many platforms (including React, Node or Native iOS and Android), it doesn’t have an official support for React Native (there’s no dedicated SDK). That means a workaround is required to resolve this problem and allow you to benefit from the advantages of Smartcar API.

In this article, we explain step-by-step how to overcome this issue, so that you can build your app in React Native and enjoy the advantages of Smartcar API.

What is Smartcar API?

The Smartcar API is a platform that allows developers to interact with vehicles directly via their apps. It’s a popular tool because of a number of advantages it brings:

  • Through this API, developers can build applications that interact with 43 vehicle brands, without worrying about the specific protocols or systems used by different manufacturers.
  • It does offer SDKs for various programming languages and platforms, making it easier for developers to integrate vehicle connectivity into their apps.
  • The platform is designed with security in mind, adhering to industry standards and regulations, which is crucial when dealing with sensitive vehicle data.
  • Smartcar implements a user-friendly authorization flow, ensuring that vehicle owners maintain control over their data and can easily grant or revoke access to third-party applications.
  • The platform provides real-time access to various vehicle data points, such as location, fuel level, odometer reading, and more, enabling developers to create responsive and up-to-date applications.

The React Native framework allows you to build mobile apps for iOS and Android Platforms. By connecting Smartcar API, you can create apps that can connect with vehicles and manage their data.

Key data provided by Smartcar

  • Vehicle Information: basic details like make, model, and year. Retrieve the air pressure for each tire, confirm a car’s VIN.
  • Location: tracking of a vehicle’s location by geographic coordinates.
  • Battery and fuel data: battery capacity, remaining battery charge or fuel level updates.
  • Vehicle controls: lock/unlock doors, start/stop the engine, adjust the charge limit, and remotely manage charging.
  • Charging status: users can be notified when their vehicle has finished charging or monitor the charging process remotely. This feature is also helpful for managing charging station usage.

Getting started - creating an account with Smartcar API

To begin, you have to sign up for the service via Smartcar developer account.

Once your account is created, start a new application from the Smartcar dashboard. That application will serve as the connection between your mobile app and the API.

Having set up your new Smartcar app, you’ll see a client ID and client secret. You’ll have to use these credentials to authenticate application requests to the Smartcar API.

Connecting your React Native app with Smartcar API - a step-by-step process

Since Smartcar does not provide an official SDK for React Native, we will have to implement Smartcar Connect using the react-native-inappbrowser-reborn library, which provides a way to handle OAuth flows in a secure in-app browser.

Here's what’s involved: 

Step 1: Install the required libraries

You'll need react-native-inappbrowser-reborn to handle the in-app browser functionality. First, install the package yarn add react-native-inappbrowser-reborn and then query-string to extract query parameters from a URL yarn add query-string

Step 2: Configure Smartcar OAuth flow


const CLIENT_ID = 'YOUR_SMARTCAR_CLIENT_ID';
const REDIRECT_URI = 'myapp://callback'; // Must be the same as registered in Smartcar
const SCOPE = 'read_vehicle_info'; // Example scope, adjust as needed
const STATE = 'YOUR_STATE_PARAMETER'; // Optional, used for security
const AUTH_URL = 'https://connect.smartcar.com/oauth/authorize';

Step 3: Set up Redirect URI

You need to configure your Smartcar app to use a redirect URI that can handle the OAuth callback. Typically, you might use a custom URL scheme or a universal link. For this example, we'll assume a custom URL scheme.

  1. Custom URL Scheme: Set up a custom URL scheme (e.g., myapp://callback).
  2. Add Redirect URI to Smartcar: Go to your Smartcar Developer Dashboard and add your custom redirect URI (e.g., myapp://callback) to your application's redirect URIs.

Step 4: Prepare OAuth URL

You need to generate the authorization URL to start the OAuth flow:


const AUTH_URL_WITH_PARAMS = `${AUTH_URL}?response_type=code&client_id=${CLIENT_ID}&redirect_uri=${encodeURIComponent(REDIRECT_URI)}&scope=${encodeURIComponent(SCOPE)}&state=${STATE}`;

Step 5: Open the OAuth URL

In your React Native app, use react-native-in-app-browser to open the Smartcar OAuth URL:


const openSmartcarAuthPage = async () => {
   try {
     if (await InAppBrowser.isAvailable()) {
       // discards the current authentication session if any
       await InAppBrowser.closeAuth();
       const result = await InAppBrowser.openAuth(
         AUTH_URL_WITH_PARAMS,
         REDIRECT_URI,
       );
       if (result.type === 'success' && result.url) {
         handleAuthSessionUrl(result.url);
       }
     }
   } catch (error) {
     console.error(error);
   }
 };

Step 6: Handle the OAuth Callback URL

The URL will be opened when Smartcar redirects back to your app:


const handleAuthSessionUrl = (url: string) => {
   if (url.includes(REDIRECT_URI)) {
     // Parse the authorization code from the URL
     const authCode = queryString.parseUrl(url).query.code;
     if (typeof authCode === 'string') {
       // Now exchange the code for an access token
       // e.g., make an API call to your server to complete the OAuth flow
       exchangeCodeForToken(authCode);
     } else {
       // Handle error (no code found)
       console.error('Authorization code not found in URL');
     }
   }
 };

Step 7: Exchange code for token

After obtaining the authorization code, you need to exchange it for an access token. This should be done on your backend server to keep your client_secret secure. Your backend will handle the token exchange and can send the access token back to your app.

Here’s a basic example of how you might implement the token exchange on a Node.js server:


const express = require('express');
const axios = require('axios');
const app = express();


app.use(express.json());


app.post('/exchange-code', async (req, res) => {
 const { code } = req.body;
 try {
   const response = await axios.post(
     'https://auth.smartcar.com/oauth/token',
     null,
     {
       params: {
         grant_type: 'authorization_code',
         code,
         redirect_uri: 'myapp://callback',
         client_id: 'your_client_id',
         client_secret: 'your_client_secret',
       },
       headers: {
         'Content-Type': 'application/x-www-form-urlencoded',
       },
     },
   );
   res.json(response.data);
 } catch (error) {
   res.status(500).send('Error exchanging code');
 }
});


app.listen(3000, () => console.log('Server running on port 3000'));

Step 8: Handle the Access Token in your app 

Once you receive the access token from your backend, you can use it to make authenticated requests to Smartcar's API to access vehicle data.

Ensure you test the OAuth flow properly, including handling edge cases such as token expiration and refresh.

By following these steps, you can integrate Smartcar Connect into your React Native app using an in-app browser for OAuth authentication. This setup provides a secure and user-friendly way to authenticate users and access vehicle data.

Best practice

There may be a case when a user updates their details in their car account. When this happens, the user will need to go through Smartcar Connect again to update their authorization via Smartcar. More information can be found here.

Need more help with connecting your React Native app to connected vehicles?

In case you have any questions about this process or run into issues with your React Native app development, feel free to write to us at hi@rst.software contact form and we’ll be happy to help!

People also ask

No items found.
Want more posts from the author?
Read more

Want to read more?

Mobile

How to connect your React Native app to CarPlay?

Integrate CarPlay in your React Native app with our comprehensive guide. Learn step-by-step how to connect and enhance user experience in vehicles.
Mobile

React Native vs NativeScript: which technology to pick for mobile development in 2021

Two JavaScript-based technologies for cross-platform development, but which to choose? Let's compare React Native and NativeScript.
Mobile

25+ in-depth examples of React Native apps in 2021 [Updated: May 25th, 2021]

I’ve compiled a long list of well-known companies that decided to use React Native in their apps and stuck with it. Read on.
No results found.
There are no results with this criteria. Try changing your search.
en