Show:

Introduction

This is the main module that allows communication between your web application and the SnapCar platform through the SnapCar Public API. This module is dependent on jQuery. The source code is available on Github.

Before using this module, you must initialize it with a user token by setting the SnapCar.token property. Please refer to the general SnapCar API documentation for more information on how to obtain a user token.

The SnapCar SDK for JavaScript does not manage user authentication. The reason for this is that obtaining a user token is done through a request that requires your API secret value to be provided. The API secret value is sensitive information that should never be revealed to the user. However, setting it in the JavaScript SDK implies that your users can access it by digging into the source code. Which is why such work flow must be implemented on the server side. Once initialized with a token, the module allows you to perform actions such as making bookings or getting ETAs on behalf of the authenticated user.

In general, all methods that are in charge of performing an API request always return a jQuery promise. The promises are resolved with the desired resources which depend on the performed request. If an error occurs during the request, the promises are rejected with an instance of SnapCar.APIError (containing more info about the issue). Look at the examples below for a comprehensive vision of the work flow.



Getting started and examples


Setting a user token

As explained above, you need to provide a token before using the SDK.

SnapCar.token = "3xI121nd93N7rhOFT7yk76I4B80PJA23J2fpaspLuy7saVFQxApt97Fv161s1F7O";


Getting current closest drivers availability at a specific location

SnapCar.eta(48.859041, 2.327889).done(function (result) {
     $.each(result, function (key, info) {

       // info is an instance of SnapCar.ETAResult
       // you get info about eta.serviceClass

       if (info.status === SnapCar.ETAResultStatuses.OK) {
           // an ETA is available and set in info.eta
       } else if (info.status === SnapCar.ETAResultStatuses.UNAVAILABLE) {
           // this service class is not available at the moment
       }

     });
});


Getting meeting points

You can easily find if there are meeting points at a specific location (such as a train station or an airport).

SnapCar.meetingPoints(48.731010, 2.365823).done(function (specialArea) {

    // There's a special area at this location. 
    // Check out the specialArea info (which is an instance of SnapCar.SpecialArea)

}).fail(function (error) {
    if (error.code === 404) {
        // No special area/meeting points at this location
    } else {
        // An other error occurred
    }
});


Let's get all user's active bookings and cancel them

SnapCar.activeBookings().done(function (bookings) {

       $.each(bookings, function(key, booking) {

           // For each booking, we want to know the cancellation price.
           // If the booking cannot be cancelled (basically because the rider is already picked up), the done callbacks aren't called. The failure callbacks are called instead.
           // You may want to check if the cancellation is charged. Check out the SnapCar.CancellationFee reference for more information.

           booking.cancellationPrice().done(function (cancellationFee) {
               booking.cancel().done(function () {
                   // Booking properly cancelled
               });
           });
       });
});


We want to get all user's past bookings

SnapCar.bookingsHistory().done(function (history) {

       $.each(history.history, function(key, booking) {
           // booking is an instance of SnapCar.Booking
       });

       // Check out the history.moreBookingsAvailable() value to know if you can call history.nextBookings()
});


Let's create a booking on demand (with no planned pick up date) and without flat price.

