# How it Works

Source: https://docs.formance.com/modules/payments/connectors/generic/how-it-works

Stack: v3.2

The Generic Connector for Formance Payments provides a way to connect your Formance Stack with payment service providers that are not natively supported by Formance.

Formance Payments interacts with the remote payment service provider through the Generic Connector as follows:

```mermaid
sequenceDiagram
  participant Payments
  participant Generic Connector
  participant Service as Integration Service
  Payments ->> Generic Connector: Poll the data
  activate Generic Connector
  Generic Connector -->> Payments: Ok
  par Account list
    Generic Connector ->> Service: Request account list
    Service -->> Generic Connector: Account list
    Generic Connector -->> Payments: Account list
    loop for each account
      Generic Connector ->> Service: Request account balance
      Service -->> Generic Connector: Account balance
    end
  and Transactions list
    Generic Connector ->> Service: Request transactions
    Service -->> Generic Connector: Transactions list
    Generic Connector -->> Payments: Transactions list
  and Beneficiary list
    Generic Connector ->> Service: Request beneficiary list
    Service -->> Generic Connector: Beneficiary list
    Generic Connector -->> Payments: Beneficiary list
  end
  deactivate Generic Connector
```

The Generic Connector is in charge of polling the data from the payment service provider and then sending it to Formance Payments. It polls the following data:

- The list of accounts available in the payment service provider and their associated balances
- The list of transactions, polled independently of the accounts rather than per account
- The list of beneficiaries available in the payment service provider for payouts

## Integration with the payment service provider

The Generic Connector interacts with the payment service provider by sending requests formatted according to the contract defined in [`generic-openapi.yaml`](https://github.com/formancehq/payments/blob/main/ce/plugins/generic/client/generic-openapi.yaml) and expecting responses formatted according to the same contract.

As a consequence, it is necessary to create a service on your side that will interact with the payment service provider and expose the data in the expected format.

### Endpoints your service must expose

The connector calls six endpoints on the service URL you configured at install time. Every endpoint is mounted at the root and authenticates via the `Authorization: Bearer <apiKey>` header.

| Method | Path                                                  | Purpose                                                                                         | Payments capability       |
| ------ | ----------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ------------------------- |
| `GET`  | `/accounts?pageSize=&page=&sort=&createdAtFrom=`      | List internal accounts.                                                                         | `FETCH_ACCOUNTS`          |
| `GET`  | `/accounts/{accountId}/balances`                      | Return point-in-time balance(s) for an internal account.                                        | `FETCH_BALANCES`          |
| `GET`  | `/beneficiaries?pageSize=&page=&sort=&createdAtFrom=` | List external accounts (beneficiaries).                                                         | `FETCH_EXTERNAL_ACCOUNTS` |
| `GET`  | `/transactions?pageSize=&page=&sort=&updatedAtFrom=`  | List transactions updated after `updatedAtFrom`.                                                | `FETCH_PAYMENTS`          |
| `POST` | `/payouts`                                            | Initiate a payout to a beneficiary. Idempotent via `idempotencyKey` on the body.                | `CREATE_PAYOUT`           |
| `POST` | `/transfers`                                          | Initiate a transfer between two internal accounts. Idempotent via `idempotencyKey` on the body. | `CREATE_TRANSFER`         |

### Required behaviors

- **Pagination** — the list endpoints (`/accounts`, `/beneficiaries`, `/transactions`) accept `pageSize` and `page` query parameters. `pageSize` defaults to 100; honour it. The connector advances `page` until it has accumulated 100 rows newer than its watermark, or a response returns fewer than `pageSize` items. It then commits the watermark and, if there may be more, starts again at `page=1` with the new filter value (see [pagination and incremental sync](https://docs.formance.com/modules/payments/connectors/generic/wire-contract#pagination-and-incremental-sync)).
- **Incremental sync** — `/transactions` carries an `updatedAtFrom` query parameter that the connector seeds with the latest watermark from the previous cycle. Return only transactions updated at or after that timestamp. The connector skips any transaction whose `updatedAt` is not strictly after the watermark, so re-emitting the boundary row is safe.
- **Idempotency** — `POST /payouts` and `POST /transfers` both carry an `idempotencyKey` on the request body. If your service sees the same key twice, return the original response (HTTP 201) rather than initiating a duplicate.
- **Error envelope** — failures return a status of `400` or above with a JSON body shaped as `{"Title": "...", "Detail": "..."}`, as declared by the `Error` schema in the contract.

The full OpenAPI document for the contract lives at
[`github.com/formancehq/payments/blob/main/ce/plugins/generic/client/generic-openapi.yaml`](https://github.com/formancehq/payments/blob/main/ce/plugins/generic/client/generic-openapi.yaml).
That's the source of truth — fields you don't see on this page are still defined there (request bodies, response schemas, enum values).

The typical deployment of the Generic Connector is as follows:

```mermaid
graph LR
  Payments["Payments Core"]
  connector["Generic Connector"]
  service["Integration Service"]
  psp["Payment Service Provider"]
  subgraph Formance Payments
    Payments <--> connector
  end
  subgraph Your infrastructure
    connector <-- HTTP --> service
  end
  service <-- PSP specific protocol --> psp
```

## Polling mechanism

The Generic Connector uses a state-based approach for polling payment data efficiently.

### How it works

1. The connector stores the latest `updatedAt` timestamp among the transactions it has received
2. In subsequent polls, it uses this timestamp to fetch only new or updated data
3. The `updatedAtFrom` query parameter is passed in API calls to your service
4. This parameter indicates that only transactions from that specific point in time should be returned

### Data storage and updates

The system doesn't fetch all data fresh every time it polls. Instead:

- Each batch of data received is stored
- The internal state is updated with the latest timestamp of the data received
- In the next polling cycle, the updated timestamp is used to fetch only new or changed data

### Benefits

This polling method offers several advantages:

- **Reduced data transfer**: Only fetches new or updated information
- **Minimized load**: Reduces strain on both Formance and your API
- **No duplicates**: Ensures the database stays up-to-date without duplicating existing data

When setting up the Generic Connector, ensure that your API can handle and respond correctly to the `updatedAtFrom` query parameter. This allows the system to efficiently retrieve only the necessary data during each polling cycle.

## Authentication

When instantiating the Generic Connector, you will need to pass an API key that will be used to authenticate the requests to your service. The Generic Connector will send requests with the API key in the `Authorization` header so that your service can authenticate the requests.

Example:

```
Authorization: Bearer <API_KEY>
```
