Skip to content

@qazuor/qzpay-core

@qazuor/qzpay-core

Required

The core package provides the foundational types, services, and utilities for QZPay.

Installation

Terminal window
pnpm add @qazuor/qzpay-core

Creating a Billing Instance

Use the createQZPayBilling factory function to create your billing instance:

import { createQZPayBilling } from '@qazuor/qzpay-core';
import { createQZPayStripeAdapter } from '@qazuor/qzpay-stripe';
import { createQZPayDrizzleAdapter } from '@qazuor/qzpay-drizzle';
const billing = createQZPayBilling({
storage: createQZPayDrizzleAdapter(db),
paymentAdapter: createQZPayStripeAdapter({
secretKey: process.env.STRIPE_SECRET_KEY!
}),
defaultCurrency: 'usd',
livemode: process.env.NODE_ENV === 'production'
});
// Access services through the billing instance
billing.customers // QZPayCustomerService
billing.subscriptions // QZPaySubscriptionService
billing.payments // QZPayPaymentService
billing.invoices // QZPayInvoiceService
billing.plans // QZPayPlanService
billing.promoCodes // QZPayPromoCodeService
billing.entitlements // QZPayEntitlementService
billing.limits // QZPayLimitService
billing.metrics // QZPayMetricsService
billing.addons // QZPayAddOnService

Configuration Options

OptionTypeRequiredDescription
storageQZPayStorageAdapterYesStorage adapter (e.g., Drizzle)
paymentAdapterQZPayPaymentAdapterNoPayment provider adapter
plansQZPayPlan[]NoPre-configured plans
defaultCurrencystringNoDefault currency code
livemodebooleanNoProduction mode flag
gracePeriodDaysnumberNoDays before hard cancellation
retryConfigobjectNoPayment retry configuration
loggerQZPayLoggerNoCustom logger

Services

Customer Service

// Create a customer
const customer = await billing.customers.create({
email: 'user@example.com',
name: 'John Doe',
metadata: { userId: 'usr_123' }
});
// Get customer by ID
const customer = await billing.customers.get(id);
// Get customer by external ID
const customer = await billing.customers.getByExternalId(externalId);
// Update customer
const updated = await billing.customers.update(id, { name: 'Jane Doe' });
// Delete customer
await billing.customers.delete(id);
// List customers with pagination
const result = await billing.customers.list({ limit: 10, offset: 0 });

Subscription Service

// Create subscription
const subscription = await billing.subscriptions.create({
customerId: customer.id,
planId: 'plan_pro'
});
// Get subscription (returns QZPaySubscriptionWithHelpers)
const sub = await billing.subscriptions.get(id);
// Subscription helper methods
sub.isActive() // Check if active
sub.isTrial() // Check if in trial
sub.isPastDue() // Check if past due
sub.isCanceled() // Check if canceled
sub.isPaused() // Check if paused
sub.willCancel() // Check if will cancel at period end
sub.hasAccess() // Check if grants access
// Lifecycle operations
await billing.subscriptions.pause(id);
await billing.subscriptions.resume(id);
await billing.subscriptions.cancel(id, { atPeriodEnd: true });
// Change plan
await billing.subscriptions.changePlan(id, {
newPlanId: 'plan_enterprise',
proration: 'create_prorations'
});

Payment Service

// Process a payment
const payment = await billing.payments.process({
customerId: customer.id,
amount: 9900, // in cents
currency: 'usd',
paymentMethodId: 'pm_xxx'
});
// Get payment
const payment = await billing.payments.get(paymentId);
// Get payments by customer
const payments = await billing.payments.getByCustomerId(customerId);
// Refund payment
const refunded = await billing.payments.refund({
paymentId,
amount: 5000, // partial refund
reason: 'customer_request'
});

Invoice Service

// Create invoice
const invoice = await billing.invoices.create({
customerId: customer.id,
lines: [
{ description: 'Pro Plan', amount: 9900, currency: 'usd' }
]
});
// Get invoice
const invoice = await billing.invoices.get(invoiceId);
// Mark invoice as paid
await billing.invoices.markPaid(invoiceId, paymentId);
// Void invoice
await billing.invoices.void(invoiceId);

Entitlement Service

