> ## Documentation Index
> Fetch the complete documentation index at: https://ekacare-durgesh-output-language.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# ABHA SDK

> Complete implementation guide for the ABHA[Ayushman Bharat Digital Mission] SDK

# ABHA SDK Implementation

This guide provides everything you need to integrate the ABHA SDK into your application.

## Overview

The ABHA SDK allows you to integrate Create ABHA, Login with ABHA flows into your healthcare applications. It provides:

* **Create ABHA**: Create a new ABHA using Mobile or Aadhaar
* **Login with ABHA**: Login with ABHA address\[PHR Address], ABHA number, Adhaar number or Mobile number linked to your ABHA into your healthcare application.

## Installation

### Prerequisites

* A modern web browser.
* Your domain must be whitelisted with Eka Care to avoid CORS(Cross-Origin Resource Sharing) error.
  (Contact Eka Care to request API access and domain whitelisting.)
* A valid HTML container element where the SDK will mount.

### Setup

Add the following HTML and script tags to your webpage:

```html theme={null}
<!DOCTYPE html>
<html>
  <head>
    <title>ABHA SDK Integration</title>

    <!-- Include ABHA SDK CSS -->
    <link
      rel="stylesheet"
      href="https://unpkg.com/@eka-care/abha/dist/sdk/abha/css/abha.css"
    />
  </head>
  <body>
    <h1>ABHA SDK Demo</h1>

    <!-- Mount Button -->
    <button class="button" onclick="mountABHASDK()">Mount SDK</button>

    <!-- Container for ABHA SDK -->
    <div id="sdk_container"></div>

    <!-- Include ABHA SDK JS -->
    <script
      type="module"
      async
      src="https://unpkg.com/@eka-care/abha/dist/sdk/abha/js/abha.js"
    ></script>

    <script>
      function mountABHASDK() {
        window.initAbhaApp({
          containerId: "sdk_container",
        
         // Pass access token and oid
          data: {
            accessToken: "<your_access_token>", // Pass the access token you have
            oid: "<your_oid_if_available>", // Pass if you have the OID
            orgIcon: "<url_of_your_org_icon>", // Pass the url to your organisation icon which starts with for ex: https://cdn.eka.care/vagus/cl56w6zg3001f0scsaqrh16is.jpg
            linkToOrgIcon: "<url_of_image_to_link_abha_to_your_org>", // Pass the url of an image which depicts linking abha to your organisation for ex https://cdn.eka.care/vagus/cm6agrs5000090tfwfz984x5b.webp
          },

          // Success callback
          onSuccess: async (params) => {
            console.log("ABHA flow completed successfully:", params);
            // Example: Store ABHA data in your app
            dispatch({
              type: "set-only-healthid-data",
              healthIdData: formatter(params.response.data),
            });
          },

          // Error callback
          onError: (params) => {
            console.error("ABHA flow failed:", params);
            if (window.EkaAbha) {
              window.EkaAbha.onAbhaFailure(JSON.stringify(params));
            }
          },
        });
      }
    </script>
  </body>
</html>
```

## Core Functions

### 1. initAbhaApp

Initializes and renders the ABHA SDK in your specified container.

**Parameters:**

| Name          | Type                                                                              | Required    | Description                                                                                                                                                                                                                                                                                                                                                               |
| ------------- | --------------------------------------------------------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `containerId` | `string`                                                                          | ✅           | The HTML element ID where the SDK will mount.                                                                                                                                                                                                                                                                                                                             |
| `data`        | `{ accessToken: string; oid?: string; orgIcon?: string; linkToOrgIcon?: string }` | ⚙️ Optional | Configuration data for initializing the ABHA flow. <br />- accessToken: Pass the access token you have. <br />- oid: Pass if available. <br />- orgIcon: URL of your organisation's icon to display inside the SDK url should start with https\://. <br />- linkToOrgIcon: URL of the icon representing “Link ABHA to your organisation” url should start with https\://. |
| `onSuccess`   | `(params: AbhaSuccessParams) => void`                                             | ✅           | Triggered when the user successfully creates or logs in to ABHA.                                                                                                                                                                                                                                                                                                          |
| `onError`     | `(params: AbhaErrorParams) => void`                                               | ✅           | Triggered when an error occurs during the ABHA flow.                                                                                                                                                                                                                                                                                                                      |

**Example:**

```javascript theme={null}
window.initAbhaApp({
  containerId: "sdk_container",
  data: {
    accessToken: "your_access_token_here",
    oid: "optional_oid_here",
    orgIcon: "url_of_your_org_icon",
    linkToOrgIcon: "url_of_image_to_link_abha_to_your_org",
  },
  onSuccess: (params) => {
    console.log("ABHA created successfully!", params);
  },
  onError: (error) => {
    console.error("ABHA flow failed:", error);
  },
});
```

## Callback Parameters

### onSuccess Callback

The onAbhaSuccess callback is triggered when the ABHA flow completes successfully.
It returns verified user details and tokens, which can be used to log in or continue the user’s session.

**Callback Signature:**

```typescript theme={null}
onSuccess: (params: TOnAbhaSuccessParams) => void;
```

**Type Definitions**

```typescript theme={null}
export type TOnAbhaSuccessParams = {
  response: TAuthVerifyV2Response;
};

export type TAuthVerifyV2Response = {
  skip_state: number;
  method: AUTH_METHOD;
  data?: {
    tokens: {
      sess: string;
      refresh: string;
    };
    profile: TProfileRecord;
  };
  txn_id: string;
  error?: {
    code: number;
    message: string;
  };
};
```

**Parameters**

