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

# POST /v1/loyalty/memberships/{id}/upgrade

> Hand a full stamps card in for a membership in the program it upgrades to.

Turns a full stamps card into a membership in another program. A stamps program can name the program it upgrades to in `rules.stamps.upgrades_to_program_id`. For example, a Club card with six visits can be exchanged for the VIP card. When the card is complete, this call deletes it, including its movements, and gives the customer the target membership.

The customer's wallet card follows automatically. If the target membership had no pass yet, the same card in Apple Wallet or Google Wallet turns into the target program's card, with its design and data. If the customer already had a pass for the target program, the old card is voided, because Apple and Google do not let a server remove a pass from a phone.

## Endpoint

```
POST https://api.keebai.com/v1/loyalty/memberships/{id}/upgrade
```

## Required scope

`loyalty:write`

## Headers

| Header | Required | Value |
| - | - | - |
| `Authorization` | Yes | `Bearer kbai_pk_<token>` |

## Path parameters

| Parameter | Type | Description |
| - | - | - |
| `id` | `string` | The `ObjectId` of the stamps membership being handed in. |

The request has no body.

## Example request

```bash curl theme={"system"}
curl -X POST https://api.keebai.com/v1/loyalty/memberships/6650aaaa1111bbbb2222cccc/upgrade \
  -H "Authorization: Bearer kbai_pk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

```js JavaScript theme={"system"}
const response = await fetch(
  "https://api.keebai.com/v1/loyalty/memberships/6650aaaa1111bbbb2222cccc/upgrade",
  {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.KEEBAI_API_TOKEN}` },
  },
);
const { membership } = await response.json();
console.log(`Now in program ${membership.program_id}`);
```

```python Python theme={"system"}
import os, requests

resp = requests.post(
    "https://api.keebai.com/v1/loyalty/memberships/6650aaaa1111bbbb2222cccc/upgrade",
    headers={"Authorization": f"Bearer {os.environ['KEEBAI_API_TOKEN']}"},
    timeout=10,
)
resp.raise_for_status()
membership = resp.json()["membership"]
```

## Response

### 201 Created

| Field | Description |
| - | - |
| `upgraded_card` | The card that was handed in, as it was before the upgrade. It no longer exists. |
| `membership` | The membership in the target program. It is new, or the customer's existing one if they already had it. |
| `entry` | The ledger entry recorded on the target membership: `kind: "adjust"`, `amount: 0`, `source: "upgrade"`, with `ref` set to the id of the program the card came from. |

```json theme={"system"}
{
  "upgraded_card": {
    "_id": "6650aaaa1111bbbb2222cccc",
    "program_id": "6650a1b2c3d4e5f6a7b8c9d0",
    "status": "active",
    "stamps_count": 6
  },
  "membership": {
    "_id": "6650bbbb2222cccc3333dddd",
    "program_id": "6650a1b2c3d4e5f6a7b8c9d1",
    "status": "active",
    "stamps_count": 0
  },
  "entry": {
    "_id": "6650dddd3333eeee4444ffff",
    "membership_id": "6650bbbb2222cccc3333dddd",
    "kind": "adjust",
    "metric": "stamps",
    "amount": 0,
    "balance_after": 0,
    "source": "upgrade",
    "ref": "6650a1b2c3d4e5f6a7b8c9d0",
    "note": "Subió desde Club con 6 sellos"
  }
}
```

Membership objects are abbreviated here. They have the same shape as [GET /v1/loyalty/memberships/{id}](https://docs.keebai.com/dev/endpoints/loyalty-membership-get.md).

### 400 Bad Request

The program is not a stamps program, or it has no `upgrades_to_program_id`.

### 401 Unauthorized

The token is missing, invalid, revoked, or expired.

### 403 Forbidden

The token does not have the `loyalty:write` scope.

### 404 Not Found

There is no membership with that id in your company, or the target program no longer exists.

### 409 Conflict

The card is not full yet, the card is not active (for example, it was already handed in), or the target program is not active. Nothing changes.

## Operational notes

* **The upgrade happens only once.** Claiming the full card is a single conditional update. If two calls race, one succeeds and the other gets `409`.
* **The old card is gone.** It is deleted the same way as [DELETE /v1/loyalty/memberships/{id}](https://docs.keebai.com/dev/endpoints/loyalty-membership-delete.md).
* **Partial redemptions use the ledger.** To pay out what a card has accumulated without upgrading, record `kind: "redeem"` with [POST .../ledger](https://docs.keebai.com/dev/endpoints/loyalty-ledger-record.md). With `reset_on_redeem`, the card goes back to `0`.
* **The cash value of a stamp is `rules.stamps.value_per_stamp`.** The wallet binding `{{stampsValue}}` shows the stamp count multiplied by that value, for example the cashback accumulated so far.


## OpenAPI

````yaml POST /v1/loyalty/memberships/{id}/upgrade
openapi: 3.0.0
info:
  title: Keebai Public API
  description: Superficie pública REST autenticada con Personal Access Tokens (PAT).
  version: 1.0.0
  contact: {}
servers:
  - url: https://api.keebai.com
    description: Production
security: []
tags: []
paths:
  /v1/loyalty/memberships/{id}/upgrade:
    post:
      tags:
        - loyalty
      summary: Subir de programa con la tarjeta de sellos completa
      description: >-
        Solo programas de sellos con `upgrades_to_program_id`. La tarjeta
        completa se elimina con sus movimientos y el cliente queda con una
        membresía en el programa destino; si ya la tenía, se reutiliza. Si el
        destino no tenía pase, la tarjeta del Wallet se actualiza sola al
        programa nuevo; si ya tenía, la vieja queda anulada. Con la tarjeta
        incompleta responde 409.
      operationId: PublicLoyaltyController_upgradeMembership
      parameters:
        - name: id
          required: true
          in: path
          schema:
            type: string
      responses:
        '201':
          description: ''
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PublicMembershipUpgradeResponseDto'
      security:
        - PAT: []
components:
  schemas:
    PublicMembershipUpgradeResponseDto:
      type: object
      properties:
        upgraded_card:
          description: 'La tarjeta entregada: sellos en 0 y estado consumed'
          allOf:
            - $ref: '#/components/schemas/PublicMembershipDto'
        membership:
          description: La membresía del programa destino (nueva o la que ya tenía)
          allOf:
            - $ref: '#/components/schemas/PublicMembershipDto'
        entry:
          $ref: '#/components/schemas/PublicLedgerEntryDto'
      required:
        - upgraded_card
        - membership
        - entry
    PublicMembershipDto:
      type: object
      properties:
        _id:
          type: string
        program_id:
          type: string
        customer:
          $ref: '#/components/schemas/PublicMembershipCustomerViewDto'
        serial_number:
          type: string
          description: >-
            Identificador del pase en Apple y Google. Es lo que codifica el
            código de barras por defecto
        balance_points:
          type: number
          description: >-
            Saldo de puntos. Si el programa vence puntos y ya pasó el plazo, se
            lee 0 sin que el ledger cambie
          example: 1240
        stamps_count:
          type: number
          example: 7
        tier:
          type: string
          description: Clave del nivel alcanzado. Vacío si el programa no es de tiers
          example: gold
        status:
          type: string
          enum:
            - active
            - suspended
            - revoked
        enrolled_at:
          type: string
        created_at:
          type: string
        updated_at:
          type: string
      required:
        - _id
        - program_id
        - serial_number
        - balance_points
        - stamps_count
        - tier
        - status
        - enrolled_at
        - created_at
        - updated_at
    PublicLedgerEntryDto:
      type: object
      properties:
        _id:
          type: string
        membership_id:
          type: string
        program_id:
          type: string
        kind:
          type: string
          enum:
            - earn
            - redeem
            - adjust
        metric:
          type: string
          enum:
            - points
            - stamps
          description: Lo decide el tipo del programa, no el request
        amount:
          type: number
          description: 'Movimiento con signo: negativo en un canje'
          example: -50
        balance_after:
          type: number
          description: Saldo resultante después del movimiento
          example: 1190
        source:
          type: string
          example: pos-sucursal-centro
        ref:
          type: string
          example: boleta-99120
        note:
          type: string
        created_at:
          type: string
      required:
        - _id
        - membership_id
        - program_id
        - kind
        - metric
        - amount
        - balance_after
        - source
        - ref
        - note
        - created_at
    PublicMembershipCustomerViewDto:
      type: object
      properties:
        id:
          type: string
          example: crm-8842
        name:
          type: string
          example: Camila Rojas
        phone:
          type: string
          example: '+56912345678'
        email:
          type: string
          example: camila@ejemplo.cl
      required:
        - id
  securitySchemes:
    PAT:
      scheme: bearer
      bearerFormat: kbai_pk_<hex>
      type: http
      description: >-
        Personal Access Token con prefijo `kbai_pk_`. Generar desde el portal
        con permiso `developer.manage_tokens`.

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.