// First, we get the info about the authenticated user
SnapCar.user().done(function (user) {

      // You may check the user.status value in order to know if he is allowed to make bookings

      // We fetch the allowed service classes
      SnapCar.serviceClasses().done(function (servicesClasses) {

          // We create a booking
          var booking = new SnapCar.Booking();

          // We define the rider and its pick up location
          booking.rider = user;
          booking.startLocation = new SnapCar.Location(48.731010, 2.365823, new SnapCar.Address('Aéroport de Paris-Orly', 'Orly', '94390', 'France'));

          // We also need to define the service class. Here we take one service class randomly.
          // In real life, you may present the different service class names to the user for selection.
          booking.serviceClass = servicesClasses[0];

          // We confirm the booking, this sends a request to the SnapCar platform
          booking.confirm()

          // This handler is called when the booking is either accepted by a driver or cancelled
          .done(function () {

              if (booking.status === SnapCar.BookingStatuses.GOING_TO_GET) {
                  // A driver has accepted the booking
              }

              else if (booking.status === SnapCar.BookingStatuses.CANCELLED) {
                  // Booking is cancelled, check out the booking.reason property to know why. It is probably set as SnapCar.BookingCancellationReasons.NO_DRIVER which means that no driver could accept the booking.
              }

              else {
                  // Other status, unlikely to happen unless the driver has switched to another status in the meantime.
              }

          // This handler is called when the SnapCar platform confirms the booking creation
          }).progress(function(error) {

              // Booking creation confirmed by the platform. Dispatch in progress, waiting for driver acceptance.

          // This handler is called upon error (ex: no driver available)
          }).fail(function(error) {

              if (error.message === "no_driver") {
                  // No driver is available for the required service class. You may try with another service class.
              }

              // Check out the documentation for a comprehensive list of error messages.

          });
      });
  });


Let's create a booking in the future (with a planned pick up date) and without flat price.

// First, we get the info about the authenticated user
SnapCar.user().done(function (user) {

      // You may check the user.status value in order to know if he is allowed to make bookings

      // We fetch the allowed service classes
      SnapCar.serviceClasses().done(function (servicesClasses) {

          // We create a booking
          var booking = new SnapCar.Booking();

          // We define the rider and its pick up location
          booking.rider = user;
          booking.startLocation = new SnapCar.Location(48.731010, 2.365823, new SnapCar.Address('Aéroport de Paris-Orly', 'Orly', '94390', 'France'));

          // We define the date. Warning: you must ensure that the timezone is correct!
          booking.plannedStartDate = new Date("2016-01-01 00:00:00");

          // We also need to define the service class. Here we take one service class randomly.
          // In real life, you may present the different service class names to the user for selection.
          booking.serviceClass = servicesClasses[0];

          // We confirm the booking, this sends a request to the SnapCar platform
          booking.confirm()

          // This handler is called when the booking is confirmed
          .done(function () {

              if (booking.status === SnapCar.BookingStatuses.PENDING) {
                  // Your booking is waiting for dispatch in the future
              }

          // This handler is called upon error (ex: no driver available)
          }).fail(function(error) {

              // Check out the documentation for a comprehensive list of error messages.

          });
      });
  });


Let's create a booking in the future (with a planned pick up date) and with a flat price.

// First, we get the info about the authenticated user
SnapCar.user().done(function (user) {

    // You may check the user.status value in order to know if he is allowed to make bookings

    // We create a booking
    var booking = new SnapCar.Booking();

    // We define the rider and its pick up location
    booking.rider = user;
    booking.startLocation = new SnapCar.Location(48.731010, 2.365823, new SnapCar.Address('Aéroport de Paris-Orly', 'Orly', '94390', 'France'));
    booking.endLocation = new SnapCar.Location(48.855272, 2.345865, new SnapCar.Address('3 Boulevard du Palais', 'Paris', '75001', 'France'));
    booking.driverInfo = "Some useful info for you.";
    booking.nameboard = true; // We want a nameboard, for the example

    // We define the date. Warning: you must ensure that the timezone is correct!
    booking.plannedStartDate = new Date("2016-01-01 00:00:00");

    booking.flatPrices().done(function(prices) {

        // We have several prices, we will confirm the first one.
        // In real life, you may present the different prices for each service class to the user for selection.

        // We confirm the booking, this sends a request to the SnapCar platform
        prices[0].confirm()

        // This handler is called when the booking is confirmed
        .done(function () {

            if (booking.status === SnapCar.BookingStatuses.PENDING) {
                // Your booking is waiting for dispatch in the future
            }

        // This handler is called upon error (ex: no driver available)
        }).fail(function(error) {

            // Check out the documentation for a comprehensive list of error messages.

        });        
    });
});


