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

quantictech-subscription-components

v2.1.0

Published

Biblioteca de componentes reutilizáveis para sistema de assinatura com Stripe - Arquitetura Service-to-Service

Downloads

15

Readme

@quantictech/subscription-components

Biblioteca de componentes React reutilizáveis para sistema de assinatura com Stripe usando arquitetura service-to-service centralizada.

🏗️ Nova Arquitetura (v2.0.0)

Esta versão implementa uma arquitetura centralizada onde:

  • Frontend usa a lib para comunicar com o backend da aplicação
  • Backend da aplicação faz service-to-service com backend central de pagamentos
  • Backend central gerencia toda comunicação com Stripe
  • Webhooks são centralizados e roteados para as aplicações
Frontend → Lib NPM → Backend App → Backend Central → Stripe
                                       ↓
                               Webhook Central
                                       ↓
                          Notifica Backends Apps

📦 Instalação

npm install @quantictech/subscription-components

🛠 Configuração

1. No Frontend (React/Next.js)

import { 
  SubscriptionProvider, 
  SubscriptionSummary,
  SubscriptionButton,
  PaymentApiClient 
} from '@quantictech/subscription-components';

// Configurar cliente da API
const paymentClient = new PaymentApiClient({
  baseURL: process.env.NEXT_PUBLIC_API_URL!, // Backend da sua aplicação
  applicationId: 'flashcards', // ID da sua aplicação
  getAuthToken: () => localStorage.getItem('token')
});

function App() {
  return (
    <SubscriptionProvider 
      apiClient={paymentClient}
      stripePublicKey={process.env.NEXT_PUBLIC_STRIPE_KEY!}
    >
      <SubscriptionSummary />
      <SubscriptionButton planId="plan_123" />
    </SubscriptionProvider>
  );
}

2. No Backend da Aplicação (NestJS)

Implemente os endpoints que fazem service-to-service com o backend central:

// payments.controller.ts
@Controller('payments')
export class PaymentsController {
  @Post('create-subscription')
  async createSubscription(@Body() data, @Req() req) {
    const user = req.user; // Já autenticado
    
    // Chamar backend central via service-to-service
    return this.paymentService.createSubscriptionInCentralBackend({
      ...data,
      externalUserId: user.id,
      userEmail: user.email,
      applicationId: 'flashcards'
    });
  }

  @Get('my-subscription')
  async getMySubscription(@Req() req) {
    return this.paymentService.getSubscriptionFromCentralBackend(req.user.id);
  }
}

3. Backend Central de Pagamentos

O backend central (be-saas-payments-v1-nestjs) gerencia:

  • Toda comunicação com Stripe
  • Webhook único do Stripe
  • Notificações para backends das aplicações

📋 Componentes Disponíveis

<SubscriptionSummary />

Exibe resumo da assinatura atual com opções de cancelar/reativar:

<SubscriptionSummary 
  onCancel={(reason) => console.log('Cancelado:', reason)}
  onReactivate={() => console.log('Reativado')}
/>

<SubscriptionButton />

Botão para iniciar nova assinatura:

<SubscriptionButton 
  planId="plan_123"
  buttonText="Assinar Premium"
  onSuccess={(subscription) => console.log('Sucesso!', subscription)}
/>

<StripePaymentElement />

Formulário de pagamento com Stripe Elements:

<StripePaymentElement 
  clientSecret={clientSecret}
  onSuccess={() => console.log('Pagamento confirmado')}
/>

🔧 Hooks Disponíveis

useSubscription()

Hook para gerenciar estado da assinatura:

const {
  subscription,
  loading,
  createSubscription,
  cancelSubscription,
  reactivateSubscription
} = useSubscription();

usePayment()

Hook para gerenciar pagamentos:

const {
  paymentHistory,
  loading,
  createPaymentIntent
} = usePayment();

🎯 Configuração de Ambiente

Frontend (.env.local)

NEXT_PUBLIC_API_URL=https://flashcards-backend.com
NEXT_PUBLIC_STRIPE_KEY=pk_live_...

Backend da Aplicação (.env)

APPLICATION_ID=flashcards
CENTRAL_PAYMENTS_BACKEND_URL=https://be-saas-payments.quantictech.com
SERVICE_JWT_SECRET=seu-secret-compartilhado

Backend Central (.env)

STRIPE_SECRET_KEY=sk_live_...
STRIPE_WEBHOOK_SECRET=whsec_...
FLASHCARDS_BACKEND_URL=https://flashcards-backend.com
CURRICULUM_BACKEND_URL=https://curriculumai-backend.com

🚀 Vantagens da Nova Arquitetura

  • Centralização: Toda lógica Stripe em um lugar
  • Escalabilidade: Novos produtos = minutos de setup
  • Segurança: Service-to-service com JWT
  • Manutenção: Updates centralizados
  • Compliance: Webhooks únicos e seguros

📚 Documentação Completa

Para templates de implementação e guia detalhado, consulte:

  • PUBLISH.md - Guia de publicação e integração
  • SECURITY.md - Análise de segurança
  • /architecture-templates/ - Templates para backends

🆕 Migração da v1.x

A v2.0.0 introduz breaking changes devido à nova arquitetura:

  1. Remover webhooks individuais das aplicações
  2. Implementar service-to-service nos backends
  3. Configurar backend central de pagamentos
  4. Atualizar configuração da lib no frontend

📄 Licença

MIT © QuanticTech