npm package: @flowpay-io/embed-core
Description: Flowpay SDK - Embed client - Core functionality and utilities
Author: Flowpay
Latest version: 1.2.0

# @flowpay-io/embed-core

Framework-agnostic core library for controlling Flowpay embedded iframe via postMessage.

## Installation

```bash
pnpm add @flowpay-io/embed-core
```

## Usage

```typescript
import {
  createFlowpayClient,
  type InputLaunchPayload,
} from "@flowpay-io/embed-core";
import { createSignedLogin } from "@flowpay-io/embed-auth/client";
import { IsoCountryCode } from "@flowpay-io/shared/types";

// Create embed client
const client = createFlowpayClient({
  embedOrigin: "https://my.flowpay.io",
  signatureProvider: {
    signPayload: async (payload) => {
      // Use createSignedLogin to canonicalize, encode, and sign the payload
      // It delegates signature generation to your server (recommended)
      return await createSignedLogin(
        payload,
        async (canonicalPayload: string) => {
          const response = await fetch("/api/sign-payload", {
            method: "POST",
            body: JSON.stringify({ payload: canonicalPayload }),
          });
          const { signature } = await response.json();
          return signature;
        },
      );
    },
  },
});

// Use an iframe with allow attribute for camera, microphone, geolocation - required by KYC verification:
// <iframe id="my-iframe" allow="camera; microphone; geolocation" src="..."></iframe>

// Attach to iframe (after iframe loads)
const iframe = document.getElementById("my-iframe") as HTMLIFrameElement;
iframe.addEventListener("load", async () => {
  if (iframe.contentWindow) {
    client.attach(iframe.contentWindow, client.urls.embedOrigin);
    await client.waitUntilReady();

    // Optional: pass UI locale as envelope meta (not part of the signed payload)
    const locale = "cs";

    // Login with launch payload (merchant = onboarding, customer = existing Flowpay customer)
    const launchPayload: InputLaunchPayload = {
      country: IsoCountryCode.CZ,
      merchantId: "merchant-123",
      partnerCode: "partner-abc",
      regNum: "12345678",
      userId: "user-456",
      email: "user@example.com",
      phone: "+420123456789",
      // createdAt is optional - auto-set by client when autoSetCreatedAt is true (default)
    };
    // For existing customer: { partnerCode, customerId, userId, repId }

    await client.login({ launchPayload, locale });
  }
});

// Listen to events
client.on("ready", () => {
  console.log("Flowpay is ready");
});

client.on("loginSuccess", () => {
  console.log("Login successful");
});
```

## Server-side Implementation

The client-side code above calls `/api/sign-payload` to sign the canonical payload. Here's an example server-side implementation:

```typescript
import { generateSignature } from "@flowpay-io/embed-auth/server";

// This endpoint is called by the client-side handleSign callback
app.post("/api/sign-payload", async (req, res) => {
  const { payload: canonicalPayload } = req.body;

  const signature = await generateSignature(
    canonicalPayload,
    async () => process.env.PARTNER_SHARED_SECRET, // Store securely
  );

  res.json({ signature });
});
```

## Configuration

The SDK accepts the following configuration options:

```typescript
interface FlowpaySdkConfig {
  // Origin of the embedded iframe URL
  embedOrigin?: string;

  // Host origin (defaults to window.location.origin)
  hostOrigin?: string;

  // Allowed host origins for security validation
  allowedhostOrigins?: string[];

  // Enable simulation mode (development only)
  simulationMode?: boolean; // default: false

  // Custom logger
  logger?: {
    debug?: (...args: unknown[]) => void;
    warn?: (...args: unknown[]) => void;
    error?: (...args: unknown[]) => void;
  };

  // Signature provider for secure authentication
  signatureProvider?: SignatureProvider;

  // Automatically set createdAt on payload (default: true)
  autoSetCreatedAt?: boolean;
}
```

## Links

- **Homepage**: [https://www.flowpay.io](https://www.flowpay.io)
- **Documentation**: [https://developers.flowpay.io](https://developers.flowpay.io)