# Criar um checkout

Gere uma página de pagamento alojada para uma encomenda.

POST`/checkout/create.php`

Terminal
```
curl "https://circus-pay.com/api/checkout/create.php" \
  -H "Authorization: Bearer $CIRCUSPAY_SECRET_KEY" \
  -H "Content-Type: application/json" \
  --data '{
  "amount": 2499,
  "currency": "EUR",
  "productName": "Ma commande",
  "orderId": "ORDER-DEMO-001",
  "successUrl": "https://example.com/payment/return",
  "cancelUrl": "https://example.com/payment/cancel"
}'
```

JavaScript
```
const response = await fetch("https://circus-pay.com/api/checkout/create.php", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.CIRCUSPAY_SECRET_KEY}`,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
  "amount": 2499,
  "currency": "EUR",
  "productName": "Ma commande",
  "orderId": "ORDER-DEMO-001",
  "successUrl": "https://example.com/payment/return",
  "cancelUrl": "https://example.com/payment/cancel"
})
});
const result = await response.json();
if (!response.ok || !result.success) {
  throw new Error(result.error || "API request failed");
}
console.log(result);
```

PHP
```
<?php
$ch = curl_init("https://circus-pay.com/api/checkout/create.php");
curl_setopt_array($ch, [
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 20,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer " . getenv("CIRCUSPAY_SECRET_KEY"),
    "Content-Type: application/json",
  ],
  CURLOPT_POST => true,
  CURLOPT_POSTFIELDS => '{
  "amount": 2499,
  "currency": "EUR",
  "productName": "Ma commande",
  "orderId": "ORDER-DEMO-001",
  "successUrl": "https://example.com/payment/return",
  "cancelUrl": "https://example.com/payment/cancel"
}',
]);
$raw = curl_exec($ch);
if ($raw === false) { throw new RuntimeException(curl_error($ch)); }
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$result = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
if ($status >= 400 || empty($result["success"])) {
  throw new RuntimeException($result["error"] ?? "API request failed");
}
```

Python
```
import os, requests

response = requests.post(
    "https://circus-pay.com/api/checkout/create.php",
    headers={"Authorization": "Bearer " + os.environ["CIRCUSPAY_SECRET_KEY"]},
    json={'amount': 2499, 'currency': 'EUR', 'productName': 'Ma commande', 'orderId': 'ORDER-DEMO-001', 'successUrl': 'https://example.com/payment/return', 'cancelUrl': 'https://example.com/payment/cancel'},
    timeout=20,
)
response.raise_for_status()
result = response.json()
if not result.get("success"):
    raise RuntimeError(result.get("error", "API request failed"))
print(result)
```

## Parâmetros

| Parâmetro | Descrição | 
| --- | --- |

| `amount · integer · obrigatório` | Montante positivo em unidades menores. Exemplo: `15000` para 150 PLN. | 
| `currency · string` | Moeda, `EUR` por predefinição. Disponibilidade segundo a conta e o processamento configurado. | 
| `orderId · string` | A referência da encomenda. Reutilizá-la pode devolver o link existente; não a use numa nova encomenda. | 
| `productName · string` | Texto apresentado ao cliente. | 
| `customerEmail / customerName` | Dados opcionais para preencher previamente o checkout. | 
| `paymentMethods · string[]` | Restringe os métodos apresentados. Não ativa métodos indisponíveis para a conta. | 
| `theme_id · string` | Identificador de um tema ativo da sua conta. Consulte Checkout Studio. | 
| `successUrl / cancelUrl` | Endereços de retorno à loja. O pagamento é confirmado no servidor. | 
| `testMode · boolean` | Ativa o fluxo de teste. Uma chave de teste também impõe este modo. | 

## Resposta

Excerto ilustrativo · domínio fictício
```
{
  "success": true,
  "token": "pay_EXAMPLE",
  "url": "https://checkout.example.com/checkout/pay_EXAMPLE",
  "orderId": "ORDER-DEMO-001",
  "test": false,
  "mode": "live"
}
```

A resposta também pode incluir `fallbackUrl`, `routing`, `ghostSite` e `theme_id`. Use `url` como destino e conserve a referência da encomenda.

## Repetir sem duplicar

Para um link não reutilizável e uma referência existente, a API pode devolver `reused: true` e `alreadyPaid`. Verifique estes campos e o estado antes de reiniciar o pagamento. Não é uma garantia geral de idempotência para todos os endpoints.
