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.
Server-side apenas
O SDK usa sua chave secreta sk_live_.... Use-o sempre no backend, nunca no navegador ou em apps cliente.
Instalação
Requer Node.js 18 ou superior, porque usa o fetch nativo.
npm install @sinnu/sdk
# ou
pnpm add @sinnu/sdkInicialização
Crie um client com sua API key. Guarde-a em variável de ambiente e não no código-fonte.
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.
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.
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.
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.
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");
}
}Webhooks
Veja Receber webhooks para a lista de eventos, reentregas e o exemplo sem SDK.
Acesso de baixo nível
Para usar um endpoint já presente no OpenAPI sem helper dedicado, chame sinnu.http com o helper unwrap.
import { unwrap } from "@sinnu/sdk";
const clientes = await unwrap(
sinnu.http.GET("/api/customers/", {
params: { query: { page: 1, pageSize: 20 } },
}),
);Próximos passos
Veja o tutorial Integrar com o SDK para um fluxo completo, ou a referência da API para todos os campos.