> For the complete documentation index, see [llms.txt](https://docs.fibricheck.com/introduction/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.fibricheck.com/introduction/cloud-sdk/introduction.md).

# Introduction

You can integrate with FibriCheck Cloud in 3 ways:&#x20;

* Use the [Flutter SDK](https://github.com/fibricheck/flutter-sdk)
* Use the [JavaScript SDK](https://github.com/fibricheck/javascript-sdk)
* Use the REST API endpoints&#x20;

### SDK

{% hint style="danger" %}
By default the SDK's will connect to the **production environment**. Please make sure to point the SDK to the development environment for developing and testing your integration. You can find more information on how to configure this below.
{% endhint %}

{% tabs %}
{% tab title="Flutter" %}
This package serves as a Flutter wrapper around all [FibriCheck](https://www.fibricheck.com) cloud services.

To get started with the FibriCheck SDK you'll need to install it, and then get credentials which will allow you to access the backend.

## Installation

In your project, you can add the package below to the `pubspec.yaml` file. Replace {TOKEN} with your personal access token. You can get a new one [here](https://github.com/settings/tokens/new). Make sure you enable the `repo` scope.

```
   flutter_fibricheck_sdk:
     git:
       url: https://{TOKEN}@github.com/fibricheck/flutter-sdk
       ref: v1.0.0
```

### Quick Start

{% hint style="danger" %}
Make sure to correctly initalise the client to connect against the correct environment (development or production)
{% endhint %}

```dart
import 'package:flutter_fibricheck_sdk/flutter_fibricheck_sdk.dart';

// To use the FibriCheck development environment
_sdk = FLFibriCheckSdk.client("<consumerKey>", "<consumerSecret>", "dev");

// To use the FibriCheck production environment
_sdk = FLFibriCheckSdk.client("<consumerKey>", "<consumerSecret>");

await _sdk.authenticateWithEmail(
      ParamsOauth1WithEmail(email: "email", password: "password"),
      (consents) {
        _onConsentNeeded(consents);
      },
    );
```

The client method (default export) supports several options you may set to achieve the expected behavior:

| Name             | Default      | Description                                       |
| ---------------- | ------------ | ------------------------------------------------- |
| `env`            | `production` | Specifies the environment you connect to          |
| `consumerKey`    |              | **Required**. Your application's `consumerKey`    |
| `consumerSecret` |              | **Required**. Your application's `consumerSecret` |

For the env, `Env.dev` or `Env.production` enumeration from the library `flutter_fibricheck_sdk` can be used.

## API

When you initialize the sdk, the returned object will have the following methods available.

```dart
class FLFibricheckSDK {
  /// Create an account based on a [UserRegisterData] object
  /// and returns [UserData] of the created user
  ///
  /// can throw [EmailUsedError]
  Future<UserData> register(UserRegisterData data) async {}
  
  /// Authenticate with an [ParamsOauth1WithToken] object and returns a
  /// [TokenDataOauth1] object
  ///
  /// can throw [ApplicationNotAuthenticatedError], [AuthenticationError],
  ///  [LoginTimeoutError], [LoginFreezeError], [TooManyFailedAttemptsError], [MfaRequiredError]
  Future<TokenDataOauth1> authenticateWithToken(
      ParamsOauth1WithToken credentials, void Function(List<Consent> consents) onConsentNeeded) async {}
  
  /// Authenticate with an [ParamsOauth1WithEmail] object and returns a
  /// [TokenDataOauth1] object
  ///
  /// can throw [ApplicationNotAuthenticatedError], [AuthenticationError],
  ///  [LoginTimeoutError], [LoginFreezeError], [TooManyFailedAttemptsError], [MfaRequiredError]
  Future<TokenDataOauth1> authenticateWithEmail(
      ParamsOauth1WithEmail credentials, void Function(List<Consent> consents) onConsentNeeded) async {}
  
  /// Clears oauth session data
  bool logout() {}
  
  /// Gives consent based on a [Consent] object
  /// Returns the number of affected records
  Future<int> giveConsent(Consent consent) async {}
  
  /// Send a measurement to the cloud
  Future<Measurement> postMeasurement(MeasurementCreationData measurementCreationData, String cameraSdkVersion) async {}
  
  /// Check if the user is entitled to perform a measurement
  Future<bool> canPerformMeasurement() async {}
  
  /// Updates the measurement context for a given measurement id
  Future<int> updateMeasurementContext(String measurementId, MeasurementContext measurementContext) async {}
  
  /// Update the user profile of the [userId] provided
  /// with the given [ProfileData] and returns the number of affected records
  Future<int> updateProfile(ProfileData updateData) async {}
  
  /// Get a measurement based on a [measurementId]
  Future<Measurement> getMeasurement(String measurementId) async {
  
  /// Get all measurements of the current user
  Future<PagedMeasurementResult> getMeasurements(bool newestFirst) async {}
  
  /// Returns a measurement report url for the given measurement id
  /// or creates one if it not yet exists.
  Future<String> getMeasurementReportUrl(String measurementId) async {}
  
  /// Returns a list of periodic reports
  Future<PagedPeriodicReportsResult> getPeriodicReports(bool newestFirst) async {}
  
  /// Returns the pdf of a periodic report as a string
  Future<String> getPeriodicReportPdf(String reportId) async {}
  
  ///Activates a prescription hash, so the user can perform a measurement
  Future activatePrescription(String hash) async {}
  
  /// Return the general configuration as a [GeneralConfiguration].
  Future<GeneralConfiguration> getGeneralConfiguration() async {}
  
  /// Return the user configuration as a [UserConfiguration].
  Future<UserConfiguration> getUserConfiguration() async {}
  
  /// Update the user with the id [userId] configuration.
  /// The [key] is the key where to save the value for the user.
  /// The [value] is an object that can be jsonEncoded.
  /// Return true if the update was done successfully.
  Future<bool> updateUserConfig(String key, Object value) async {}
}

```

{% endtab %}

{% tab title="JavaScript / TypeScript" %}
This package serves as a JavaScript wrapper around all [FibriCheck](https://www.fibricheck.com) cloud services.

To get started with the FibriCheck SDK you'll need to install it, and then get credentials which will allow you to access the backend.

## Installation

In your project, if you are using yarn or npm you need to create a file called `.npmrc` at the root level of your project and add these lines. Replace ${AUTH\_TOKEN} with your personal access token. You can get a new one at [here](https://github.com/settings/tokens/new). Make sure you enable the `read:packages` scope.

```
@extrahorizon:registry=https://npm.pkg.github.com
@fibricheck:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=${AUTH_TOKEN}
```

Alternatively, this file can be added/edited in your home directory and it will be applied to all projects.

Explanation from GitHub on how to add your token can be found [here](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-npm-registry#authenticating-to-github-packages).

Using npm:

```shell
npm install --save @fibricheck/javascript-sdk react-native-device-info
```

Using yarn:

```shell
yarn add @fibricheck/javascript-sdk react-native-device-info
```

## Quick Start

To be able to receive data from the FibriCheck cloud services, an app should authenticate with a username/password or token/tokenSecret combination.

To debug your data, an additional request/response logger can be added.

{% hint style="danger" %}
Make sure to set the property `env: 'dev'` in the client configuration when developing against the development environment.
{% endhint %}

```typescript
import client from '@fibricheck/javascript-sdk';
import { requestLogger } from 'axios-logger';

(async () => {
  const sdk = client({
    env: 'dev',
    consumerKey: '',
    consumerSecret: '',
    requestLogger
  });

  await sdk.authenticate({
    username: '',
    password: '',
  });
})();
```

The client method (default export) supports several options you may set to achieve the expected behavior:

| Name             | Default      | Description                                       |
| ---------------- | ------------ | ------------------------------------------------- |
| `env`            | `production` | Specifies the environment you connect to          |
| `consumerKey`    |              | **Required**. Your application's `consumerKey`    |
| `consumerSecret` |              | **Required**. Your application's `consumerSecret` |

## API

When you initialize the sdk, the returned object will have the following interface. These descriptions and signatures are also available as inline JSDoc in your IDE.

```typescript
interface FibricheckSDK {
  /**
   * Create an account
   *
   * @param requestBody UserRegisterData
   * @returns User
   * @throws {EmailUsedError}
   */
  register: (data: UserRegisterData) => Promise<UserData>;
  /**
   * Use token authentication.
   * As second parameter you need to pass in callback function that is fired when the user needs to sign updated legal documents
   * @see https://docs.fibricheck.com/examples#legal-documents-updated
   * @example
   * await sdk.auth.authenticate({
   *   token: '',
   *   tokenSecret: '',
   * });
   * @throws {ApplicationNotAuthenticatedError}
   * @throws {AuthenticationError}
   * @throws {LoginTimeoutError}
   * @throws {LoginFreezeError}
   * @throws {TooManyFailedAttemptsError}
   * @throws {MfaRequiredError}
   */
  authenticate(credentials: ParamsOauth1WithToken,
    onConsentNeeded: (data: Consent[]) => void
  ): Promise<TokenDataOauth1>;
  /**
   * Use password authentication.
   * As second parameter you need to pass in callback function that is fired when the user needs to sign updated legal documents
   * @see https://docs.fibricheck.com/examples#legal-documents-updated
   * @example
   * await sdk.auth.authenticate({
   *   email: '',
   *   password: '',
   * });
   * @throws {ApplicationNotAuthenticatedError}
   * @throws {AuthenticationError}
   * @throws {LoginTimeoutError}
   * @throws {LoginFreezeError}
   * @throws {TooManyFailedAttemptsError}
   * @throws {MfaRequiredError}
   */
  authenticate(credentials: ParamsOauth1WithEmail,
    onConsentNeeded: (data: Consent[]) => void
  ): Promise<TokenDataOauth1>;
  /**
   *  Logout
   *  @returns {boolean} Success
   *  @example
   *  await sdk.authenticate({
   *    password: '',
   *    username: '',
   *  });
   *  sdk.auth.logout();
   */
  logout: () => boolean;
  /**
   * Return documents received from the `onConsentNeeded` callback on authentication after the user has approved them.
   * @params {Omit<Consent, 'url'>} data
   * @returns AffectedRecords
   */
  giveConsent: (data: Omit<Consent, 'url'>) => Promise<AffectedRecords>;
  /**
   * Send a measurement to the cloud.
   * @see https://docs.fibricheck.com/examples#react-component-to-make-a-measurement
   * @params {MeasurementCreationData} measurementData
   * @throws {NoActivePrescriptionError}
   * @returns {Promise<Measurement>} measurement
   */
  postMeasurement: (measurement: MeasurementCreationData, cameraSdkVersion?: string) => Promise<Measurement>;
  /**
   * Check if the user is entitled to perform a measurement
   * @returns {Promise<Measurement>} measurement
   */
  canPerformMeasurement: () => Promise<boolean>;
  /**
   * Add context to an existing measurement
   * @param {string} measurementId
   * @params {MeasurementError} measurementContext
   * @throws {LockedDocumentError}
   * @returns AffectedRecords
   */
  updateMeasurementContext: (measurementId: string, measurementContext: MeasurementContext) => Promise<AffectedRecords>;
  /**
   * Update the user profile
   * @param {string} userId
   * @params {ProfileData} profileData
   * @returns AffectedRecords
   */
  updateProfile: (profileData: ProfileData) => Promise<AffectedRecords>;
  /**
   * Gets a measurement by measurementId
   * @param {string} measurementId
   * @returns {Promise<Measurement>} measurement
   */
  getMeasurement: (measurementId: string) => Promise<Measurement>;
  /**
   * Gets all measurements for the current user
   * @returns {Promise<PagedResult<Measurement>>} measurements
   */
  getMeasurements: () => Promise<PagedResult<Measurement>>;
  /**
   * Returns an url that can be used to render or download the report as PDF.
   * @see https://docs.fibricheck.com/examples#requesting-a-measurement-report-and-rendering-pdf
   * @returns {string} url
   */
  getMeasurementReportUrl: (measurementId: string) => Promise<string>;
  /**
   * Gets a list of periodic reports
   * @returns {FindAllIterator<PeriodicReport>} periodicReports
   */
  getPeriodicReports: () => Promise<FindAllIterator<PeriodicReport>>;
  /**
   * Get the pdf of a periodic report
   * @returns {pdf} pdf
   */
  getPeriodicReportPdf: (reportId: string) => Promise<ArrayBuffer>;
  /**
   * Activates a prescription hash, so the user can perform a measurement
   * @throws {NotPaidError}
   * @throws {AlreadyActivatedError}
   */
  activatePrescription: (hash: string) => Promise<void>;
}

```

{% endtab %}
{% endtabs %}

### REST API

FibriCheck offers a REST API to integrate FibriCheck in your application. A public Postman workspace is available where you can see and try-out all the relevant endpoints.&#x20;

{% embed url="<https://www.postman.com/fibricheck-developers/workspace/fibricheck-partner-api/collection/26480141-dc9e4539-fbd9-47ac-bc91-e3fdd674cfcf>" %}

This workspace also contains an environment named `FibriCheck Development` that contains all the variables that are needed for the different API calls.&#x20;

<figure><img src="https://550842036-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1VHmKXYQVUzvBkU504K0%2Fuploads%2FmUufyTAJV0tmHPyY1PF0%2Fimage.png?alt=media&amp;token=2d3c8514-ed5c-4a80-99ab-911a80bfc5f5" alt=""><figcaption></figcaption></figure>

The variables `consumerKey`, `consumerSecret`, `email` and `password` need to be filled in before doing any API calls.&#x20;

The `accessToken` and `tokenSecret` values are automatically filled in when performing the authentication call that is available as a request.

All variables that have the `var_` prefix differ depending on the context and authenticated user.
