# SDKs (/docs/sdks)

The SDKs do for you what every integration must get right:

- **They pick the environment from your key**: `psp_test_…` goes to sandbox, `psp_live_…` to live.
- **They retry without duplicating**: on a network failure, a `429`, a `500` or a `503`, they retry with the **same** `Idempotency-Key`. If you pass none, they generate one per call.
- **They honor `Retry-After`** when the API asks to wait.
- **Typed errors**, with `type`, `code`, `param` and `request_id`.
- **Auto-pagination**: walk a whole list with a `for` loop.
- **Webhook verification**: signature, timestamp and event parsing in one function.
- **Complete types** for every resource, generated from the OpenAPI contract. Every endpoint of the [reference](/api#tag/payouts/POST/v1/payouts) shows its example in all three languages.

## Install [#install]

<Tabs items={["Node.js", "Python", "Go"]}>
<Tab value="Node.js">

```bash
npm install caibopay
```

Node.js 18 or later. No dependencies. ESM and CommonJS, with TypeScript types included.

</Tab>
<Tab value="Python">

```bash
pip install caibopay
```

Python 3.8 or later. Fully typed (`py.typed`).

</Tab>
<Tab value="Go">

```bash
go get go.caibopay.app/caibopay
```

Go 1.23 or later. No dependencies.

</Tab>
</Tabs>

## Your first call [#your-first-call]

<Tabs items={["Node.js", "Python", "Go"]}>
<Tab value="Node.js">

```ts
import { Caibo } from "caibopay";

const caibo = new Caibo(process.env.CAIBO_API_KEY!);

const account = await caibo.account.retrieve();
console.log(account.environment); // "sandbox"
```

</Tab>
<Tab value="Python">

```python
import os
import caibopay

client = caibopay.Client(os.environ["CAIBO_API_KEY"])

account = client.account.retrieve()
print(account["environment"])  # "sandbox"
```

</Tab>
<Tab value="Go">

```go
client, err := caibopay.NewClient(os.Getenv("CAIBO_API_KEY"))
if err != nil {
	log.Fatal(err)
}
account, err := client.Account.Retrieve(context.Background())
if err != nil {
	log.Fatal(err)
}
fmt.Println(account.Environment) // "sandbox"
```

</Tab>
</Tabs>

## Collect an exact amount [#collect-an-exact-amount]

<Tabs items={["Node.js", "Python", "Go"]}>
<Tab value="Node.js">

```ts
const fa = await caibo.fundingAccounts.create(
  { method: "pix", currency: "BRL", amount: "250.00", payer: { "payer.name": "Ana Souza" } },
  { idempotencyKey: "payin-order-8812" },
);
```

</Tab>
<Tab value="Python">

```python
fa = client.funding_accounts.create(
    method="pix",
    currency="BRL",
    amount="250.00",
    payer={"payer.name": "Ana Souza"},
    idempotency_key="payin-order-8812",
)
```

</Tab>
<Tab value="Go">

```go
fa, err := client.FundingAccounts.Create(ctx, &caibopay.FundingAccountCreate{
	Method:   "pix",
	Currency: "BRL",
	Amount:   "250.00",
	Payer:    map[string]string{"payer.name": "Ana Souza"},
}, caibopay.WithIdempotencyKey("payin-order-8812"))
```

</Tab>
</Tabs>

## Pay out [#pay-out]

<Tabs items={["Node.js", "Python", "Go"]}>
<Tab value="Node.js">

```ts
const quote = await caibo.quotes.create(
  { source_currency: "USDT", destination_currency: "PEN", method: "bank_transfer", amount: "350.00", amount_side: "destination" },
  { idempotencyKey: "quote-order-5531" },
);
const payout = await caibo.payouts.create(
  { beneficiary_id: "ben_01m3sgazybenxvqfw0h5bnszk4", quote_id: quote.id },
  { idempotencyKey: "payout-order-5531" },
);
```

</Tab>
<Tab value="Python">

```python
quote = client.quotes.create(
    source_currency="USDT", destination_currency="PEN", method="bank_transfer",
    amount="350.00", amount_side="destination", idempotency_key="quote-order-5531",
)
payout = client.payouts.create(
    beneficiary_id="ben_01m3sgazybenxvqfw0h5bnszk4", quote_id=quote["id"], idempotency_key="payout-order-5531",
)
```

</Tab>
<Tab value="Go">

```go
quote, err := client.Quotes.Create(ctx, &caibopay.QuoteCreate{
	SourceCurrency: "USDT", DestinationCurrency: "PEN", Method: "bank_transfer",
	Amount: "350.00", AmountSide: caibopay.QuoteCreateAmountSideDestination,
}, caibopay.WithIdempotencyKey("quote-order-5531"))
if err != nil {
	return err
}
payout, err := client.Payouts.Create(ctx, &caibopay.PayoutCreate{
	BeneficiaryID: "ben_01m3sgazybenxvqfw0h5bnszk4", QuoteID: quote.ID,
}, caibopay.WithIdempotencyKey("payout-order-5531"))
```

</Tab>
</Tabs>

## Walk a list [#walk-a-list]

<Tabs items={["Node.js", "Python", "Go"]}>
<Tab value="Node.js">

```ts
for await (const payout of caibo.payouts.list({ status: "completed" })) {
  console.log(payout.id, payout.destination.amount);
}
```

</Tab>
<Tab value="Python">

```python
for payout in client.payouts.list(status="completed"):
    print(payout["id"], payout["destination"]["amount"])
```

</Tab>
<Tab value="Go">

```go
for payout, err := range client.Payouts.ListAll(ctx, &caibopay.ListPayoutsParams{Status: "completed"}) {
	if err != nil {
		return err
	}
	fmt.Println(payout.ID, payout.Destination.Amount)
}
```

</Tab>
</Tabs>

## Errors [#errors]

<Tabs items={["Node.js", "Python", "Go"]}>
<Tab value="Node.js">

```ts
import { CaiboError } from "caibopay";

try {
  await caibo.payouts.create({ beneficiary_id: "ben_...", quote_id: "quo_..." });
} catch (err) {
  if (err instanceof CaiboError && err.code === "quote_expired") {
    // get a new quote
  }
  throw err;
}
```

</Tab>
<Tab value="Python">

```python
try:
    client.payouts.create(beneficiary_id="ben_...", quote_id="quo_...")
except caibopay.InvalidRequestError as e:
    if e.code == "quote_expired":
        ...  # get a new quote
    raise
```

</Tab>
<Tab value="Go">

```go
_, err := client.Payouts.Create(ctx, &caibopay.PayoutCreate{BeneficiaryID: "ben_...", QuoteID: "quo_..."})
if caibopay.IsCode(err, "quote_expired") {
	// get a new quote
}
```

</Tab>
</Tabs>

## Webhooks [#webhooks]

<Tabs items={["Node.js", "Python", "Go"]}>
<Tab value="Node.js">

```ts
import express from "express";
import { constructEvent } from "caibopay";

app.post("/webhooks/caibo", express.raw({ type: "application/json" }), (req, res) => {
  try {
    const event = constructEvent(req.body, req.get("Psp-Signature"), process.env.CAIBO_WEBHOOK_SECRET!);
    queue.push(event); // process later; dedupe on event.id
    res.sendStatus(200);
  } catch {
    res.sendStatus(400);
  }
});
```

</Tab>
<Tab value="Python">

```python
@app.post("/webhooks/caibo")
def webhook():
    try:
        event = caibopay.construct_event(request.get_data(), request.headers.get("Psp-Signature"), secret)
    except caibopay.SignatureVerificationError:
        return "", 400
    enqueue(event)  # process later; dedupe on event["id"]
    return "", 200
```

</Tab>
<Tab value="Go">

```go
http.HandleFunc("/webhooks/caibo", func(w http.ResponseWriter, r *http.Request) {
	body, _ := io.ReadAll(r.Body)
	event, err := caibopay.ConstructEvent(body, r.Header.Get(caibopay.SignatureHeader), secret)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	enqueue(event) // process later; dedupe on event.ID
	w.WriteHeader(http.StatusOK)
})
```

</Tab>
</Tabs>

## Options [#options]

| | Node.js | Python | Go |
| --- | --- | --- | --- |
| Retries (2 by default) | `{ maxRetries }` | `max_retries=` | `WithMaxRetries(n)` |
| Timeout per attempt (30 s) | `{ timeout }` | `timeout=` | `WithHTTPClient(...)` |
| Another host | `{ baseUrl }` | `base_url=` | `WithBaseURL(u)` |
| Your Idempotency-Key | `{ idempotencyKey }` | `idempotency_key=` | `WithIdempotencyKey(k)` |
| Your trace id | `{ correlationId }` | `request_options={"correlation_id": …}` | `WithCorrelationID(id)` |

<Callout title="Another language?">
Any language can use the API over HTTP and JSON, or generate its own client from [`/openapi.json`](/openapi.json). Write to us if you need an official SDK for another language.
</Callout>
