PERS SDK - v2.3.26 / Exports / PersSDK
PERS SDK - Main SDK class with domain managers
Main SDK interface providing clean, high-level managers for common operations while maintaining full access to the underlying API client and domain services.
The SDK follows a layered architecture:
- Managers: High-level, intuitive APIs for common operations
- Domain Services: Full-featured access for advanced use cases
- API Client: Direct REST API access for custom operations
Example
import { PersSDK } from '@explorins/pers-sdk';
import { BrowserFetchClientAdapter } from '@explorins/pers-sdk/platform-adapters';
const sdk = new PersSDK(new BrowserFetchClientAdapter(), {
environment: 'production',
apiProjectKey: 'your-project-key'
});Example
// Login with external JWT
await sdk.auth.loginWithToken(firebaseJWT, 'user');
// Check authentication
if (await sdk.auth.isAuthenticated()) {
const user = await sdk.auth.getCurrentUser();
console.log('Welcome,', user.name);
}Example
// Get active businesses
const businesses = await sdk.businesses.getActiveBusinesses();
// Get business details
const business = await sdk.businesses.getBusinessById(businessId);Example
// Get user's token balances
const tokens = await sdk.tokens.getTokens();
// Get active credit token
const creditToken = await sdk.tokens.getActiveCreditToken();Since
1.3.0 - Manager pattern architecture
- events
- auth
- users
- userStatus
- tokens
- businesses
- campaigns
- redemptions
- transactions
- purchases
- files
- tenants
- apiKeys
- analytics
- donations
- triggerSources
- webhooks
- customFields
- bookings
- walletEvents
- notifications
- connectWalletEvents
- restoreSession
- configureWalletEvents
- setDataSource
- updateDataSource
- setPlatform
- api
- isProduction
- isInitialized
• get events(): PersEventEmitter
Event emitter - Subscribe to SDK-wide events
Provides a platform-agnostic event system for subscribing to transaction, authentication, campaign, and system events. Use this to display notifications, update UI, or trigger side effects in your application.
All events have a userMessage field ready for display.
PersEventEmitter instance
Example
const unsubscribe = sdk.events.subscribe((event) => {
// userMessage is always present and UI-ready
showNotification(event.userMessage, event.level);
});
// Later: cleanup
unsubscribe();Example
sdk.events.subscribe((event) => {
if (event.level === 'success' && event.domain === 'transaction') {
playSuccessSound();
confetti();
}
if (event.level === 'error') {
logToSentry(event);
}
});Example
// Auto-unsubscribe after first event
sdk.events.once((event) => {
console.log('First event received:', event.type);
});See
PersEventEmitter for detailed documentation
• get auth(): AuthManager
Authentication manager - High-level authentication operations
Provides methods for user login, logout, token management, and authentication status checking. Supports both user and admin authentication flows.
AuthManager instance
Example
// Login with external JWT (Firebase, Auth0, etc.)
await sdk.auth.loginWithToken(firebaseJWT, 'user');
// Check authentication status
if (await sdk.auth.isAuthenticated()) {
const user = await sdk.auth.getCurrentUser();
console.log('Welcome,', user.name);
}
// Logout
await sdk.auth.clearAuth();Example
// Admin login
await sdk.auth.loginAdmin(adminJWT);
// Check if valid auth exists (synchronous)
if (sdk.auth.hasValidAuth()) {
console.log('Authentication tokens found');
}See
AuthManager for detailed documentation
• get users(): UserManager
User manager - High-level user operations
Example
const user = await sdk.user.getCurrentUser();
await sdk.user.updateCurrentUser(userData);
const users = await sdk.user.getAllUsersPublic();• get userStatus(): UserStatusManager
User Status manager - High-level user status operations
Example
const statusTypes = await sdk.userStatus.getUserStatusTypes();
const earnedStatus = await sdk.userStatus.getEarnedUserStatus();
await sdk.userStatus.createUserStatusType(statusData);• get tokens(): TokenManager
Token manager - High-level token operations
Example
const tokens = await sdk.tokens.getTokens();
const creditToken = await sdk.tokens.getActiveCreditToken();
const rewards = await sdk.tokens.getRewardTokens();• get businesses(): BusinessManager
Business manager - High-level business operations
Example
const businesses = await sdk.business.getActiveBusinesses();
const business = await sdk.business.getBusinessById(id);
const types = await sdk.business.getBusinessTypes();• get campaigns(): CampaignManager
Campaign manager - High-level campaign operations
Example
const campaigns = await sdk.campaigns.getActiveCampaigns();
await sdk.campaigns.claimCampaign(claimData);
const claims = await sdk.campaigns.getUserClaims();• get redemptions(): RedemptionManager
Redemption manager - High-level redemption operations
Example
const redemptions = await sdk.redemptions.getActiveRedemptions();
await sdk.redemptions.redeem(redemptionId);
const history = await sdk.redemptions.getUserRedemptions();• get transactions(): TransactionManager
Transaction manager - High-level transaction operations
Example
const transaction = await sdk.transactions.getTransactionById(id);
await sdk.transactions.createTransaction(txData);
const history = await sdk.transactions.getUserTransactionHistory('all');• get purchases(): PurchaseManager
Purchase manager - High-level purchase operations
Example
const intent = await sdk.purchases.createPaymentIntent(100, 'usd', 'email@example.com', 'Purchase');
const tokens = await sdk.purchases.getActivePurchaseTokens();
const purchases = await sdk.purchases.getAllUserPurchases();• get files(): FileManager
File manager - High-level file operations
Example
const uploadUrl = await sdk.files.getSignedPutUrl('entity-123', 'token', 'jpg');
const accessUrl = await sdk.files.getSignedGetUrl('entity-123', 'token');
const optimizedUrl = await sdk.files.optimizeMedia(originalUrl, 800, 600);• get tenants(): TenantManager
Tenant manager - High-level tenant operations
Example
const tenant = await sdk.tenant.getTenantInfo();
const config = await sdk.tenant.getClientConfig();
const admins = await sdk.tenant.getAdmins();• get apiKeys(): ApiKeyManager
API Key manager - High-level API key management operations (Admin Only)
Provides methods for creating, listing, and revoking API keys for the tenant. All operations require tenant admin authentication.
ApiKeyManager instance
Example
// Create a JWT token for frontend authentication
const jwtToken = await sdk.apiKeys.createJwtToken('Frontend App');
console.log('Store this JWT securely:', jwtToken.key);
// List all API keys
const apiKeys = await sdk.apiKeys.listApiKeys();
// Revoke an old API key
await sdk.apiKeys.revokeApiKey('old-key-id');• get analytics(): AnalyticsManager
Analytics manager - High-level analytics operations
Example
const analytics = await sdk.analytics.getTransactionAnalytics(request);• get donations(): DonationManager
Donation manager - High-level donation operations
Example
const types = await sdk.donations.getDonationTypes();• get triggerSources(): TriggerSourceManager
TriggerSource manager - High-level trigger source operations (Admin Only)
Provides CRUD operations for managing trigger sources (QR codes, NFC tags, GPS geofences, API webhooks). TriggerSources are standalone entities that can be assigned to campaigns via the campaigns manager.
TriggerSourceManager instance
Example
// Create a QR code trigger source
const qrSource = await sdk.triggerSources.create({
name: 'Store Entrance QR',
type: 'QR_CODE',
description: 'QR code at main entrance'
});
// Get all trigger sources
const sources = await sdk.triggerSources.getAll();
// Update trigger source
await sdk.triggerSources.update(sourceId, { name: 'Updated Name' });
// Assign to campaign (via campaigns manager)
await sdk.campaigns.assignTriggerSource(campaignId, qrSource.id);• get webhooks(): WebhookManager
Webhook manager - High-level webhook operations
Provides methods for creating webhooks, triggering them programmatically, and monitoring execution history. Supports async workflows with callbacks.
WebhookManager instance
Example
// Admin: Create a webhook
const webhook = await sdk.webhooks.create({
name: 'Order Processing',
targetUrl: 'https://n8n.example.com/webhook/orders',
method: 'POST'
});
// Trigger webhook with payload
const result = await sdk.webhooks.trigger(webhook.id, {
orderId: 'order-123',
action: 'created'
});
// Trigger and wait for async workflow completion
const asyncResult = await sdk.webhooks.triggerAndWait(
'ai-webhook',
{ prompt: 'Analyze this data' },
30000 // Wait up to 30s
);See
WebhookManager for detailed documentation
• get customFields(): CustomFieldDefinitionManager
Custom Field Definition Manager - Manage tenant-specific custom fields
Provides CRUD operations for custom field definitions that extend the built-in user profile fields. Custom fields are tenant-specific and support validation.
CustomFieldDefinitionManager instance
Example
// List all custom fields
const fields = await sdk.customFields.getDefinitions();
// Create a new field
const field = await sdk.customFields.createDefinition({
key: 'employee_id',
label: 'Employee ID',
fieldType: 'text',
validation: { required: true }
});
// Validate user data
const errors = sdk.customFields.validateUserData(formData, fields.data);• get bookings(): BookingManager
Booking manager - High-level booking operations
Provides methods for managing user bookings (hotel stays, reservations, etc.) Used for eligibility checks on redemptions that require valid bookings.
BookingManager instance
Example
// Get all bookings for a user
const bookings = await sdk.bookings.getByUser('user-123');
// Filter by status
const activeBookings = await sdk.bookings.getAll({ status: 'active' });Example
const booking = await sdk.bookings.create({
userId: 'user-123',
locationName: 'Grand Hotel',
checkInDate: '2026-06-01',
checkOutDate: '2026-06-05'
});Example
const hasBooking = await sdk.bookings.hasValidBooking('user-123');
if (hasBooking) {
// User is eligible for booking-required redemption
}• get walletEvents(): WalletEventsManager
Wallet Events Manager - Real-time blockchain events for user's wallets
Provides real-time WebSocket connection to receive blockchain events for the user's wallets (transfers, approvals, NFT mints, etc.).
Events are also routed through sdk.events for unified event handling.
Important: Requires walletEventsWsUrl configuration and authentication.
WalletEventsManager instance
Example
// Configure SDK with events URL
sdk.configureWalletEvents({ wsUrl: 'wss://events.pers.ninja' });
// Connect after authentication
await sdk.auth.loginWithToken(jwt, 'user');
await sdk.walletEvents.connect();
// Listen for token transfers
sdk.walletEvents.on('Transfer', (event) => {
if (event.data.to === myWallet) {
showNotification(`Received ${event.data.value} tokens!`);
}
});Example
// Wallet events also flow through sdk.events
sdk.events.subscribe((event) => {
if (event.domain === 'wallet') {
console.log('Wallet event:', event.type);
}
});See
WalletEventsManager for detailed documentation
• get notifications(): NotificationManager
Notification Manager - Per-recipient notification inbox (Flow 1 — transactional/private)
Notifications are delivered through two independent channels — use both together:
- REST inbox (
list,getUnreadCount,markAsRead,delete): source of truth - WS Relay
notification.pending(onPending): real-time wake signal only
Real-time delivery shares the same WebSocket connection as sdk.walletEvents — calling connectRealtime() connects it (if needed) and binds the channelId.
NotificationManager instance
Example
await sdk.notifications.connectRealtime();
const inbox = await sdk.notifications.list({ unreadOnly: true });
const { count } = await sdk.notifications.getUnreadCount();
sdk.notifications.onPending(() => {
// Signal carries no content — re-fetch the inbox
sdk.notifications.list();
});See
NotificationManager for detailed documentation
• new PersSDK(httpClient, config): PersSDK
Creates a new PERS SDK instance
Initializes all domain managers and sets up the API client with the provided HTTP client adapter and configuration.
| Name | Type | Description |
|---|---|---|
httpClient | HttpClient | Platform-specific HTTP client implementation |
config | PersConfig | SDK configuration options |
Example
import { BrowserFetchClientAdapter } from '@explorins/pers-sdk/platform-adapters';
const sdk = new PersSDK(new BrowserFetchClientAdapter(), {
environment: 'production',
apiProjectKey: 'your-project-key'
});Example
import { NodeHttpClientAdapter } from '@explorins/pers-sdk/platform-adapters';
const sdk = new PersSDK(new NodeHttpClientAdapter(), {
environment: 'production',
apiProjectKey: 'your-project-key',
baseUrl: 'https://api.yourpers.com'
});Example
import { AngularHttpClientAdapter } from '@explorins/pers-sdk/platform-adapters';
constructor(private http: HttpClient) {
this.sdk = new PersSDK(new AngularHttpClientAdapter(this.http), {
environment: 'production',
apiProjectKey: 'your-project-key'
});
}▸ connectWalletEvents(): Promise<void>
Connect to wallet events and auto-subscribe based on auth type
Connects to the WebSocket relay and automatically subscribes to relevant blockchain events based on the current authentication type:
- USER: Subscribes to all user's wallets
- BUSINESS: Subscribes to all business's wallets
- TENANT: Subscribes to all chains where tokens are deployed
This method is called automatically on login when captureWalletEvents is enabled. Call manually if you need to reconnect or refresh subscriptions.
Promise<void>
Example
await sdk.connectWalletEvents();▸ restoreSession(): Promise<null | UserDTO>
Restore user session from stored tokens
Note: This method is called automatically on SDK initialization when autoRestoreSession is enabled (default: true). You only need to call this manually if you disabled auto-restore or need to force a session refresh.
Validates stored tokens and fetches user data to restore the session. Emits session_restored event on success, session_restoration_failed on error.
Important: Only works for USER and BUSINESS accounts. Admin/tenant accounts don't support user data fetching, so this will return null for them (though their tokens remain valid for API calls).
Promise<null | UserDTO>
Promise resolving to User data if session restored, null if no session or admin account
Throws
If token validation or user fetch fails
Example
// Manual restore (only needed if autoRestoreSession: false)
const user = await sdk.restoreSession();
if (user) {
console.log('Welcome back,', user.name);
}▸ configureWalletEvents(config): void
Configure wallet events (call before accessing walletEvents)
| Name | Type | Description |
|---|---|---|
config | WalletEventsConfig | Events configuration including wsUrl |
void
▸ setDataSource(dataSource): void
Set data source tracking for analytics attribution
Use this to track where users and actions originate from. Web apps typically only need medium/campaign/source (channel is auto-detected). Native apps must set channel: 'mobile'.
| Name | Type | Description |
|---|---|---|
dataSource | DataSource | Data source configuration |
void
Example
sdk.setDataSource({
medium: 'email',
campaign: 'summer_2026',
source: 'mailchimp',
});Example
sdk.setDataSource({
channel: 'mobile',
medium: 'push',
campaign: 'retention_30d',
});▸ updateDataSource(dataSource): void
Update data source (merges with existing values)
| Name | Type | Description |
|---|---|---|
dataSource | Partial<DataSource> | Partial data source to merge |
void
Example
sdk.updateDataSource({ campaign: 'new_campaign' });▸ setPlatform(platform): void
Set platform info for device analytics
Native apps should call this on initialization with device info. Web apps can optionally send browser/OS info.
| Name | Type | Description |
|---|---|---|
platform | Platform | Platform information |
void
Example
sdk.setPlatform({
os: 'iOS',
osVersion: '17.4',
app: 'MyApp',
appVersion: '2.3.1',
deviceType: 'phone',
});▸ api(): PersApiClient
Gets the API client for direct PERS API requests
Use this for advanced operations not covered by the managers. The returned client handles authentication, token refresh, and error handling automatically.
Configured PersApiClient instance
Example
const apiClient = sdk.api();
const customData = await apiClient.get<CustomType>('/custom-endpoint');
await apiClient.post('/custom-endpoint', customData);▸ isProduction(): boolean
Checks if SDK is configured for production environment
boolean
True if environment is 'production', false otherwise
▸ isInitialized(): boolean
Checks if SDK has an authentication provider configured
Note: This only checks if an auth provider exists, not if tokens are valid. For token validity checking, use auth.hasValidAuth() (async) or auth.isAuthenticated() (async).
boolean
True if authentication provider is configured, false otherwise