// Check if customer has entitlement
const hasAccess = await billing.entitlements.check(customerId, 'advanced_analytics');
// Get all customer entitlements
const entitlements = await billing.entitlements.getByCustomerId(customerId);
// Grant entitlement
await billing.entitlements.grant({ customerId, entitlementKey: 'premium_support', source: 'manual' });
// Revoke entitlement
await billing.entitlements.revoke(customerId, 'premium_support');

Limit Service

// Check usage limit
const result = await billing.limits.check(customerId, 'api_calls');
// Returns: { allowed: boolean, currentValue: number, maxValue: number, remaining: number }
// Get all customer limits
const limits = await billing.limits.getByCustomerId(customerId);
// Increment usage
await billing.limits.increment(customerId, 'api_calls', 1);
// Set limit
await billing.limits.set({ customerId, limitKey: 'api_calls', maxValue: 10000 });
// Record usage
await billing.limits.recordUsage(customerId, 'api_calls', 100, 'increment');

Metrics Service

// Get MRR (Monthly Recurring Revenue)
const mrr = await billing.metrics.getMrr();
// Get subscription metrics
const subMetrics = await billing.metrics.getSubscriptionMetrics();
// Get revenue metrics
const revenue = await billing.metrics.getRevenueMetrics({
startDate: new Date('2024-01-01'),
endDate: new Date('2024-12-31')
});
// Get churn metrics
const churn = await billing.metrics.getChurnMetrics({
startDate: new Date('2024-01-01'),
endDate: new Date('2024-12-31')
});
// Get full dashboard
const dashboard = await billing.metrics.getDashboard();

Event System

Subscribe to billing events:

// Subscribe to events
billing.on('customer.created', async (event) => {
console.log('New customer:', event.data.id);
});
billing.on('subscription.created', async (event) => {
console.log('New subscription:', event.data.id);
});
billing.on('subscription.canceled', async (event) => {
// Handle cancellation
});
billing.on('payment.succeeded', async (event) => {
// Send receipt
});
billing.on('payment.failed', async (event) => {
// Notify customer
});
// One-time listener
billing.once('invoice.paid', async (event) => {
// Handle first invoice
});
// Unsubscribe
const unsubscribe = billing.on('customer.updated', handler);
unsubscribe(); // Remove listener

Available Events

EventDescription
customer.createdCustomer was created
customer.updatedCustomer was updated
customer.deletedCustomer was deleted
subscription.createdSubscription was created
subscription.updatedSubscription was updated
subscription.canceledSubscription was canceled
subscription.pausedSubscription was paused
subscription.resumedSubscription was resumed
subscription.trial_endingTrial is ending soon
subscription.trial_endedTrial has ended
payment.succeededPayment was successful
payment.failedPayment failed
payment.refundedPayment was refunded
payment.disputedPayment was disputed
invoice.createdInvoice was created
invoice.paidInvoice was paid
invoice.payment_failedInvoice payment failed
invoice.voidedInvoice was voided
addon.createdAdd-on was created
addon.updatedAdd-on was updated
addon.deletedAdd-on was deleted

Types

import type {
QZPayCustomer,
QZPaySubscription,
QZPaySubscriptionWithHelpers,
QZPayPayment,
QZPayInvoice,
QZPayPlan,
QZPayPrice,
QZPayEntitlement,
QZPayCustomerEntitlement,
QZPayLimit,
QZPayCustomerLimit,
QZPayAddOn,
QZPayPromoCode,
QZPayVendor,
QZPayMetrics
} from '@qazuor/qzpay-core';

Constants

import {
QZPaySubscriptionStatus, // active, paused, canceled, past_due, trial, pending
QZPayPaymentStatus, // pending, succeeded, failed, refunded, disputed, canceled
QZPayInvoiceStatus, // draft, open, paid, void, uncollectible
QZPayBillingInterval, // daily, weekly, monthly, quarterly, yearly, custom
QZPayCurrency, // USD, EUR, GBP, MXN, etc.
QZPayPaymentProvider, // stripe, mercadopago
QZPayBillingEvent // All event type constants
} from '@qazuor/qzpay-core';

Utilities

import {
// Date utilities
qzpayFormatDate,
qzpayAddInterval,
// Money utilities
qzpayFormatMoney,
// Hash utilities
qzpayGenerateId,
// Validation utilities
qzpayIsValidEmail
} from '@qazuor/qzpay-core';

Adapters Interface

If you need to create custom adapters:

import type {
QZPayStorageAdapter,
QZPayPaymentAdapter,
QZPayEmailAdapter
} from '@qazuor/qzpay-core';