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

# Integração por linguagem

> Chame a API Nasten em Node.js, Python, PHP, Go ou Java, sem dependências além do HTTP.

A API Nasten é REST puro: qualquer linguagem com um cliente HTTP integra em minutos. Abaixo, o mesmo fluxo (autenticar e criar um Pix) em cada stack.

> [!NOTE]
>
> SDKs oficiais estão em desenvolvimento. Enquanto isso, os exemplos abaixo usam apenas a biblioteca HTTP padrão de cada linguagem e funcionam hoje.

## Autenticar + criar um Pix

O CPF `01234567890` dos exemplos é fictício. Para testar sem cobrar ninguém, use a chave de Desenvolvimento: veja [Modo de teste](https://nasten.mintlify.site/pages/sandbox.md).

```javascript Node.js theme={null}
const BASE = 'https://api.nasten.net'

async function auth() {
  const basic = Buffer.from(
    `${process.env.NASTEN_PUBLIC_KEY}:${process.env.NASTEN_SECRET_KEY}`
  ).toString('base64')
  const res = await fetch(`${BASE}/auth`, {
    method: 'POST',
    headers: { Authorization: `Basic ${basic}` }
  })
  return (await res.json()).token
}

async function criarPix() {
  const token = await auth()
  const res = await fetch(`${BASE}/v1/pix/in/qrcode`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`
    },
    body: JSON.stringify({
      amountInCents: 5000,
      description: 'Pedido #1042',
      customer: {
        name: 'Ana Souza',
        email: 'ana.souza@exemplo.com.br',
        documentType: 'cpf',
        document: '01234567890'
      }
    })
  })
  const body = await res.json()
  if (!res.ok || !body.success) throw new Error(body.message)
  console.log(body.data.pix.emv)
}

criarPix()
```

```python Python theme={null}
import base64, os, requests

BASE = "https://api.nasten.net"

def auth() -> str:
    basic = base64.b64encode(
        f'{os.environ["NASTEN_PUBLIC_KEY"]}:{os.environ["NASTEN_SECRET_KEY"]}'.encode()
    ).decode()
    res = requests.post(f"{BASE}/auth", headers={"Authorization": f"Basic {basic}"})
    res.raise_for_status()
    return res.json()["token"]

def criar_pix():
    token = auth()
    res = requests.post(
        f"{BASE}/v1/pix/in/qrcode",
        headers={"Authorization": f"Bearer {token}"},
        json={
            "amountInCents": 5000,
            "description": "Pedido #1042",
            "customer": {
                "name": "Ana Souza",
                "email": "ana.souza@exemplo.com.br",
                "documentType": "cpf",
                "document": "01234567890",
            },
        },
    )
    res.raise_for_status()
    print(res.json()["data"]["pix"]["emv"])

criar_pix()
```

```php PHP theme={null}
<?php
const BASE = 'https://api.nasten.net';

function nastenAuth(): string {
    $basic = base64_encode(getenv('NASTEN_PUBLIC_KEY') . ':' . getenv('NASTEN_SECRET_KEY'));
    $ch = curl_init(BASE . '/auth');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => ["Authorization: Basic $basic"],
    ]);
    $data = json_decode(curl_exec($ch), true);
    curl_close($ch);
    return $data['token'];
}

$token = nastenAuth();
$ch = curl_init(BASE . '/v1/pix/in/qrcode');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        "Authorization: Bearer $token",
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'amountInCents' => 5000,
        'description' => 'Pedido #1042',
        'customer' => [
            'name' => 'Ana Souza',
            'email' => 'ana.souza@exemplo.com.br',
            'documentType' => 'cpf',
            'document' => '01234567890',
        ],
    ]),
]);
$res = json_decode(curl_exec($ch), true);
echo $res['data']['pix']['emv'];
```

```go Go theme={null}
package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

const base = "https://api.nasten.net"

func auth() (string, error) {
	basic := base64.StdEncoding.EncodeToString(
		[]byte(os.Getenv("NASTEN_PUBLIC_KEY") + ":" + os.Getenv("NASTEN_SECRET_KEY")))
	req, _ := http.NewRequest("POST", base+"/auth", nil)
	req.Header.Set("Authorization", "Basic "+basic)
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return "", err
	}
	defer res.Body.Close()
	var out struct{ Token string `json:"token"` }
	json.NewDecoder(res.Body).Decode(&out)
	return out.Token, nil
}

func main() {
	token, _ := auth()
	body, _ := json.Marshal(map[string]any{
		"amountInCents": 5000,
		"description":   "Pedido #1042",
		"customer": map[string]string{
			"name": "Ana Souza", "email": "ana.souza@exemplo.com.br",
			"documentType": "cpf", "document": "01234567890",
		},
	})
	req, _ := http.NewRequest("POST", base+"/v1/pix/in/qrcode", bytes.NewReader(body))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+token)
	res, _ := http.DefaultClient.Do(req)
	defer res.Body.Close()
	var out map[string]any
	json.NewDecoder(res.Body).Decode(&out)
	fmt.Println(out)
}
```

```java Java theme={null}
import java.net.URI;
import java.net.http.*;
import java.util.Base64;

public class NastenPix {
    static final String BASE = "https://api.nasten.net";
    static final HttpClient http = HttpClient.newHttpClient();

    static String auth() throws Exception {
        String basic = Base64.getEncoder().encodeToString(
            (System.getenv("NASTEN_PUBLIC_KEY") + ":" + System.getenv("NASTEN_SECRET_KEY")).getBytes());
        var req = HttpRequest.newBuilder(URI.create(BASE + "/auth"))
            .header("Authorization", "Basic " + basic)
            .POST(HttpRequest.BodyPublishers.noBody()).build();
        String body = http.send(req, HttpResponse.BodyHandlers.ofString()).body();
        return body.replaceAll(".*\"token\":\"([^\"]+)\".*", "$1");
    }

    public static void main(String[] args) throws Exception {
        String token = auth();
        String json = """
            {"amountInCents":5000,"description":"Pedido #1042",
             "customer":{"name":"Ana Souza","email":"ana.souza@exemplo.com.br",
                         "documentType":"cpf","document":"01234567890"}}""";
        var req = HttpRequest.newBuilder(URI.create(BASE + "/v1/pix/in/qrcode"))
            .header("Content-Type", "application/json")
            .header("Authorization", "Bearer " + token)
            .POST(HttpRequest.BodyPublishers.ofString(json)).build();
        System.out.println(http.send(req, HttpResponse.BodyHandlers.ofString()).body());
    }
}
```

## Boas práticas em qualquer stack

* **Cacheie o token** (10 min de validade): [exemplos prontos](https://nasten.mintlify.site/pages/auth/generate-token.md#renovacao-automatica)
* **Trate erros pelo envelope** `{ success, message, code }`: [guia de erros](https://nasten.mintlify.site/pages/reference/errors.md)
* **Idempotência no saque** com `x-idempotency-key`: [Pix Out](https://nasten.mintlify.site/pages/pix-out/overview.md)
* **Confira `success`** antes de ler `data`: a criação de Pix pode responder `200` com `success: false` e `message: "Erro ao criar transação"`
* **Webhooks** para status em tempo real: [guia](https://nasten.mintlify.site/pages/webhook/overview.md)

## Teste direto no navegador

Na **Referência da API** desta documentação você encontra o playground interativo: preencha o token, edite o corpo e dispare a requisição sem sair da página. As chamadas do playground são reais: use um token da chave de Desenvolvimento para testar cobranças.


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