# HYPER-SDK-CAPACITOR

Capacitor Wrapper over HyperSDK which enables payment orchestration via different dynamic modules. More details available at Juspay Developer Docs for [Express Checkout SDK](juspay.io/in/docs/ec-headless/capacitor) and [Payment Page SDK](https://juspay.io/in/docs/hyper-checkout/capacitor).

## Install

```bash
npm install hyper-sdk-capacitor
npx cap sync
```

### Android

Add following maven url in root build.gradle:

```groovy
allprojects {
    repositories {
        ....
        ....
        maven { url "https://maven.juspay.in/jp-build-packages/hyper-sdk/" }
    }
}
```

#### **Updating Client ID**

Add the clientId ext property in root(top) `build.gradle`:

```groovy
buildscript {
    ....
    ext {
        ....
        clientId = "<clientId shared by Juspay team>"
        hyperSDKVersion = "2.2.2"
        excludedMicroSDKs = ["<microSDK to be excluded>"]
        microSDKs = ["<microSDK to be included>"]
        ....
    }
    ....
}
```
- You can also provide an override for base SDK version present in plugin (the newer version among both would be considered). - Optional
- Exclude microSDKs provided with HyperSDK for given clientId by adding excludedMicroSDKs - Optional
- Override the set of microSDKs provided with HyperSDK for given clientId by adding microSDKs - Optional. When set, **only** the listed microSDKs are added, replacing the default set resolved for the clientId. Use `excludedMicroSDKs` instead if you only want to drop a few from the default set.


### iOS

Place the `MerchantConfig.txt` file inside the folder where the Podfile is present. This file doesn't need to be added to the project. The content of the file should be as below

```txt
clientId = <clientId shared by Juspay Team>
```

Add below post_install script in the Podfile

```sh
post_install do |installer|
 fuse_path = "./Pods/HyperSDK/Fuse.rb"
 clean_assets = false # Pass true to re-download all the assets
 if File.exist?(fuse_path)
   if system("ruby", fuse_path.to_s, clean_assets.to_s)
   end
 end
end
```

Run the following command inside the ios folder of your project:

```sh
pod install
```

**(Optional)** Add the following property in `package.json` of your project before running pod install if you want to override the base SDK version present in the plugin (the newer version among both would be considered):

```json
  {
    ....
    "scripts": {
      ....
    },
    "dependencies": {
      ....
    },
    "devDependencies": {
      ....
    },
    "hyperSdkIOSVersion": "2.2.2"
    ....
  }
```

#### Swift Package Manager (SPM) Integration

For Capacitor 6+ projects using SPM, the `hyperSdkIOSVersion` from `package.json` is also supported.

> **Updating HyperSDK Version with SPM**
> 
> If you need to change the `hyperSdkIOSVersion` after initial installation, you must:
> 1. Update `hyperSdkIOSVersion` in your `package.json`
> 2. Uninstall and reinstall the plugin:
>    ```bash
>    npm uninstall hyper-sdk-capacitor
>    npm install hyper-sdk-capacitor
>    npx cap sync ios
>    ```
> 3. Close and reopen Xcode to re-resolve packages
>
> This is required because SPM caches resolved package versions.

__________________

### Import HyperSDK

```ts
import { Plugins } from '@capacitor/core';
import 'hyper-sdk-capacitor';

const { HyperServices } = Plugins;
```

### Prefetch

To keep the SDK up to date with the latest changes, it is highly recommended to call preFetch as early as possible. It takes a `JSON Object` as its argument.

```javascript
await HyperServices.preFetch(payload);
```

__________________

### Step-1: Create HyperServices Object

This method creates an instance of `HyperServices` class in the Capacitor Plugin on which all the `HyperSDK` APIs / methods are triggered. It internally uses the current activity as an argument.

**Note**: This method is mandatory and is required to call any other subsequent methods from `HyperSDK`.

```javascript
await HyperServices.createHyperServices();
```

**Note**: For Web, following parameters should be passed createHyperServices API.

- clientId : "Client shared by Juspay"
- service :
  - `"in.juspay.hyperpay"` (For Payment Page)
  - `"in.juspay.hyperapi"` (For Express Checkout)

```javascript
await HyperServices.createHyperServices(clientId, service)
```

__________________

### Step-2: Initiate

This method should be called on the render of the host screen. This will boot up the SDK and start the Hyper engine. It takes a `JSON Object` as its argument which will contain the base parameters for the entire session and remains static throughout one SDK instance lifetime.

**Notes**:

1. It is highly recommended to initiate SDK from the order summary page (at least 5 seconds before opening your payment page) for seamless user experience.
2. `initiate` should be called only once in one session.

```javascript
await HyperServices.initiate(initiatePayload);
```

`Create Initiate payload` - Follow the documentation for [initiatePayload] (https://juspay.io/in/docs/hyper-checkout/capacitor/base-sdk-integration/initiating-sdk)

__________________

### To check if SDK is initialized or not

```javascript
var { isInitialised } = await HyperServices.isInitialised();
```

### Step-3: Process

This API can be triggered any number of times based on requirements or app flow structure.
It should not be called on an HyperSDK instance which has not been initiated (Initiate API should be called before calling process API and make sure SDK is initialized)

This API should be triggered for all operations required from `HyperSDK`. The operation may be related to:

- Displaying payment options on your payment page
- Performing a transaction
- User's payment profile management

The result of the process call is provided in the `Hyper Event listener`, later discussed in [step-4](#step-4-listen-to-events-from-hypersdk).

```javascript
await HyperServices.process(processPayload);

```

Follow the documentation for [Process Payload](https://juspay.io/in/docs/hyper-checkout/capacitor/base-sdk-integration/rendering-the-checkout-screen) :

__________________

### Step-4: Listen to events from HyperSDK

`HyperSDK` Native Module will be emitting all the relevant events to JS via `notifyListeners` and JavaScript modules can then register to receive events by invoking `addListener` on the `HyperServices` Plugin instance with the event name `'HyperEvent'`. The listener will return a `JSON` response.

The following events should be handled here:

- `show_loader`: To show a loader for the processing state.
- `hide_loader`: To hide the previously shown loader.
- `initiate_result`: Result of initiate done in [step-2](#step-2-initiate).
- `process_result`: Result of the process operation done in [step-3](#step-3-process).

```javascript

HyperServices.addListener('HyperEvent', async (data) => {
   var event = data["event"];
   switch (event) {
      case "show_loader": {
         // Show a loader
      }
      break;
      case "hide_loader": {
         // Hide Loader
      }
      break;
      case "initiate_result": {
         // Initiate api response
      }
      break;
      case "process_result": {
         // Process result
      }
      break;
      default:
         let payload = data["payload"];
         console.log("process result: ", payload)
      break;
   }
});
```

#### WEB

Documentation : <https://juspay.io/in/docs/hyper-checkout/web/overview/integration-architecture>
Once the payment is complete the user is redirected to the return_url configured by you. Following is the typical destination where the user is taken to:
Payment Response : <https://juspay.io/in/docs/hyper-checkout/web/base-sdk-integration/handle-payment-response>

__________________

### Step-5: Android Hardware Back-Press Handling

`HyperSDK` internally uses an android fragment for opening the bank page and will need the control to hardware back press when the bank page is active. This can be done by invoking `addEventListener` on the `backButton` provided by React Capacitor.

If the blocking asynchronous call `HyperServices.onBackPressed()` returns true, `HyperSDK` will handle the back press, else merchant can handle it.

```javascript
import { App } from '@capacitor/app';

.........
.........

App.addListener('backButton', async (data) => {
  const { onBackPressed } = await HyperServices.onBackPressed();
  if (!onBackPressed) {
    window.history.back();
  }
});
```

__________________

### Terminate SDK

This method shall be triggered when `HyperSDK` is no longer required.
Note : After calling terminate, initiate has to be called again.

```javascript
await HyperServices.terminate();
```

__________________

### Helper Method: Is Null

This is a helper method and can be used to check whether the `HyperServices` object is `null` at any particular moment. It is a blocking synchronous method and returns a `boolean` value.

```javascript
var { isNull } = await HyperServices.isNull();
```

__________________

### Payment Widget (Inline Embedded Checkout)

The payment widget allows you to embed the payment UI inline inside your page rather than taking over the full screen. The SDK renders into a native view that is positioned to match a placeholder div in your HTML.

#### Step 1: Add a placeholder div in your HTML

The div must have an explicit `position`, `width`, and a `height` (height is optional — if omitted the SDK will size itself):

```html
<div id="paymentWidgetContainer" style="
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100px;
  display: none;
"></div>
```

#### Step 2: Show the div and call process with the div ID

Pass the div's element ID as a string for `fragmentViewGroups.paymentWidget`. The plugin automatically reads `getBoundingClientRect()` on the div and positions the native container to match it.

```javascript
// Show the placeholder div before calling process
document.getElementById('paymentWidgetContainer').style.display = 'block';

await HyperServices.process({
  requestId: '<uuid>',
  service: 'in.juspay.hyperpay',
  payload: {
    fragmentViewGroups: {
      paymentWidget: 'paymentWidgetContainer', // div element ID
    },
    action: 'paymentPage',
    // ... rest of your process payload
  },
});
```

#### Step 3: Hide the div on terminate

```javascript
document.getElementById('paymentWidgetContainer').style.display = 'none';
await HyperServices.terminate();
```

**Notes:**
- The div must be visible (not `display: none`) when `process()` is called so `getBoundingClientRect()` returns valid dimensions.
- On **Web**, the div ID is resolved to a DOM element and passed directly to the SDK.
- On **Android** and **iOS**, a native `FrameLayout`/`UIView` is created and positioned at the same screen coordinates as the div. The WebView remains interactive outside the widget area.
- If `height` is `0` or not set on the div, the native container uses `WRAP_CONTENT` and the SDK sizes itself.

## License

hyper-sdk-capacitor is distributed under [AGPL-3.0-only](https://github.com/juspay/hyper-sdk-capacitor/src/main/LICENSE.md) license.
