npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@rodrigogs/asaas-sdk

v0.1.1

Published

[![CI](https://github.com/rodrigogs/asaas-sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/rodrigogs/asaas-sdk/actions/workflows/ci.yml) [![npm version](https://img.shields.io/npm/v/%40rodrigogs%2Fasaas-sdk)](https://www.npmjs.com/package/@rodr

Readme

@rodrigogs/asaas-sdk

CI npm version npm downloads License Coverage Node.js TypeScript ESM only Zero runtime deps

SDK TypeScript para a API da plataforma de pagamentos Asaas.

English version

Funcionalidades

  • Zero dependências de runtime
  • Suporte completo a TypeScript com tipagem forte
  • ESM-only, compatível com projetos modernos
  • Paginação automática com AsyncIterable
  • Tratamento robusto de erros com classes especializadas
  • Ambientes SANDBOX e PRODUCTION
  • Timeout configurável (padrão: 30 segundos)
  • Lazy-loading de serviços para melhor performance
  • Suporte nativo a Node.js >= 20 (fetch, AbortSignal, FormData)

Instalação

Pacote no npm: @rodrigogs/asaas-sdk

npm install @rodrigogs/asaas-sdk
yarn add @rodrigogs/asaas-sdk
pnpm add @rodrigogs/asaas-sdk

Início Rápido

import { AsaasClient } from '@rodrigogs/asaas-sdk'

// Criar cliente (ambiente SANDBOX para testes)
const client = new AsaasClient({
  accessToken: 'seu_access_token_aqui',
  environment: 'SANDBOX',
})

// Criar um cliente
const customer = await client.customers.create({
  name: 'João Silva',
  cpfCnpj: '12345678901',
  email: '[email protected]',
  phone: '11987654321',
})

// Criar uma cobrança
const payment = await client.payments.create({
  customer: customer.id,
  billingType: 'BOLETO',
  value: 150.00,
  dueDate: '2026-03-20',
  description: 'Serviço de manutenção',
})

console.log('Cobrança criada:', payment.id)
console.log('Link do boleto:', payment.bankSlipUrl)

Configuração

Opções do Cliente

const client = new AsaasClient({
  // Obrigatório: Token de acesso da API
  accessToken: process.env.ASAAS_ACCESS_TOKEN,

  // Opcional: Ambiente (padrão: 'PRODUCTION')
  environment: 'SANDBOX', // ou 'PRODUCTION'

  // Opcional: URL base customizada
  baseUrl: 'https://api-sandbox.asaas.com/v3',

  // Opcional: Timeout em milissegundos (padrão: 30000)
  timeout: 60000,

  // Opcional: Implementação customizada de fetch
  fetch: customFetch,

  // Opcional: User-Agent customizado
  userAgent: 'MeuApp/1.0',
})

Variáveis de Ambiente

# .env
ASAAS_ACCESS_TOKEN=seu_token_aqui
ASAAS_ENVIRONMENT=SANDBOX
const client = new AsaasClient({
  accessToken: process.env.ASAAS_ACCESS_TOKEN!,
  environment: process.env.ASAAS_ENVIRONMENT as 'SANDBOX' | 'PRODUCTION',
})

Visão Geral dos Serviços

| Serviço | Descrição | Exemplo | |---------|-----------|---------| | customers | Gerenciamento de clientes (CRUD, restauração, notificações) | client.customers.create(...) | | payments | Criação de cobranças, consultas, estornos, confirmações | client.payments.create(...) | | cards | Tokenização e pagamento com cartão de crédito | client.cards.tokenize(...) | | installments | Parcelamentos e carnês | client.installments.create(...) | | chargebacks | Listagem e disputa de chargebacks | client.chargebacks.list() | | paymentDocuments | Upload e gerenciamento de documentos de cobrança | client.paymentDocuments.upload(...) | | pix | Serviços Pix (chaves, QR codes, transações) | client.pix.qrCodes.create(...) | | subscriptions | Assinaturas recorrentes | client.subscriptions.create(...) | | transfers | Transferências bancárias e para contas Asaas | client.transfers.create(...) | | subaccounts | Gerenciamento de subcontas | client.subaccounts.create(...) | | myAccount | Informações e webhooks da conta atual | client.myAccount.getCommercialInfo() | | notifications | Notificações de clientes | client.notifications.list(...) | | paymentLinks | Links de pagamento | client.paymentLinks.create(...) | | checkouts | Checkouts personalizados | client.checkouts.create(...) | | checkoutConfig | Configuração de checkout | client.checkoutConfig.update(...) | | splits | Consultas de split de pagamento | client.splits.listReceived() | | anticipations | Solicitação e simulação de antecipações | client.anticipations.create(...) | | anticipationConfig | Configuração de antecipação automática | client.anticipationConfig.update(...) | | bill | Pagamento de contas | client.bill.create(...) | | escrow | Configuração de conta escrow | client.escrow.getConfig() | | fiscalInfo | Informações fiscais e tributárias | client.fiscalInfo.getMunicipalServices() | | invoices | Emissão de notas fiscais | client.invoices.schedule(...) |

Tratamento de Erros

import { AsaasApiError, AsaasTimeoutError, AsaasConnectionError } from '@rodrigogs/asaas-sdk'

try {
  const payment = await client.payments.create({
    customer: 'cus_000000000000',
    billingType: 'PIX',
    value: 100.00,
    dueDate: '2026-03-20',
  })
} catch (error) {
  if (error instanceof AsaasApiError) {
    console.error('Erro da API:', error.message)
    console.error('Status:', error.status)
    console.error('Detalhes:', error.issues)

    // Verificações de tipo específicas
    if (error.isAuth) {
      console.error('Erro de autenticação - verifique seu token')
    } else if (error.isRateLimit) {
      console.error('Limite de taxa excedido - aguarde antes de tentar novamente')
    } else if (error.isRetryable) {
      console.error('Erro recuperável - considere tentar novamente')
    }
  } else if (error instanceof AsaasTimeoutError) {
    console.error(`Timeout após ${error.timeoutMs}ms`)
  } else if (error instanceof AsaasConnectionError) {
    console.error('Erro de conexão:', error.message)
  }
}

Paginação

Todos os métodos .list() retornam um PaginatedList<T> que é iterável e suporta auto-paginação.

Iteração Automática

// Iterar sobre todas as páginas automaticamente
const customers = await client.customers.list({ limit: 100 })
for await (const customer of customers) {
  console.log(customer.name, customer.email)
}

Conversão para Array

// Buscar até 500 registros e converter para array
const result = await client.customers.list()
const allCustomers = await result.toArray({ limit: 500 })

console.log(`Total de clientes: ${allCustomers.length}`)

Acesso Manual

const result = await client.customers.list({ limit: 10, offset: 0 })

console.log('Registros:', result.data)
console.log('Tem mais?', result.hasMore)
console.log('Total:', result.totalCount)

Verificação de Webhooks

A Asaas envia um header customizado para autenticar webhooks:

import { ASAAS_WEBHOOK_AUTH_HEADER } from '@rodrigogs/asaas-sdk'

// Express.js exemplo
app.post('/webhook/asaas', (req, res) => {
  const receivedToken = req.headers[ASAAS_WEBHOOK_AUTH_HEADER]
  const expectedToken = process.env.ASAAS_ACCESS_TOKEN

  if (receivedToken !== expectedToken) {
    return res.status(401).json({ error: 'Unauthorized' })
  }

  // Processar webhook
  const event = req.body
  console.log('Evento recebido:', event.event)

  res.json({ received: true })
})

Exemplos Adicionais

Criar Cobrança Pix

const pixPayment = await client.payments.create({
  customer: 'cus_000000000000',
  billingType: 'PIX',
  value: 250.50,
  dueDate: '2026-03-15',
  description: 'Pagamento via Pix',
})

console.log('QR Code:', pixPayment.pixTransaction?.qrCode)
console.log('Copia e Cola:', pixPayment.pixTransaction?.payload)

Criar Assinatura Recorrente

const subscription = await client.subscriptions.create({
  customer: 'cus_000000000000',
  billingType: 'CREDIT_CARD',
  value: 99.90,
  nextDueDate: '2026-04-01',
  cycle: 'MONTHLY',
  description: 'Assinatura Premium',
})

console.log('Assinatura criada:', subscription.id)
console.log('Status:', subscription.status)

Tokenizar e Pagar com Cartão

// 1. Tokenizar cartão
const token = await client.cards.tokenize({
  customer: 'cus_000000000000',
  creditCard: {
    holderName: 'João Silva',
    number: '5162306219378829',
    expiryMonth: '12',
    expiryYear: '2028',
    ccv: '123',
  },
  creditCardHolderInfo: {
    name: 'João Silva',
    cpfCnpj: '12345678901',
    postalCode: '01310-100',
    addressNumber: '123',
    phone: '11987654321',
  },
})

// 2. Criar cobrança com token
const payment = await client.payments.create({
  customer: 'cus_000000000000',
  billingType: 'CREDIT_CARD',
  value: 150.00,
  dueDate: '2026-03-20',
  creditCard: {
    creditCardToken: token.creditCardToken,
  },
  creditCardHolderInfo: token.creditCardHolderInfo,
})

Transferência para Conta Bancária

const transfer = await client.transfers.create({
  value: 500.00,
  bankAccount: {
    bank: {
      code: '341', // Itaú
    },
    accountName: 'Maria Santos',
    ownerName: 'Maria Santos',
    cpfCnpj: '98765432100',
    agency: '1234',
    account: '56789',
    accountDigit: '0',
  },
})

console.log('Transferência criada:', transfer.id)
console.log('Status:', transfer.status)

Documentação

Guias

Serviços

Requisitos

  • Node.js >= 18.0.0
  • TypeScript >= 5.0 (recomendado para projetos TypeScript)

O SDK utiliza APIs nativas do Node.js 18+:

  • fetch global
  • AbortSignal.timeout()
  • FormData e Blob nativos

Contribuindo

Contribuições são bem-vindas! Por favor, abra uma issue ou pull request no repositório.

Licença

Apache License 2.0


Desenvolvido com TypeScript para a comunidade brasileira de desenvolvedores.