| Key        | Type                    | Description                                                                                                |
| ---------- | ----------------------- | ---------------------------------------------------------------------------------------------------------- |
| `response` | `TAuthVerifyV2Response` | The complete ABHA verification response, containing session tokens, user profile, and transaction details. |

**Example:**

```javascript theme={null}
const onSuccess = (params) => {
  console.log("ABHA Success:", params.response);

  const abhaNumber = params.response.data?.profile?.abha_number;
  const userName = params.response.data?.profile?.name;

  alert(`Welcome ${userName}! Your ABHA Number: ${abhaNumber}`);

  // Optionally pass data to native bridge
  if (window.EkaAbha) {
    window.EkaAbha.onAbhaSuccess(JSON.stringify(params));
  }
};
```

### onError Callback

The onError callback is triggered whenever an ABHA flow fails or is interrupted.
It provides details about the failure through structured parameters, allowing you to handle or forward the error appropriately (for example, to native apps or monitoring tools).

**Callback Signature:**

```typescript theme={null}
onError: (params: TOnAbhaFailureParams) => void;
```

**Type Definitions**

```typescript theme={null}
type TOnAbhaFailureParams = {
  error?: string;
  response?: TAuthVerifyV2Response;
};

export type TAuthVerifyV2Response = {
  skip_state: number;
  method: AUTH_METHOD;
  data?: {
    tokens: {
      sess: string;
      refresh: string;
    };
    profile: TProfileRecord;
  };
  txn_id: string;
  error?: {
    code: number;
    message: string;
  };
};
```

**Parameters**

| Key        | Type                     | Description                                                      |
| ---------- | ------------------------ | ---------------------------------------------------------------- |
| `error`    | `string?`                | Short description of the failure or error message.               |
| `response` | `TAuthVerifyV2Response?` | Partial or full API response object returned from ABHA services. |

**Example:**

```javascript theme={null}
const onError = (params) => {
  console.error("ABHA Error:", params);

  if (params.response?.error?.code === 1001) {
    alert("Authentication failed. Please try again.");
  } else if (params.error === "NETWORK_ERROR") {
    alert("Please check your internet connection.");
  } else {
    alert("Something went wrong. Please retry.");
  }

  // Forward the error to native handler if available
  if (window.EkaAbha) {
    window.EkaAbha.onAbhaFailure(JSON.stringify(params));
  }
};
```

**Suggest Handling**
-Always log the full error response (params) for debugging.
-Display friendly error messages for known error.code values.
-If params.response is present, inspect response.error.message for more detail.
-If integrating with native apps, forward the serialized error object:

```javascript theme={null}
window.EkaAbha.onAbhaFailure(JSON.stringify(params));
```

### Container Styling

Ensure your container has sufficient space:

```html theme={null}
<div
  id="sdk_container"
  style="width: 100%; height: 600px; border: 1px solid #ddd;"
></div>
```

## Complete Implementation Example

```html theme={null}
<!DOCTYPE html>
<html>
  <head>
    <title>ABHA SDK Complete Example</title>
    <link
      rel="stylesheet"
      href="https://unpkg.com/@eka-care/abha/dist/sdk/abha/css/abha.css"
    />
  </head>
  <body>
    <h1>ABHA SDK Demo</h1>

    <button onclick="mountABHASDK()">Launch ABHA SDK</button>

    <div
      id="sdk_container"
      style="width: 100%; height: 600px; border: 1px solid #ccc;"
    ></div>

    <script
      type="module"
      async
      src="https://unpkg.com/@eka-care/abha/dist/sdk/abha/js/abha.js"
    ></script>

    <script>
      function mountABHASDK() {
        window.initAbhaApp({
          containerId: "sdk_container",
          data: {
            accessToken: "<your_access_token>", 
            oid: "<your_oid_if_available>", 
            orgIcon: "<url_of_your_org_icon>",
            linkToOrgIcon: "<url_of_image_to_link_abha_to_your_org>",
          },
          onSuccess: (params) => {
            console.log("ABHA flow completed successfully:", params);
          },
          onError: (params) => {
            console.error("ABHA flow failed:", params);
          },
        });
      }
    </script>
  </body>
</html>
```

## Type Definitions

```typescript theme={null}
interface InitAbhaAppParams {
  containerId: string;
  data?: {
    accessToken: string;
    oid?: string;
    orgIcon?: string;              
    linkToOrgIcon?: string;        
  };
  onSuccess: (params: AbhaSuccessParams) => void;
  onError: (params: AbhaErrorParams) => void;
}

interface AbhaSuccessParams {
  response: {
    data: {
      abha_number?: string;
      abha_address?: string;
      name?: string;
      gender?: string;
      yearOfBirth?: string;
      mobile?: string;
    };
  };
  message: string;
  status: "SUCCESS";
}

interface AbhaErrorParams {
  status: "FAILED";
  message: string;
  error_code?: string;
  details?: any;
}
```

## Troubleshooting

### Common Issues

#### 1. SDK Not Rendering

**Problem**: Nothing appears in the container.

**Solution**:

* Ensure containerId matches an existing HTML element.
* Verify the SDK JS and CSS are correctly loaded.
* Check browser console for errors.

#### 2. Callback Not Triggered

**Problem**: onSuccess or onError isn’t firing.

**Solution**:

* Make sure both callbacks are passed as valid functions.
* Avoid race conditions (e.g., calling before SDK fully loads).

#### 3. Styling Issues

**Problem**: SDK content appears misaligned or clipped.

**Solution**:

* Give your container a fixed height (e.g., 600px).
* Ensure no parent element uses overflow: hidden.