Let's create a booking on demand (without a planned pick up date) and with a flat price.

// First, we get the info about the authenticated user
SnapCar.user().done(function (user) {

    // You may check the user.status value in order to know if he is allowed to make bookings

    // We create a booking
    var booking = new SnapCar.Booking();

    // We define the rider and its pick up location
    booking.rider = user;
    booking.startLocation = new SnapCar.Location(48.731010, 2.365823, new SnapCar.Address('Aéroport de Paris-Orly', 'Orly', '94390', 'France'));
    booking.endLocation = new SnapCar.Location(48.855272, 2.345865, new SnapCar.Address('3 Boulevard du Palais', 'Paris', '75001', 'France'));

    booking.flatPrices().done(function(prices) {

        // We have several prices, we will confirm the first one.
        // In real life, you may present the different prices for each service class to the user for selection.

        // We confirm the booking, this sends a request to the SnapCar platform
        prices[0].confirm()

        // This handler is called when the booking is either accepted by a driver or cancelled
        .done(function () {

            if (booking.status === SnapCar.BookingStatuses.GOING_TO_GET) {
                // A driver has accepted the booking
            }

            else if (booking.status === SnapCar.BookingStatuses.CANCELLED) {
                // Booking is cancelled, check out the booking.reason property to know why. It is probably set as SnapCar.BookingCancellationReasons.NO_DRIVER which means that no driver could accept the booking.
            }

            else {
                // Other status, unlikely to happen unless the driver has switched to another status in the meantime.
            }

        // This handler is called when the SnapCar platform confirms the booking creation
        }).progress(function(error) {

            // Booking creation confirmed by the platform. Dispatch in progress, waiting for driver acceptance.

        // This handler is called upon error (ex: no driver available)
        }).fail(function(error) {

            if (error.message === "no_driver") {
                // No driver is available for the required service class. You may try with another service class.
            }

            // Check out the documentation for a comprehensive list of error messages.

        });       
    });
});


Let's create a booking in advance (with a planned pick up date), without flat price and with a meeting point.

In the example below, we make this booking only if we find specific meeting points at this location. In real life, you would just check if there are meeting points and would propose the list to your user for selection but would make the booking anyway.


SnapCar.meetingPoints(48.731010, 2.365823).done(function (specialArea) {

  // There's a special area at this location. 

     // Let's create a booking on demand (with no planned pick up date) and without flat price.

     // First, we get the info about the authenticated user
     SnapCar.user().done(function (user) {

           // You may check the user.status value in order to know if he is allowed to make bookings

           // We fetch the allowed service classes
           SnapCar.serviceClasses().done(function (servicesClasses) {

               // We create a booking
               var booking = new SnapCar.Booking();

               // We define the rider and its pick up location
               booking.rider = user;
               booking.startLocation = new SnapCar.Location(48.731010, 2.365823, new SnapCar.Address('Aéroport de Paris-Orly', 'Orly', '94390', 'France'));

               // We define the date. Warning: you must ensure that the timezone is correct!
               booking.plannedStartDate = new Date("2016-01-01 00:00:00");

               // We also need to define the service class. Here we take one service class randomly.
               // In real life, you may present the different service class names to the user for selection.
               booking.serviceClass = servicesClasses[0];

               // We define the first meeting point
               // In real life, you may present the different meeting points to the user for selection.
               booking.meetingPoint = specialArea.meetingPoints[0];

               // We confirm the booking, this sends a request to the SnapCar platform
               booking.confirm()

               // This handler is called when the booking is confirmed
               .done(function () {

                   if (booking.status === SnapCar.BookingStatuses.PENDING) {
                       // Your booking is waiting for dispatch in the future
                   }

               // This handler is called upon error (ex: no driver available)
               }).fail(function(error) {

                   // Check out the documentation for a comprehensive list of error messages.

               });

           });
       });

}).fail(function (error) {
   if (error.code === 404) {
       // No special area/meeting points at this location
   } else {
       // An other error occurred
   }
});

