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

# Criar Oferta

> Cria uma nova oferta para um produto existente

#### Escopo

```bash theme={null}
    write offers
```

<Note>
  `product` deve ser o Id de um produto **existente e pertencente à sua conta** — caso contrário, `400` com `{ "detail": "Produto não encontrado." }`.
</Note>

<Info>
  Ao criar a oferta, a Cakto automaticamente:

  * Gera o link de pagamento (`https://pay.cakto.com.br/{id_da_oferta}`)
  * Adiciona a oferta ao **checkout padrão** do produto, se houver um
</Info>

O preço segue os mesmos limites por moeda descritos em [Criar Produto](/api-reference/products/create).


## OpenAPI

````yaml POST /public_api/offers/
openapi: 3.0.3
info:
  title: Cakto API
  version: 1.0.0
  description: Documentação da API pública do Cakto.
servers:
  - url: https://api.cakto.com.br
    description: Cakto API
security: []
paths:
  /public_api/offers/:
    post:
      tags:
        - offers
      description: |-
        Public API for managing offers, inherits from OfferAPIView,
        customizes the schema generation and authentication/permission settings.
      operationId: offers_create
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Offer'
          multipart/form-data:
            schema:
              $ref: '#/components/schemas/Offer'
          application/x-www-form-urlencoded:
            schema:
              $ref: '#/components/schemas/Offer'
        required: true
      responses:
        '201':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Offer'
              examples:
                Successo:
                  value:
                    id: 5Hrb526
                    name: Nome da Oferta
                    image: https://example.com/image.png
                    price: 5
                    units: 1
                    default: true
                    product: fb3fda61-e88f-43b5-982a-32d50f112414
                    status: active
                    type: unique
                    intervalType: week
                    interval: 1
                    recurrence_period: 30
                    quantity_recurrences: -1
                    trial_days: 0
                    max_retries: 3
                    retry_interval: 1
          description: Corpo da resposta status 201
        '400':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OfferCreate400'
              examples:
                CampoAusente:
                  value:
                    campo: Este campo é obrigatório.
                ProdutoNãoExistente:
                  value:
                    detail: Produto não encontrado.
                PreçoInválido:
                  value:
                    price: O preço mínimo do produto é de R$ 5,00
                IntervaloInválido:
                  value:
                    interval: O intervalo de tempo deve ser maior que 0.
                StatusInválido:
                  value:
                    status: O status da oferta deve ser "active" ou "disabled".
                DiasDeTesteInválido:
                  value:
                    trial_days: O número de dias de teste deve estar entre 0 e 365.
                RecorrênciasInválidas:
                  value:
                    quantity_recurrences: >-
                      O número de recorrências deve estar entre 1 e 100 ou ser
                      igual a -1 para recorrência infinita.
          description: Corpo da resposta status 400
        '401':
          description: Request não autenticado devido à ausência ou invalidez do token.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UnauthenticatedError'
              examples:
                Token ausente ou inválido:
                  $ref: '#/components/examples/UnauthenticatedErrorExample'
      security:
        - OAuth Token: []
