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

@criapix/saas-assinaturas-client

v2.1.1

Published

SDK JavaScript/TypeScript para o AssinaturasService - Sistema de gestão de assinaturas SaaS com processamento de pagamentos de faturas (cartão, PIX, débito), gerenciamento de métodos de pagamento, pagamentos recorrentes e análise de falhas de pagamento

Readme

AssinaturasService SDK JavaScript/TypeScript

SDK JavaScript/TypeScript para integração com o AssinaturasService - Sistema de gestão de assinaturas SaaS multi-tenant.

📦 Instalação

Via NPM (local link)

npm install @saas-core/assinaturas-client

Via arquivo local

npm install file:../saas-core-assinaturas/AssinaturasService.SDK.JS

🚀 Uso Básico

Criar e Configurar o Cliente

import { AssinaturasServiceClient } from '@saas-core/assinaturas-client';

// Criar instância do cliente
const client = new AssinaturasServiceClient('http://localhost:5001');

// Configurar token de autenticação
client.setAuthorizationToken(jwtToken);

Planos de Assinatura

// Listar planos
const plans = await client.listSubscriptionPlans({
  isActive: true,
  page: 1,
  pageSize: 10
});

// Criar plano
const newPlan = await client.createSubscriptionPlan({
  name: 'Plano Básico',
  description: 'Plano básico para pequenos condomínios',
  pricePerUnit: 7.00,
  features: '["Gestão de unidades", "Cobrança mensal"]',
  isDefault: true,
  isActive: true
});

// Atualizar plano
const updatedPlan = await client.updateSubscriptionPlan(planId, {
  name: 'Plano Básico Atualizado',
  pricePerUnit: 8.00
});

// Deletar plano
await client.deleteSubscriptionPlan(planId);

Assinaturas

import { BillingCycle } from '@saas-core/assinaturas-client';

// Criar assinatura
const subscription = await client.createSubscription({
  customerId: customerId,
  subscriptionPlanId: planId,
  quantity: 15,
  billingCycle: BillingCycle.Monthly,
  startTrial: false,
  defaultInvoiceDueDayOfMonth: 10
});

// Listar assinaturas
const subscriptions = await client.listSubscriptions({
  customerId: customerId,
  page: 1,
  pageSize: 10
});

// Cancelar assinatura
await client.cancelSubscription(subscriptionId, 'Cliente solicitou cancelamento');

Faturas

// Gerar fatura
const invoice = await client.generateInvoice({
  subscriptionId: subscriptionId,
  dueDate: '2024-02-10',
  notes: 'Fatura referente ao mês de Janeiro'
});

// Listar faturas
const invoices = await client.listInvoices({
  subscriptionId: subscriptionId,
  page: 1,
  pageSize: 10
});

// Atualizar status da fatura
import { InvoiceStatus } from '@saas-core/assinaturas-client';

await client.updateInvoiceStatus(invoiceId, {
  status: InvoiceStatus.Paid,
  paidAt: new Date().toISOString(),
  paymentMethod: 'PIX'
});

Processamento de Pagamentos

// Processar primeiro pagamento com cartão
const firstPaymentResult = await client.processFirstPayment(invoiceId, {
  cardToken: 'card_token_from_mercadopago',
  cardHolderName: 'João Silva',
  cardExpiryDate: '11/30', // Suporta MM/YY, MM/YYYY ou ISO 8601
  customer: {
    name: 'João Silva',
    email: '[email protected]',
    documentNumber: '12345678901',
    phone: '11999999999'
  }
});

// Processar pagamento PIX
const pixResult = await client.processPixPayment(invoiceId, {
  customer: {
    name: 'João Silva',
    email: '[email protected]',
    documentNumber: '12345678901'
  }
});

// Processar pagamento com débito
const debitResult = await client.processDebitPayment(invoiceId, {
  cardToken: 'debit_card_token',
  cardHolderName: 'João Silva',
  cardExpiryDate: '05/2032',
  customer: {
    name: 'João Silva',
    email: '[email protected]',
    documentNumber: '12345678901'
  }
});