Methods

abortRequest
(
  • The
)

Cancels a request performed against the web service.

Parameters:

  • The jQuery.Promise

    jQuery promise associated to the request to be cancelled.

activeBookings () jQuery.Promise

Gets the currently authentified rider's active bookings.

Returns:

jQuery.Promise:

A Promise object. Success handlers are called with an array of SnapCar.Booking as the single argument. Failure handlers are called with a single SnapCar.APIError argument upon error.

booking
(
  • id
)
jQuery.Promise

Gets information about a specific booking.

Parameters:

  • id Number

    The booking unique identifier.

Returns:

jQuery.Promise:

A Promise object. Success handlers are called with a SnapCar.Booking as the single argument. Failure handlers are called with a single SnapCar.APIError argument upon error.

bookingsHistory
(
  • offset=0
  • limit=20
)
jQuery.Promise

Gets the currently authentified rider's bookings history.

Parameters:

  • [offset=0] Number optional

    The position of the first booking in the pagination.

  • [limit=20] Number optional

    The maximum number of bookings to return.

Returns:

jQuery.Promise:

A Promise object. Success handlers are called with a SnapCar.BookingHistory as the single argument. Failure handlers are called with a single SnapCar.APIError argument upon error.

eta
(
  • lat
  • lng
)
jQuery.Promise

Retrieves current ETA and availability for each service class.

Parameters:

  • lat Number

    Latitude of the position at which you want to get the current eta and availability.

  • lng Number

    Longitude of the position at which you want to get the current eta and availability.

Returns:

jQuery.Promise:

A Promise object. Success handlers are called with an array of SnapCar.ETAResult as the single argument. Failure handlers are called with a single SnapCar.APIError argument upon error.

meetingPoints
(
  • lat
  • lng
)
jQuery.Promise

Retrieves meeting point information at a specific location.

Parameters:

  • lat Number

    Latitude of the position at which you want to get the information.

  • lng Number

    Longitude of the position at which you want to get the information.

Returns:

jQuery.Promise:

A Promise object. Success handlers are called with a SnapCar.SpecialArea as the single argument. Failure handlers are called with a single SnapCar.APIError argument upon error. Be aware that if no specific meeting point information is found at a location, the failure callback will be called with a SnapCar.APIError having a 404 code value.

serviceClasses
(
  • lat
  • lng
)
jQuery.Promise

Retrieves a list of all allowed service classes at a specific location.

Parameters:

  • lat Number

    Latitude of the position at which you want to get the allowed service classes.

  • lng Number

    Longitude of the position at which you want to get the allowed service classes.

Returns:

jQuery.Promise:

A Promise object. Success handlers are called with an array of SnapCar.ServiceClass as the single argument. Failure handlers are called with a single SnapCar.APIError argument upon error.

user () jQuery.Promise

Gets the currently authenticated user information.

Returns:

jQuery.Promise:

A Promise object. Success handlers are called with a SnapCar.Rider as the single argument. Failure handlers are called with a single SnapCar.APIError argument upon error.

Properties

baseDomain

String

Defined in dist/SnapCar.js:431

The web service base domain on which API calls are made. You can change this value in order to perform requests on demo/sandbox web services rather than the production one.

Default: "https://api.snapcar.com/public"

fallbackLocale

String

Defined in dist/SnapCar.js:462

Locale used as a default in case you would provide a non supported locale value. Its value is "en".

locale

String

Defined in dist/SnapCar.js:450

The user locale. As you may know, some information returned through the API are localized (ex. : the meeting point details). You need to set this value in order to receive data localized in the user language if supported. The fallbackLocale value is used otherwise.

Default: "en"

Example:

SnapCar.locale = "fr";

token

String

Defined in dist/SnapCar.js:441

The user token. You must provide this value in order to be able to make API calls.