@qazuor/qzpay-core
@qazuor/qzpay-core
Required View on npm @qazuor/qzpay-core
The core package provides the foundational types, services, and utilities for QZPay.
Installation
pnpm add @qazuor/qzpay-coreCreating 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 instancebilling.customers // QZPayCustomerServicebilling.subscriptions // QZPaySubscriptionServicebilling.payments // QZPayPaymentServicebilling.invoices // QZPayInvoiceServicebilling.plans // QZPayPlanServicebilling.promoCodes // QZPayPromoCodeServicebilling.entitlements // QZPayEntitlementServicebilling.limits // QZPayLimitServicebilling.metrics // QZPayMetricsServicebilling.addons // QZPayAddOnServiceConfiguration Options
| Option | Type | Required | Description |
|---|---|---|---|
storage | QZPayStorageAdapter | Yes | Storage adapter (e.g., Drizzle) |
paymentAdapter | QZPayPaymentAdapter | No | Payment provider adapter |
plans | QZPayPlan[] | No | Pre-configured plans |
defaultCurrency | string | No | Default currency code |
livemode | boolean | No | Production mode flag |
gracePeriodDays | number | No | Days before hard cancellation |
retryConfig | object | No | Payment retry configuration |
logger | QZPayLogger | No | Custom logger |
Services
Customer Service
// Create a customerconst customer = await billing.customers.create({ email: 'user@example.com', name: 'John Doe', metadata: { userId: 'usr_123' }});
// Get customer by IDconst customer = await billing.customers.get(id);
// Get customer by external IDconst customer = await billing.customers.getByExternalId(externalId);
// Update customerconst updated = await billing.customers.update(id, { name: 'Jane Doe' });
// Delete customerawait billing.customers.delete(id);
// List customers with paginationconst result = await billing.customers.list({ limit: 10, offset: 0 });Subscription Service
// Create subscriptionconst subscription = await billing.subscriptions.create({ customerId: customer.id, planId: 'plan_pro'});
// Get subscription (returns QZPaySubscriptionWithHelpers)const sub = await billing.subscriptions.get(id);
// Subscription helper methodssub.isActive() // Check if activesub.isTrial() // Check if in trialsub.isPastDue() // Check if past duesub.isCanceled() // Check if canceledsub.isPaused() // Check if pausedsub.willCancel() // Check if will cancel at period endsub.hasAccess() // Check if grants access
// Lifecycle operationsawait billing.subscriptions.pause(id);await billing.subscriptions.resume(id);await billing.subscriptions.cancel(id, { atPeriodEnd: true });
// Change planawait billing.subscriptions.changePlan(id, { newPlanId: 'plan_enterprise', proration: 'create_prorations'});Payment Service
// Process a paymentconst payment = await billing.payments.process({ customerId: customer.id, amount: 9900, // in cents currency: 'usd', paymentMethodId: 'pm_xxx'});
// Get paymentconst payment = await billing.payments.get(paymentId);
// Get payments by customerconst payments = await billing.payments.getByCustomerId(customerId);
// Refund paymentconst refunded = await billing.payments.refund({ paymentId, amount: 5000, // partial refund reason: 'customer_request'});Invoice Service
// Create invoiceconst invoice = await billing.invoices.create({ customerId: customer.id, lines: [ { description: 'Pro Plan', amount: 9900, currency: 'usd' } ]});
// Get invoiceconst invoice = await billing.invoices.get(invoiceId);
// Mark invoice as paidawait billing.invoices.markPaid(invoiceId, paymentId);
// Void invoiceawait billing.invoices.void(invoiceId);Entitlement Service
// Check if customer has entitlementconst hasAccess = await billing.entitlements.check(customerId, 'advanced_analytics');
// Get all customer entitlementsconst entitlements = await billing.entitlements.getByCustomerId(customerId);
// Grant entitlementawait billing.entitlements.grant({ customerId, entitlementKey: 'premium_support', source: 'manual' });
// Revoke entitlementawait billing.entitlements.revoke(customerId, 'premium_support');Limit Service
// Check usage limitconst result = await billing.limits.check(customerId, 'api_calls');// Returns: { allowed: boolean, currentValue: number, maxValue: number, remaining: number }
// Get all customer limitsconst limits = await billing.limits.getByCustomerId(customerId);
// Increment usageawait billing.limits.increment(customerId, 'api_calls', 1);
// Set limitawait billing.limits.set({ customerId, limitKey: 'api_calls', maxValue: 10000 });
// Record usageawait billing.limits.recordUsage(customerId, 'api_calls', 100, 'increment');Metrics Service
// Get MRR (Monthly Recurring Revenue)const mrr = await billing.metrics.getMrr();
// Get subscription metricsconst subMetrics = await billing.metrics.getSubscriptionMetrics();
// Get revenue metricsconst revenue = await billing.metrics.getRevenueMetrics({ startDate: new Date('2024-01-01'), endDate: new Date('2024-12-31')});
// Get churn metricsconst churn = await billing.metrics.getChurnMetrics({ startDate: new Date('2024-01-01'), endDate: new Date('2024-12-31')});
// Get full dashboardconst dashboard = await billing.metrics.getDashboard();Event System
Subscribe to billing events:
// Subscribe to eventsbilling.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 listenerbilling.once('invoice.paid', async (event) => { // Handle first invoice});
// Unsubscribeconst unsubscribe = billing.on('customer.updated', handler);unsubscribe(); // Remove listenerAvailable Events
| Event | Description |
|---|---|
customer.created | Customer was created |
customer.updated | Customer was updated |
customer.deleted | Customer was deleted |
subscription.created | Subscription was created |
subscription.updated | Subscription was updated |
subscription.canceled | Subscription was canceled |
subscription.paused | Subscription was paused |
subscription.resumed | Subscription was resumed |
subscription.trial_ending | Trial is ending soon |
subscription.trial_ended | Trial has ended |
payment.succeeded | Payment was successful |
payment.failed | Payment failed |
payment.refunded | Payment was refunded |
payment.disputed | Payment was disputed |
invoice.created | Invoice was created |
invoice.paid | Invoice was paid |
invoice.payment_failed | Invoice payment failed |
invoice.voided | Invoice was voided |
addon.created | Add-on was created |
addon.updated | Add-on was updated |
addon.deleted | Add-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';