> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tybritelabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Gift Cards

> Reference for the GiftCardsService class in the Tybrite SDK.

The `GiftCardsService` class (accessed via `client.giftCards`) manages the checking and redemption of store-issued gift cards.

## Methods

### `listGiftCards`

Retrieve all gift cards held by a specific customer (gift cards are merchant-issued stored-value/loyalty instruments, not a payment method). This is used for listing a customer's gift cards in their account dashboard.

<Note>
  `customerId` is **strictly required** for this endpoint to identify whose gift cards to retrieve. In addition, a customer identity must be supplied so Galactic Core can verify the requester owns those gift cards — **either** `xAuthToken` (the customer's session token) **or** `xExternalAuth` (a bring-your-own-auth assertion); provide one, not both.
</Note>

```typescript theme={null}
const { gift_cards } = await client.giftCards.listGiftCards({
  customerId: 'customer-uuid',
  xAuthToken: customerSession.access_token, // Required — customer JWT
  fields: 'code,balance,status,expiry_date' // Optional field filtering
});

gift_cards.forEach(gc => {
  console.log(`GC: ${gc.code} | Balance: ${gc.balance}`);
});
```

```json Response theme={null}
{
  "gift_cards": [
    {
      "code": "GTSA-1B2C-3D4E-5F6G",
      "balance": 100,
      "status": "active",
      "expiry_date": "2027-06-20"
    }
  ]
}
```

<Note>Customers with no gift cards get `{ "gift_cards": [] }`.</Note>

<Note>
  When listing gift cards for a customer, the resolved customer identity (`xAuthToken` or `xExternalAuth`) must match the `customerId` parameter. Otherwise the request returns 403. This means a leaked publishable key alone cannot enumerate another customer's gift cards — a customer credential is required.
</Note>

***

### `checkGiftCard`

Retrieve the current balance and status of a gift card using its code. Because gift cards operate as **bearer instruments** (like cash), this endpoint deliberately does *not* require a customer ID.

This allows both registered users and **guest checkout** users to check balances.

```typescript theme={null}
const details = await client.giftCards.checkGiftCard({
  code: 'GTSA-1B2C-3D4E-5F6G',
  fields: 'balance,status,expiry_date' // Optional
});

console.log(`Remaining Balance: ${details.balance}`);
console.log(`Valid: ${details.valid}`);   // true only when active, has balance, and not expired
console.log(`Status: ${details.status}`); // 'active' while redeemable
```

```json Response theme={null}
{
  "valid": true,
  "balance": 100,
  "status": "active",
  "expiry_date": "2027-06-20",
  "maximum_usage_percentage": 100,
  "gift_card": {
    "id": "c91a7…",
    "code": "GTSA-1B2C-3D4E-5F6G",
    "value": 100,
    "balance": 100,
    "status": "active",
    "expiry_date": "2027-06-20",
    "type": "promotional",
    "minimum_purchase_amount": 0,
    "maximum_usage_percentage": 100,
    "redemption_count": 0,
    "max_redemptions": null
  }
}
```

<Note>
  No customer auth required — the gift card code itself is the credential.
</Note>

***

## 🛡️ Secure Redemption Architecture

Tybrite does **not** expose a standalone redemption endpoint for gift cards. This architectural decision prevents financial race conditions (double-spending) and ensures that all gift card deductions are natively tied to a unified accounting ledger and order generated during checkout.

To redeem a gift card, pass the code and amount during the **order creation** process:

```typescript theme={null}
const order = await client.orders.createOrder({
  idempotencyKey: 'checkout-123',
  xTimestamp: timestamp,
  xSignature: signature,
  requestBody: {
    // ...other order details...
    gift_card_redemption: { 
      code: 'GTSA-1B2C-3D4E-5F6G', 
      amount: 5000 
    }
  }
});
// → { order: { id, total_amount, payment_status, … }, post_processing_warnings? }
// A failed redemption surfaces as a post_processing_warnings entry — see OrdersService.
```

This ensures the gift card balance is only deducted if the main order succeeds.

## Card Lifecycle

A gift card is redeemable only when **all** of the following hold — this is exactly what the `valid` flag on `checkGiftCard` reflects:

* **Active**: `status` is `active`.
* **Has balance**: `balance` is greater than zero.
* **Not expired**: the current date is before `expiry_date`.

Once the balance reaches zero or the `expiry_date` passes, the card is no longer redeemable even though its `status` may still read `active`. Always rely on the `valid` flag rather than inferring usability from `status` alone.

***

<Tip>
  To let customers pay for partial orders with gift cards, use `checkGiftCard` to see the available balance first, then include it in the `gift_card_redemption` object when calling `createOrder`.
</Tip>

***

## Authentication Flow

`listGiftCards` requires a customer credential in addition to your API key — the session JWT from `AuthenticationService` passed as `xAuthToken`, or a bring-your-own-auth assertion passed as `xExternalAuth`:

```typescript theme={null}
// 1. Sign the customer in (magic link, OTP, or password)
const result = await client.authentication.login({
  requestBody: {
    email: 'john.doe@example.com',
    password: 'their-password'
  }
});
// → { user: { id, email, … }, session: { access_token, refresh_token, expires_at } }

// 2. Use the returned session access token to list their gift cards
const { gift_cards } = await client.giftCards.listGiftCards({
  customerId: result.user.id,
  xAuthToken: result.session.access_token
});
// → { gift_cards: [{ code, balance, status, expiry_date }, …] }
```

The resolved customer identity must match the requested `customerId` before any gift cards are returned.

### Response Codes

| Code  | Meaning                                              |
| ----- | ---------------------------------------------------- |
| `200` | Success.                                             |
| `400` | Missing required `customer_id` (on `listGiftCards`). |
| `401` | Missing or invalid `xAuthToken` or API key.          |
| `403` | Customer token does not match the `customer_id`.     |
| `404` | Gift card not found (on `checkGiftCard`).            |
