# JavaScript SDK

The JavaScript SDK is a TypeScript-first, Node.js 20+ client for resolving receipt recipients and issuing end-to-end encrypted receipts and credit notes. Version `2.2.1` aligns its receipt flow and behavior with the Java SDK while using idiomatic JavaScript objects and readonly service properties.

The SDK preserves Cheqi's zero-knowledge boundary: your integration supplies the definitive receipt values, the SDK encrypts them locally for every matched owner device, and Cheqi receives ciphertext rather than the plaintext receipt body. The SDK does not calculate, enrich, or reconcile receipt values.

Source code and releases: [cheqi-io/cheqi-sdk-javascript](https://github.com/cheqi-io/cheqi-sdk-javascript)

## Requirements

- Node.js 20 or newer
- an API key, or an OAuth access token with the required permissions
- a base64-encoded PKCS#8 RSA private key when using recipient-side decryption


## Installation

```bash
npm install @cheqi/sdk@2.2.1
```

## Initialization

With an API key:

```typescript
import { CheqiSDK, Environment } from "@cheqi/sdk";

const sdk = new CheqiSDK({
  apiEndpoint: Environment.SANDBOX,
  apiKey: process.env.CHEQI_API_KEY
});
```

With per-call OAuth access tokens, omit `apiKey` and pass the token to the service method:

```typescript
const sdk = new CheqiSDK({
  apiEndpoint: Environment.SANDBOX
});
```

Standard environments configure both the API endpoint and customer-facing receipt origin:

| Environment | API endpoint | Receipt origin |
|  --- | --- | --- |
| `Environment.SANDBOX` | `https://sandbox.api.cheqi.io` | `https://sandbox.receipt.cheqi.io` |
| `Environment.TEST` | `https://test.api.cheqi.io` | `https://test.receipt.cheqi.io` |
| `Environment.PRODUCTION` | `https://api.cheqi.io` | `https://receipt.cheqi.io` |


For a custom deployment, configure both URLs if you use download receipts:

```typescript
const sdk = new CheqiSDK({
  apiEndpoint: "http://localhost:8080",
  receiptDownloadBaseUrl: "http://localhost:5190",
  apiKey: process.env.CHEQI_API_KEY
});
```

Configuration also accepts `privateKey`, `timeoutSeconds`, `maxRetries`, `logger`, a Fetch-compatible `fetch` implementation, or a custom `apiClient`.
The current decryption methods still take `privateKeyBase64` explicitly, even when a private key is present in the SDK configuration.

## Issue a receipt

Use plain JavaScript objects for recipient-identification data and the `createReceiptPayload` validation factory for the definitive receipt payload:

```typescript
import {
  CheqiSDK,
  Environment,
  PaymentType,
  UnitCode,
  createReceiptPayload,
  type IdentificationDetails
} from "@cheqi/sdk";

const sdk = new CheqiSDK({
  apiEndpoint: Environment.SANDBOX,
  apiKey: process.env.CHEQI_API_KEY
});

const identificationDetails = {
  paymentType: PaymentType.CARD_PAYMENT,
  cardDetails: {
    paymentAccountReference: "PAR123456789",
    cardProvider: "VISA",
    lastFourDigits: "4242"
  },
  recipientEmail: "customer@example.com"
} satisfies IdentificationDetails;

const receiptPayload = createReceiptPayload({
  documentNumber: "POS-2026-0001",
  issueDate: new Date(),
  currency: "EUR",
  receiptSubtotal: "10.00",
  totalBeforeTax: "10.00",
  totalTaxAmount: "2.10",
  totalAmount: "12.10",
  taxesApplied: true,
  paymentDetails: {
    paymentMeansCode: "48",
    description: "Card payment",
    cardProvider: "VISA",
    cardLastFour: "4242",
    merchantId: "MID-123",
    paymentTerminalId: "TID-456"
  },
  products: [{
    name: "Coffee beans",
    brandName: "Cheqi Coffee",
    identifier: "SKU-COFFEE-001",
    quantity: 1,
    baseQuantity: 1,
    unitCode: UnitCode.C62,
    unitPrice: "10.00",
    subtotal: "10.00",
    total: "12.10",
    taxes: [{ rate: 21, type: "VAT", taxableAmount: "10.00", amount: "2.10" }]
  }],
  taxes: [{
    rate: 21,
    type: "VAT",
    taxableAmount: "10.00",
    amount: "2.10",
    label: "VAT 21%"
  }]
});

const result = await sdk.receiptService.issueReceipt(
  identificationDetails,
  receiptPayload
);

if (result.isAccepted()) {
  console.log(result.cheqiReceiptId, result.deliveryRouteType);
} else if (result.isEmailReceiptRequired()) {
  // Generate and submit the permitted email-fallback receipt explicitly.
} else if (result.isDownloadEnvelopeRequired()) {
  // Generate the final ReceiptEnvelope locally, then complete the fallback.
}
```

`ReceiptPayload` is definitive. Supply `taxesApplied`, totals, line values, payment presentation, and jurisdictional data yourself. `IdentificationDetails` is only matching and local fallback context; the SDK does not copy it into `ReceiptPayload.paymentDetails` on the digital route.

### Authentication and store overloads

The optional arguments to `issueReceipt` are:

```typescript
// Configured API key
await sdk.receiptService.issueReceipt(identificationDetails, receiptPayload);

// Per-call OAuth token
await sdk.receiptService.issueReceipt(identificationDetails, receiptPayload, accessToken);

// Store ID and per-call OAuth token
await sdk.receiptService.issueReceipt(identificationDetails, receiptPayload, storeId, accessToken);
```

When only a third string argument is present, the SDK treats a UUID as `storeId` and any other non-empty string as an access token. Pass both arguments when using a store with OAuth so the intent is explicit.

## Delivery routes and fallbacks

`ReceiptResult.deliveryRouteType` is the authoritative route:

- `DIGITAL`: the SDK encrypts the exact serialized payload independently for every matched owner device and submits it immediately.
- `DOWNLOAD_FALLBACK`: the SDK creates and uploads a client-encrypted download when `IdentificationDetails.paymentType` is available. Otherwise, it returns `isDownloadEnvelopeRequired()`.
- `EMAIL_FALLBACK`: the SDK returns `isEmailReceiptRequired()`. `issueReceipt` does not send the email automatically.


If recipient resolution returns `routeFound: false`, `issueReceipt` throws `CheqiSDKError` with error code `CUSTOMER_NOT_FOUND`; it does not return a synthetic customer-not-found result.

### Explicit download receipt

For a known customer-without-Cheqi flow, skip matching:

```typescript
const result = await sdk.receiptService.issueDownloadReceipt(
  { paymentType: PaymentType.CASH },
  receiptPayload,
  accessToken
);

console.log(result.downloadUrl);
```

The content key is generated locally and remains in the URL fragment; Cheqi receives only the download ID, ciphertext, and template hash. Anyone with the complete URL can decrypt the receipt, so deliver it through an appropriate customer-facing channel.

If the matched fallback needs a caller-generated final envelope, complete it with:

```typescript
const completed = await sdk.receiptService.completeDownloadFallback(
  result,
  receiptEnvelope,
  templateHash,
  accessToken
);
```

Your integration owns durable storage, scheduling, retry, monitoring, and retention for deferred download work. See [Download links](/receipts/download-fallback) for the encryption and recovery contract.

## Matching and lower-level encryption

Use the service APIs when you need to control matching, encryption, or submission separately:

```typescript
const resolution = await sdk.matchingService.matchCustomer(
  identificationDetails,
  accessToken
);

const delivery = sdk.encryptionService.encryptReceiptForRecipient(
  receiptPayloadJson,
  resolution.recipients[0]
);

const response = await sdk.receiptService.submitEncryptedReceipt({
  matchId: resolution.matchId,
  deviceDeliveries: [delivery]
}, accessToken);
```

The caller must honor the selected route, encrypt for every owner device, and preserve identical definitive plaintext across device encryptions.

## Credit notes

Merchant-issued credit notes use the same recipient-resolution and per-device encryption model:

```typescript
const result = await sdk.creditNoteService.issueCreditNote(
  identificationDetails,
  parentCheqiReceiptId,
  definitiveCreditNotePayload,
  accessToken
);
```

To associate the credit note with a store, pass `storeId` before `accessToken`. The SDK serializes the supplied payload without calculations and submits it through the separate encrypted credit-note endpoint.

Customer return requests are separate from merchant-issued credit notes. Decrypt, deserialize, and validate a polling or webhook request in one call:

```typescript
const request = sdk.decryptionService.decryptCreditNoteInitiationRequest(
  webhook.data.creditNoteInitiationRequest,
  privateKeyBase64
);
```

The validation covers identifiers, positive quantities, reason codes, note lengths, refund preference, and bank-account requirements. Your integration remains responsible for eligibility, remaining quantities, accepted outcomes, taxes, and the definitive refund. See [Receiving Return Requests](/creditnote/receiving-returns) and [Issuing Credit Notes](/creditnote/issuing-credit-notes).

## Receipt and webhook decryption

`decryptReceipt` accepts an `EncryptedReceiptDeliveryResponse` from polling or a `WebhookReceiptEnvelope` from `data.encryptedReceipt` or `data.encryptedCreditNote`:

```typescript
const envelope = sdk.decryptionService.decryptReceipt(
  webhook.data.encryptedReceipt,
  privateKeyBase64
);
```

The plaintext is already a complete `ReceiptEnvelope`; no backend-context merge step is required.

## Verification

The verification service implements RFC 8785 canonical JSON hashing and Exclusive XML Canonicalization 1.0 hashing:

```typescript
const verification = sdk.verificationService;

const cheqiHash = verification.calculateCheqiReceiptHash(cheqiReceiptJson);
const ublHash = verification.calculateUblHash(ublPurchaseReceiptXml);

const jsonMatches = verification.verifyJsonHash(cheqiReceiptJson, cheqiHash);
const xmlMatches = verification.verifyXmlHash(ublPurchaseReceiptXml, ublHash);
```

## Store management

Store operations require an OAuth access token with the relevant store permissions:

```typescript
const stores = sdk.storeService;

const store = await stores.createStore(companyId, createStoreRequest, accessToken);
const allStores = await stores.getStores(companyId, accessToken);
const activeStores = await stores.getActiveStores(companyId, accessToken);
const selected = await stores.getStore(companyId, storeId, accessToken);
const updated = await stores.updateStore(companyId, storeId, updateStoreRequest, accessToken);

await stores.activateStore(companyId, storeId, accessToken);
await stores.deactivateStore(companyId, storeId, accessToken);
await stores.deleteStore(companyId, storeId, accessToken);
```

## Errors

High-level methods throw `CheqiSDKError`. API failures retain the error code, HTTP status, and correlation ID where available:

```typescript
import { CheqiSDKError } from "@cheqi/sdk";

try {
  await sdk.receiptService.issueReceipt(
    identificationDetails,
    receiptPayload,
    accessToken
  );
} catch (error) {
  if (error instanceof CheqiSDKError) {
    console.error(error.message, error.errorCode, error.httpStatusCode);
    if (error.hasCorrelationId()) {
      console.error("Correlation ID:", error.correlationId);
    }
  }
}
```

## Generated models

The root package exports typed model interfaces, validation factories, and enums. Every OpenAPI-generated model, enum, and serializer is also available under `Generated`:

```typescript
import { Generated } from "@cheqi/sdk";

const route = Generated.RecipientResolutionResponseDeliveryRouteTypeEnum.DIGITAL;
```

## Available services

`CheqiSDK` exposes services and configuration as readonly properties:

- `receiptService`
- `creditNoteService`
- `matchingService`
- `encryptionService`
- `decryptionService`
- `downloadService`
- `verificationService`
- `storeService`
- `apiClient`
- `config`