components:
  schemas:
    Offer:
      type: object
      description: >-
        Secure file replacement (context)

        -------------------------------

        When an update replaces an existing uploaded file (e.g. a profile
        picture), the

        old file usually remains in storage unless you explicitly delete it.
        Over time,

        this leaves orphaned files and increases storage costs.


        What this class does

        --------------------

        This is an opt-in base serializer that deletes old files from storage
        *after* a

        successful update that replaces (or clears) a Django
        ``models.FileField`` /

        ``models.ImageField``.


        It is configured via ``Meta.delete_replaced_files_fields``:

        - As a list/tuple/set of field names, or

        - As a dict mapping field name → options.


        Supported options (per field)

        -----------------------------

        - ``delete_on_clear`` (bool, default True): when the update sets the
        field to
          ``None``/empty, delete the previous stored file.

        Example usage (simple)

        ----------------------

        ```python

        class UserUpdateSerializer(DeleteOldFilesMixin,
        serializers.ModelSerializer):  # DeleteOldFilesMixin should be first
        that the actual serializer
            class Meta:
                model = User
                fields = ["id", "picture", "first_name", "last_name"]
                delete_replaced_files_fields = ["picture"]
        ```


        Example usage (per-field options)

        --------------------------------

        ```python

        class DocumentUpdateSerializer(DeleteOldFilesMixin,
        serializers.ModelSerializer):  # DeleteOldFilesMixin should be first
        that the actual serializer
            class Meta:
                model = Document
                fields = ["id", "picture", "document_image"]
                delete_replaced_files_fields = {
                    "picture": {"delete_on_clear": True},
                    "document_image": {"delete_on_clear": False},
                }
        ```
      properties:
        id:
          type: string
          readOnly: true
          title: Identificador
          description: Identificador único da oferta
        name:
          type: string
          title: Nome
          description: Nome da oferta, exibido no checkout e em outros locais
          maxLength: 255
        image:
          type: string
          format: uri
          nullable: true
        price:
          type: number
          format: double
          description: Preço da oferta
        currency:
          allOf:
            - $ref: '#/components/schemas/CurrencyEnum'
          title: Moeda
          description: |-
            Moeda da oferta

            * `BRL` - Real
            * `EUR` - Euro
            * `MXN` - Peso Mexicano
            * `PEN` - Sol Peruano
            * `USD` - Dólar
            * `CLP` - Peso Chileno
            * `COP` - Peso Colombiano
            * `ARS` - Peso Argentino
            * `BOB` - Boliviano
            * `UYU` - Peso Uruguayo
        units:
          type: integer
          maximum: 2147483647
          minimum: 1
          title: Unidades
          description: >-
            Número de unidades que o cliente irá adquirir ao comprar esta
            oferta.
        default:
          type: boolean
          readOnly: true
          description: Indica se esta é a oferta padrão do produto
        product:
          type: string
          description: Produto ao qual esta oferta pertence
          title: Produto
        status:
          allOf:
            - $ref: '#/components/schemas/OfferStatus'
          description: |-
            Status atual da oferta

            * `active` - Ativo
            * `disabled` - Desabilitado
            * `deleted` - Deletado
        type:
          allOf:
            - $ref: '#/components/schemas/ProductType'
          title: Tipo de pagamento
          description: |-
            Tipo de pagamento da oferta (ex: unique, subscription)

            * `unique` - Pagamento único
            * `subscription` - Assinatura recorrente
        intervalType:
          allOf:
            - $ref: '#/components/schemas/IntervalTypeEnum'
          title: Tipo de intervalo
          description: >-
            Tipo de intervalo do acesso concedido pela oferta (ex: month, week,
            lifetime)


            * `week` - Semana

            * `month` - Mês

            * `year` - Ano

            * `lifetime` - Vitalício
        interval:
          type: integer
          maximum: 2147483647
          minimum: -2147483648
          title: Quantidade de intervalos
          description: >-
            Número de intervalos que serão concedidos ao comprar esta oferta.
            Ex: `interval=2` e `intervalType=month` concede 2 meses de acesso.
        recurrence_period:
          type: integer
          maximum: 2147483647
          minimum: -2147483648
          title: Período de recorrência
          description: Número de dias entre cada cobrança da assinatura
        quantity_recurrences:
          type: integer
          maximum: 2147483647
          minimum: -2147483648
          title: Quantidade de recorrências
          description: >-
            Número de cobranças que serão feitas na assinatura. Use -1 para
            cobranças ilimitadas.
        trial_days:
          type: integer
          maximum: 2147483647
          minimum: -2147483648
          title: Dias de teste
          description: Número de dias de teste grátis antes da primeira cobrança
        max_retries:
          type: integer
          maximum: 2147483647
          minimum: -2147483648
          title: Quantidade de retentativas de cobrança
          description: >-
            Número máximo de retentativas de cobrança em caso de falha no
            pagamento
        retry_interval:
          type: integer
          maximum: 2147483647
          minimum: -2147483648
          title: Intervalo entre retentativas
          description: Número de dias entre cada retentativa de cobrança
      required:
        - default
        - id
        - name
        - price
        - product
    OfferCreate400:
      type: object
      properties:
        campo:
          type: string
      required:
        - campo
    UnauthenticatedError:
      type: object
      properties:
        detail:
          type: string
    CurrencyEnum:
      enum:
        - BRL
        - EUR
        - MXN
        - PEN
        - USD
        - CLP
        - COP
        - ARS
        - BOB
        - UYU
      type: string
      description: |-
        * `BRL` - Real
        * `EUR` - Euro
        * `MXN` - Peso Mexicano
        * `PEN` - Sol Peruano
        * `USD` - Dólar
        * `CLP` - Peso Chileno
        * `COP` - Peso Colombiano
        * `ARS` - Peso Argentino
        * `BOB` - Boliviano
        * `UYU` - Peso Uruguayo
    OfferStatus:
      enum:
        - active
        - disabled
        - deleted
      type: string
      description: |-
        * `active` - Ativo
        * `disabled` - Desabilitado
        * `deleted` - Deletado
    ProductType:
      enum:
        - unique
        - subscription
      type: string
      description: |-
        * `unique` - Pagamento único
        * `subscription` - Assinatura recorrente
    IntervalTypeEnum:
      enum:
        - week
        - month
        - year
        - lifetime
      type: string
      description: |-
        * `week` - Semana
        * `month` - Mês
        * `year` - Ano
        * `lifetime` - Vitalício
  examples:
    UnauthenticatedErrorExample:
      summary: Token ausente ou inválido
      description: Token ausente ou inválido
      value:
        detail: As credenciais de autenticação não foram fornecidas.
  securitySchemes:
    OAuth Token:
      type: http
      scheme: bearer
      in: header
      name: Authorization
      description: >-
        Token de autenticação do tipo `Bearer {access_token}`, onde
        `{access_token}` é o token obtido no fluxo de
        [autenticação](/authentication).

````