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

# Ruby

> Integre a Whallet em aplicações Ruby em minutos.

> [card] [Whallet Ruby SDK](https://github.com/whallet-oficial/whallet-ruby-sdk)
>
> Repositório oficial — issues, changelog e contribuições.

## Pré-requisitos

* Ruby 3.2+
* Gem `whallet-ruby` 1.2.2 ou superior
* Uma chave de API ([criar no dashboard](https://whallet.com/dashboard))

## Instalação

```bash Gemfile theme={"theme":{"light":"github-light","dark":"vesper"}}
# Adicione ao seu Gemfile:
gem 'whallet-ruby'
# Depois execute:
bundle install
```

```bash bundler theme={"theme":{"light":"github-light","dark":"vesper"}}
bundle add whallet-ruby
```

```bash gem theme={"theme":{"light":"github-light","dark":"vesper"}}
gem install whallet-ruby
```

## Configuração

Armazene sua chave de API em uma variável de ambiente e nunca no código:

```ruby theme={"theme":{"light":"github-light","dark":"vesper"}}
# config/initializers/whallet.rb
Whallet.configure do |config|
  config.api_token = ENV['WHALLET_API_KEY']
  config.timeout   = 30 # opcional, em segundos
end
```

> [card] Dev mode x Produção
>
> O ambiente é definido **pela chave utilizada**, não por configuração do SDK — chaves criadas em Dev mode geram transações simuladas. Saiba mais [aqui](https://whallet.mintlify.site/pages/devmode.md).

## Primeira cobrança

```ruby theme={"theme":{"light":"github-light","dark":"vesper"}}
checkout = Whallet.checkouts.create(
  Whallet::Resources::Checkouts.new(
    methods: ['PIX'],
    products: [
      Whallet::Resources::Billings::Product.new(
        external_id: 'prod_abc123xyz',
        name:        'Pro plan',
        quantity:    1,
        price:       1000 # em centavos
      )
    ],
    metadata: Whallet::Resources::Billings::Metadata.new(
      return_url:     'https://meusite.com/app',
      completion_url: 'https://meusite.com/pagamento/sucesso'
    )
  )
)

puts checkout.url # URL de pagamento para o cliente
```

**Resposta:**

```json theme={"theme":{"light":"github-light","dark":"vesper"}}
{
  "success": true,
  "error": null,
  "data": {
    "id": "bill_12345667",
    "url": "https://whallet.com/pay/bill_12345667",
    "amount": 1000,
    "status": "PENDING",
    "devMode": true,
    "createdAt": "2026-08-04T18:38:28.573Z"
  }
}
```

## Recursos disponíveis

Todos os recursos são acessíveis pela fachada `Whallet.<recurso>`:

| Recurso | Métodos |
| - | - |
| `customers` | `list` `get` `create` `delete` |
| `products` | `list` `get` `create` `delete` |
| `coupons` | `list` `get` `create` `delete` `toggle` |
| `checkouts` | `list` `get` `create` `refund` |
| `payment_links` | `list` `get` `create` `refund` |
| `subscriptions` | `list` `create` `cancel` `change_plan` `record_usage` |
| `transparents` | `list` `create` `check` `simulate_payment` `refund` |
| `pix` | `list` `get` `send_pix` |
| `payouts` | `list` `get` `create` |
| `store` | `get` `merchant_info` `mrr` `revenue` |
| `webhook_endpoints` | `list` `get` `create` `delete` |

```ruby theme={"theme":{"light":"github-light","dark":"vesper"}}
Whallet.customers.list(limit: 25)
Whallet.products.get('prod_abc123xyz')
Whallet.checkouts.refund('bill_abc123xyz')
Whallet.subscriptions.cancel('subs_abc123xyz')
```

## Tratamento de erros

O SDK de Ruby **levanta exceções** — ele não retorna `{ data, error, success }`. Toda falha herda de `Whallet::Error`:

```ruby theme={"theme":{"light":"github-light","dark":"vesper"}}
begin
  checkout = Whallet.checkouts.create(data)
rescue Whallet::ConfigurationError => e
  # token ausente ou vazio
rescue Whallet::ApiError => e
  # erro da API, falha de rede ou timeout
end
```

| Exceção | Quando acontece |
| - | - |
| `Whallet::ConfigurationError` | Token ausente ou vazio |
| `Whallet::ApiError` | Erro da API, falha de rede ou timeout |
| `Whallet::Webhooks::SignatureError` | Assinatura de webhook ausente, vazia ou inválida |
| `Whallet::Webhooks::PayloadError` | Corpo do webhook malformado ou que não é um objeto JSON |

## Webhooks

A Whallet usa **dois mecanismos** e a [documentação de segurança](https://whallet.mintlify.site/pages/webhooks/security.md) orienta usar os dois:

| Mecanismo | O que garante |
| - | - |
| `webhookSecret` na query | autentica a **origem** |
| Assinatura HMAC no header | integridade do **corpo** |

A chave HMAC é pública e global, publicada na documentação, então a assinatura sozinha não prova origem.

```ruby theme={"theme":{"light":"github-light","dark":"vesper"}}
payload   = request.body.read
signature = request.headers['X-Webhook-Signature']

begin
  # 1. Autentica a origem com o secret definido ao criar o webhook.
  Whallet::Webhooks.verify_secret!(
    received: params[:webhookSecret],
    expected: ENV['WHALLET_WEBHOOK_SECRET']
  )

  # 2. Verifica a integridade do corpo antes de fazer o parse.
  event = Whallet::Webhooks.construct_event(
    payload: payload, signature: signature
  )
rescue Whallet::Webhooks::SignatureError
  return head :unauthorized
rescue Whallet::Webhooks::PayloadError
  return head :bad_request
end

case event.type
when 'checkout.completed'          then handle_payment(event.data)
when 'subscription.payment_failed' then handle_dunning(event.data)
end
```

> [!TIP]
>
> A Whallet reentrega qualquer webhook que não responda 2xx. Guarde o `id` do evento com índice único no banco e responda 200 também para duplicatas, senão a reentrega não para.

> [!WARNING]
>
> Em Rails, leia `request.query_parameters` em vez de `params` antes de validar. Tocar em `params` faz o framework parsear o corpo, e um corpo malformado estoura antes do seu código rodar.

## Boleto

Boleto tem vencimento, juros e multa próprios. Valores em centavos.

```ruby theme={"theme":{"light":"github-light","dark":"vesper"}}
Whallet.checkouts.create(
  Whallet::Resources::Checkouts.new(
    methods: ['BOLETO'],
    due_date: '2026-09-15',
    interest: { value: 100 },
    fine: { value: 200, type: 'PERCENTAGE' },
    products: [
      Whallet::Resources::Billings::Product.new(external_id: 'prod_abc123xyz', quantity: 1)
    ]
  )
)
```

No checkout transparente, o boleto exige nome e CPF/CNPJ do pagador. O SDK valida isso localmente, antes de gastar uma chamada:

```ruby theme={"theme":{"light":"github-light","dark":"vesper"}}
boleto = Whallet.transparents.create(charge, method: 'BOLETO')
boleto.bar_code   # linha digitável
boleto.url        # PDF para impressão
boleto.br_code    # PIX alternativo da mesma cobrança
```

## Paginação

Listas retornam no máximo 100 itens. Para percorrer tudo sem lidar com cursor:

```ruby theme={"theme":{"light":"github-light","dark":"vesper"}}
Whallet.customers.auto_paging_each { |customer| puts customer.name }
```

## Resiliência

O SDK já traz retry com backoff exponencial e jitter em 429 e 5xx. Escritas nunca são repetidas, porque refazer uma criação de cobrança após timeout poderia cobrar o cliente duas vezes.

```ruby theme={"theme":{"light":"github-light","dark":"vesper"}}
Whallet.configure do |config|
  config.api_token   = ENV['WHALLET_API_KEY']
  config.timeout     = 30  # segundos
  config.max_retries = 2   # 0 desliga
  config.logger      = Rails.logger  # opcional, o token é redigido
end
```

## Próximos passos

> [card] [Configurar webhooks](https://whallet.mintlify.site/pages/webhooks.md)
>
> Receba notificações em tempo real sobre pagamentos confirmados.

> [card] [Checkout Transparente](https://whallet.mintlify.site/pages/transparents/create.md)
>
> Aceite PIX e cartão diretamente na sua interface.

> [card] [Criar clientes](https://whallet.mintlify.site/pages/client/create.md)
>
> Gerencie clientes vinculados às cobranças.

> [card] [Referência completa](https://whallet.mintlify.site/pages/reference/introduction.md)
>
> Todos os endpoints, status codes e formato de resposta.


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