// Atualizar método de pagamento
const updateResult = await client.updatePaymentMethod(subscriptionId, {
  cardToken: 'new_card_token',
  cardHolderName: 'João Silva',
  cardExpiryDate: '12/35',
  customer: {
    name: 'João Silva',
    email: '[email protected]',
    documentNumber: '12345678901'
  }
});

Análise de Falhas de Pagamento

import {
  PaymentFailureHelper,
  canRetryPayment,
  getSuggestedAction,
  getUserFriendlyReason
} from '@saas-core/assinaturas-client';

// Verificar se um pagamento pode ser tentado novamente
const canRetry = canRetryPayment('insufficient_funds', 'Saldo insuficiente');
// Retorna: true

// Ou usando a classe diretamente
const canRetryAlt = PaymentFailureHelper.canRetryPayment(
  'insufficient_funds',
  'Saldo insuficiente'
);

// Obter ação sugerida para o usuário
const suggestedAction = getSuggestedAction(
  'insufficient_funds',
  'Saldo insuficiente',
  true
);
// Retorna: "Verifique o saldo disponível ou aguarde a próxima tentativa automática"

// Obter mensagem amigável para o usuário
const friendlyMessage = getUserFriendlyReason(
  'expired_card',
  null,
  'Card is expired'
);
// Retorna: "Cartão expirado"

// Exemplo completo com resposta de pagamento falhado
if (paymentResponse.success === false) {
  const canRetry = canRetryPayment(
    paymentResponse.failureCode,
    paymentResponse.failureReason
  );

  const userMessage = getUserFriendlyReason(
    paymentResponse.failureCode,
    paymentResponse.failureReason,
    paymentResponse.errorMessage
  );

  const action = getSuggestedAction(
    paymentResponse.failureCode,
    paymentResponse.failureReason,
    canRetry
  );

  console.log(`Erro: ${userMessage}`);
  console.log(`Ação sugerida: ${action}`);
  console.log(`Pode tentar novamente: ${canRetry ? 'Sim' : 'Não'}`);
}

Validação de Data de Expiração de Cartão

import {
  CardExpiryDateValidator,
  isValidCardExpiryDate,
  parseCardExpiryDate,
  normalizeCardExpiryDate
} from '@saas-core/assinaturas-client';

// Validar formato de data
const validationResult = CardExpiryDateValidator.validate('11/30');
if (validationResult.valid) {
  console.log('Data válida:', validationResult.parsedDate);
} else {
  console.error('Erro:', validationResult.error);
}

// Verificação rápida
const isValid = isValidCardExpiryDate('11/30'); // true

// Converter para Date
const expiryDate = parseCardExpiryDate('11/30');

// Normalizar para ISO 8601 (usado internamente pelo SDK)
const isoDate = normalizeCardExpiryDate('11/30');
// Retorna: "2030-11-30T23:59:59.000Z"

// Formatos suportados:
// - "11/30" (MM/YY)
// - "11/2030" (MM/YYYY)
// - "2030-11-30T00:00:00Z" (ISO 8601)

🔐 Autenticação

O SDK utiliza autenticação JWT via header Authorization: Bearer {token}.

// Configurar token antes de fazer requisições
client.setAuthorizationToken(jwtToken);

O token deve conter as seguintes claims:

  • saasId: Identificador da aplicação SaaS
  • sub ou userId: ID do usuário
  • role: Role do usuário (Admin, User, etc.)

📚 Tipos Disponíveis

Enums

  • SubscriptionStatus: Trial, Active, Suspended, Cancelled, Expired
  • InvoiceStatus: Pending, Paid, Overdue, Cancelled, Refunded
  • BillingCycle: Monthly, Quarterly, Yearly

Interfaces

  • SubscriptionPlanResponse
  • CreateSubscriptionPlanRequest
  • UpdateSubscriptionPlanRequest
  • SubscriptionResponse
  • InvoiceResponse
  • PaginatedResponse<T>

🛠️ Build

npm run build

📄 Licença

Este projeto é privado e proprietário.