SDK TypeScript (@sinnu/sdk)

Client oficial em TypeScript: autenticação por API key, recursos para links e transações, erros normalizados e paginação por async iterator.

O @sinnu/sdk integra a API da Sinnu em aplicações Node.js. Ele expõe helpers para a superfície pública atual: links de pagamento, transações, checkout hospedado e validação de webhooks.

Instalação

Requer Node.js 18 ou superior, porque usa o fetch nativo.

Instalação
npm install @sinnu/sdk
# ou
pnpm add @sinnu/sdk

Inicialização

Crie um client com sua API key. Guarde-a em variável de ambiente e não no código-fonte.

sinnu.ts
import { Sinnu } from "@sinnu/sdk";

export const sinnu = new Sinnu({
  apiKey: process.env.SINNU_API_KEY!,
});

Criar um link de pagamento

Valores vão em centavos. Os métodos aceitos são pix e credit_card.

Criar link
const link = await sinnu.links.create({
  title: "Curso de TypeScript",
  description: "Acesso anual",
  priceMode: "fixed",
  amountCents: 9900,
  methods: ["pix", "credit_card"],
  maxInstallments: 12,
  interestMode: "pass_to_customer",
  threeDsMode: "always",
});

console.log(sinnu.checkout.url(link.slug));

Listar transações

Liste uma página ou itere por todas com listAll, que cuida da paginação automaticamente.

Listar transações
const page = await sinnu.transactions.list({ status: "approved", page: 1 });
console.log(`${page.data.length} de ${page.total} transações`);

for await (const tx of sinnu.transactions.listAll({ status: "approved" })) {
  console.log(tx.id, tx.method, tx.amount);
}

Tratamento de erros

Toda falha vira uma instância de SinnuError ou de uma subclasse específica.

Erros tipados
import {
  SinnuAuthError,
  SinnuNotFoundError,
  SinnuValidationError,
  SinnuError,
} from "@sinnu/sdk";

try {
  await sinnu.links.create({
    title: "Teste",
    priceMode: "fixed",
    amountCents: 500,
    methods: ["pix"],
  });
} catch (err) {
  if (err instanceof SinnuAuthError) {
    console.error("API key inválida");
  } else if (err instanceof SinnuValidationError) {
    console.error("Payload inválido:", err.body?.message);
  } else if (err instanceof SinnuNotFoundError) {
    console.error("Recurso não encontrado");
  } else if (err instanceof SinnuError) {
    console.error(err.statusCode, err.message);
  }
}

Verificar webhooks

O SDK também valida webhooks sem fazer requisições. Use sinnu.webhooks.constructEvent com o corpo bruto, a assinatura do header X-Sinnu-Signature e o segredo de webhook.

Verificar e desserializar um webhook
import { Sinnu, SinnuWebhookSignatureError } from "@sinnu/sdk";

const sinnu = new Sinnu({ apiKey: process.env.SINNU_API_KEY! });

try {
  const event = sinnu.webhooks.constructEvent({
    payload: rawBody,
    signature: req.header("X-Sinnu-Signature"),
    secret: process.env.SINNU_WEBHOOK_SECRET!,
  });

  if (event.type === "transaction.approved") {
    console.log("Pagamento confirmado:", event.data.id);
  }
} catch (err) {
  if (err instanceof SinnuWebhookSignatureError) {
    console.error("assinatura inválida");
  }
}

Acesso de baixo nível

Para usar um endpoint já presente no OpenAPI sem helper dedicado, chame sinnu.http com o helper unwrap.

Client tipado
import { unwrap } from "@sinnu/sdk";

const clientes = await unwrap(
  sinnu.http.GET("/api/customers/", {
    params: { query: { page: 1, pageSize: 20 } },
  }),
);