@subtrak/angular
v2.0.6
Published
Angular SDK for Subtrak - Subscription billing and entitlement management (IN DEVELOPMENT)
Maintainers
Readme
@subtrak/angular
IMPORTANT: This is a part of a developer-first SaaS Billing software that is still IN DEVELOPMENT. Send an email to [email protected] of you are interested in trying it out.
Official Angular SDK for Subtrak - The complete subscription billing and entitlement management solution for your SaaS application.
🚀 Quick Start
npm install @subtrak/angularConfiguration
// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { provideSubtrak, authInterceptor, caseTransformInterceptor } from '@subtrak/angular';
bootstrapApplication(AppComponent, {
providers: [
provideHttpClient(
withInterceptors([authInterceptor, caseTransformInterceptor])
),
provideSubtrak({
publicKey: 'pk_test_your_key_here',
apiUrl: 'https://api.subtrak.com/v5'
})
]
});Basic Usage
import { Component } from '@angular/core';
import { SubscriptionStatusComponent } from '@subtrak/angular';
@Component({
selector: 'app-billing',
standalone: true,
imports: [SubscriptionStatusComponent],
template: `
<subtrak-subscription-status
[customerId]="customerId"
[showEntitlements]="true"
[showUsageMeters]="true"
(upgradeClicked)="onUpgrade()">
</subtrak-subscription-status>
`
})
export class BillingComponent {
customerId = 'cus_123';
onUpgrade() {
// Handle upgrade action
}
}✨ Features
🎨 6 Pre-Built Components
- SubscriptionStatusComponent - Display subscription status with management actions
- EntitlementDisplayComponent - Auto-format entitlement values by type
- UsageMeterComponent - Real-time usage tracking with progress bars
- PaymentProviderCardComponent - Multi-provider payment forms (Stripe + Paymob)
- PricingTableComponent - Feature comparison and plan selection
- BillingPortalComponent - All-in-one billing management widget
⚡ 5 Complete Services
- SubscriptionsService - Subscription lifecycle management
- EntitlementsService - Feature access and limit checking
- UsageService - Metered usage tracking
- InvoicesService - Invoice history and PDF downloads
- PaymentMethodsService - Payment method management
🛡️ Additional Features
- 2 Directives -
*subFeatureGate,*subQuotaGuardfor feature gating - 1 Route Guard -
EntitlementGuardfor route protection - 3 Pipes - Format entitlement values in templates
- Multi-Provider Payments - Automatic Stripe/Paymob detection
- TypeScript - Full type safety with 350+ type definitions
- Standalone Components - Angular 17+ modern architecture
- RxJS - Reactive data streams
📚 Component Examples
Subscription Status
<subtrak-subscription-status
[customerId]="customerId"
[showEntitlements]="true"
[showUsageMeters]="true"
[showUpgradeButton]="true"
(upgradeClicked)="onUpgrade()">
</subtrak-subscription-status>Usage Meter
<subtrak-usage-meter
[meterId]="'api_calls'"
[customerId]="customerId"
[limitCode]="'max_api_calls'"
[showOverageWarning]="true"
[warningThreshold]="0.9">
</subtrak-usage-meter>Payment Provider Card
<!-- Auto-detects country from customer data -->
<subtrak-payment-provider-card
[customerId]="customerId"
(paymentMethodAdded)="onPaymentMethodAdded($event)"
(error)="onPaymentError($event)">
</subtrak-payment-provider-card>
<!-- Or specify country explicitly -->
<subtrak-payment-provider-card
[customerId]="customerId"
[countryCode]="'US'"
(paymentMethodAdded)="onPaymentMethodAdded($event)">
</subtrak-payment-provider-card>Pricing Table
<!-- Auto-detects country from customer data -->
<subtrak-pricing-table
[customerId]="customerId"
[currentPlanId]="currentPlan?.id"
(planSelected)="onPlanSelected($event)">
</subtrak-pricing-table>
<!-- Or specify country explicitly -->
<subtrak-pricing-table
[countryCode]="'US'"
[highlightEntitlements]="['premium_analytics', 'priority_support']"
(planSelected)="onPlanSelected($event)">
</subtrak-pricing-table>Billing Portal (All-in-One)
<!-- Complete billing management in one component -->
<subtrak-billing-portal
[customerId]="customerId">
</subtrak-billing-portal>🔧 Service Examples
Subscriptions
import { SubscriptionsService } from '@subtrak/angular';
constructor(private subscriptions: SubscriptionsService) {}
// Get current subscription
this.subscriptions.getCurrentSubscription('cus_123').subscribe(subscription => {
console.log('Current plan:', subscription.price.nickname);
});
// Create subscription
this.subscriptions.createSubscription({
customerId: 'cus_123',
priceId: 'price_456',
quantity: 1
}).subscribe();
// Upgrade subscription
this.subscriptions.upgradeSubscription('sub_789', 'price_premium').subscribe();Entitlements
import { EntitlementsService, EntitlementChecker } from '@subtrak/angular';
constructor(private entitlements: EntitlementsService) {}
// Get all entitlements
this.entitlements.getEntitlements('cus_123').subscribe(entitlements => {
const checker = new EntitlementChecker(entitlements);
// Check BOOLEAN features
if (checker.hasFeature('premium_analytics')) {
// Show premium analytics
}
// Check NUMERIC limits
const maxProjects = checker.getLimit('max_projects'); // 25
const remaining = checker.getRemainingQuota('max_projects', currentCount);
// Check ENUM values
const supportLevel = checker.getEnumValue('support_level'); // 'priority'
});Usage Tracking
import { UsageService } from '@subtrak/angular';
constructor(private usage: UsageService) {}
// Record usage event
this.usage.recordUsage({
meterId: 'meter_api_calls',
customerId: 'cus_123',
eventName: 'api_call',
properties: { endpoint: '/api/data', method: 'GET' },
value: 1
}).subscribe();
// Get current usage
this.usage.getCurrentUsage('meter_api_calls', 'cus_123').subscribe(summary => {
console.log('Total usage:', summary.totalUsage);
console.log('Billable units:', summary.billableUnits);
});Invoices
import { InvoicesService } from '@subtrak/angular';
constructor(private invoices: InvoicesService) {}
// List invoices
this.invoices.listInvoices({
customerId: 'cus_123',
status: InvoiceStatus.PAID
}).subscribe(response => {
console.log('Invoices:', response.data);
});
// Download PDF
this.invoices.downloadInvoicePdf('inv_123').subscribe(blob => {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'invoice.pdf';
a.click();
});🎯 Directives
Feature Gate
import { FeatureGateDirective } from '@subtrak/angular';
// Show/hide based on BOOLEAN entitlements
<div *subFeatureGate="'premium_analytics'; customerId: customerId; else: upgrade">
<app-premium-analytics></app-premium-analytics>
</div>
<ng-template #upgrade>
<button (click)="showUpgradeModal()">Upgrade to Pro</button>
</ng-template>Quota Guard
import { QuotaGuardDirective } from '@subtrak/angular';
// Show/hide based on NUMERIC limits
<button
*subQuotaGuard="'max_projects'; current: projectCount; customerId: customerId; else: limitReached"
(click)="createProject()">
Create New Project
</button>
<ng-template #limitReached>
<p>Project limit reached. Upgrade to create more.</p>
</ng-template>🔒 Route Guards
import { Routes } from '@angular/router';
import { EntitlementGuard } from '@subtrak/angular';
export const routes: Routes = [
{
path: 'analytics',
component: AnalyticsComponent,
canActivate: [EntitlementGuard],
data: {
entitlement: 'premium_analytics',
type: 'BOOLEAN',
redirectTo: '/upgrade'
}
}
];🌍 Multi-Provider Payments
The SDK automatically detects and uses the correct payment provider based on customer location:
- Stripe - Global countries (US, CA, GB, EU, etc.)
- Paymob - MENA region (Egypt, KSA, UAE, Oman, Pakistan)
// Automatic provider detection based on country
<subtrak-payment-provider-card
[customerId]="customerId"
[countryCode]="'EG'" // Automatically uses Paymob
(paymentMethodAdded)="onSuccess($event)">
</subtrak-payment-provider-card>📦 Installation & Setup
Step 1: Install Package
npm install @subtrak/angularStep 2: Configure Providers
// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { provideSubtrak, authInterceptor, caseTransformInterceptor } from '@subtrak/angular';
bootstrapApplication(AppComponent, {
providers: [
provideRouter(routes),
provideHttpClient(
withInterceptors([
authInterceptor,
caseTransformInterceptor
])
),
provideSubtrak({
publicKey: 'pk_test_your_key_here', // Your Subtrak public key
apiUrl: 'https://api.subtrak.com/v5' // Your API URL
})
]
}).catch(err => console.error(err));Step 3: Import Components
import { Component } from '@angular/core';
import {
SubscriptionStatusComponent,
PricingTableComponent,
BillingPortalComponent
} from '@subtrak/angular';
@Component({
selector: 'app-root',
standalone: true,
imports: [
SubscriptionStatusComponent,
PricingTableComponent,
BillingPortalComponent
],
template: `
<subtrak-billing-portal [customerId]="customerId">
</subtrak-billing-portal>
`
})
export class AppComponent {
customerId = 'cus_123';
}🎨 Entitlement Types
Subtrak supports 4 types of entitlements:
BOOLEAN - Feature Flags
{ key: 'premium_analytics', type: 'BOOLEAN', value: true }
// Display: ✓ Enabled or ✗ DisabledNUMERIC - Limits & Quotas
{ key: 'max_projects', type: 'NUMERIC', value: 25 }
// Display: 25 or 25 ProjectsENUM - Selection Values
{ key: 'support_level', type: 'ENUM', value: 'priority' }
// Display: Priority SupportMETERED - Usage-Based
{ key: 'api_calls', type: 'METERED', currentUsage: 8500, limit: 10000 }
// Display: 8,500 / 10,000 (85%)🔧 Configuration Options
interface SubtrakConfig {
// API Authentication (required)
publicKey?: string; // For frontend apps
secretKey?: string; // For backend apps (use publicKey in browser)
// API Configuration
apiUrl?: string; // Default: staging API
timeout?: number; // Request timeout (default: 30000ms)
maxRetries?: number; // Max retry attempts (default: 3)
// Customer Context
customerId?: string; // Pre-set customer ID for all requests
// Debugging
debug?: boolean; // Enable debug logging (default: false)
}🌟 Angular 19.2 Support
This package is fully compatible with Angular 19.2:
- ✅ Angular 19.2.x (recommended)
- ✅ Angular 18.x
- ✅ Angular 17.x
- ✅ TypeScript 5.6
- ✅ RxJS 7.8 & 8.x
- ✅ Zone.js 0.15
- ✅ Standalone components
- ✅ Functional interceptors
- ✅ Modern build tools
📊 Bundle Size
- Unpacked: ~850 KB
- Gzipped: ~120 KB
- Tree-shakeable: Import only what you need
🔐 Error Handling
import { ApiError, ValidationError, AuthError, NotFoundError } from '@subtrak/angular';
this.subscriptions.createSubscription({...}).subscribe({
next: (subscription) => {
// Success
},
error: (error) => {
if (error instanceof ValidationError) {
console.error('Validation failed:', error.details);
} else if (error instanceof AuthError) {
this.router.navigate(['/login']);
} else if (error instanceof NotFoundError) {
console.error('Resource not found');
}
}
});📖 Documentation
- GitHub: https://github.com/subtrak/subtrak-angular-sdk
- Changelog: CHANGELOG.md
- Migration Guide: MIGRATION_V2.md
- Example App: example-app
🐛 Issues & Support
Found a bug or need help?
- GitHub Issues: https://github.com/subtrak/subtrak-angular-sdk/issues
- Discussions: https://github.com/subtrak/subtrak-angular-sdk/discussions
📝 License
MIT License - see LICENSE file for details.
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
🔄 Changelog
See CHANGELOG.md for a list of changes.
🏷️ Version
Current version: 2.0.0
- Full Angular 19.2 support
- Backward compatible with Angular 17 & 18
- Zero breaking changes from v1.x
Made with ❤️ by the Subtrak team
For more information, visit subtrak.com
