Skip to content
Last updated

PERS SDK - v2.3.26 / Exports / PersSDK

Class: 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

Table of contents

Accessors

Constructors

Methods

Accessors

events

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.

Returns

PersEventEmitter

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

Defined in

pers-sdk.ts:637


auth

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.

Returns

AuthManager

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

Defined in

pers-sdk.ts:677


users

get users(): UserManager

User manager - High-level user operations

Returns

UserManager

Example

const user = await sdk.user.getCurrentUser();
await sdk.user.updateCurrentUser(userData);
const users = await sdk.user.getAllUsersPublic();

Defined in

pers-sdk.ts:694


userStatus

get userStatus(): UserStatusManager

User Status manager - High-level user status operations

Returns

UserStatusManager

Example

const statusTypes = await sdk.userStatus.getUserStatusTypes();
const earnedStatus = await sdk.userStatus.getEarnedUserStatus();
await sdk.userStatus.createUserStatusType(statusData);

Defined in

pers-sdk.ts:711


tokens

get tokens(): TokenManager

Token manager - High-level token operations

Returns

TokenManager

Example

const tokens = await sdk.tokens.getTokens();
const creditToken = await sdk.tokens.getActiveCreditToken();
const rewards = await sdk.tokens.getRewardTokens();

Defined in

pers-sdk.ts:728


businesses

get businesses(): BusinessManager

Business manager - High-level business operations

Returns

BusinessManager

Example

const businesses = await sdk.business.getActiveBusinesses();
const business = await sdk.business.getBusinessById(id);
const types = await sdk.business.getBusinessTypes();

Defined in

pers-sdk.ts:745


campaigns

get campaigns(): CampaignManager

Campaign manager - High-level campaign operations

Returns

CampaignManager

Example

const campaigns = await sdk.campaigns.getActiveCampaigns();
await sdk.campaigns.claimCampaign(claimData);
const claims = await sdk.campaigns.getUserClaims();

Defined in

pers-sdk.ts:762


redemptions

get redemptions(): RedemptionManager

Redemption manager - High-level redemption operations

Returns

RedemptionManager

Example

const redemptions = await sdk.redemptions.getActiveRedemptions();
await sdk.redemptions.redeem(redemptionId);
const history = await sdk.redemptions.getUserRedemptions();

Defined in

pers-sdk.ts:779


transactions

get transactions(): TransactionManager

Transaction manager - High-level transaction operations

Returns

TransactionManager

Example

const transaction = await sdk.transactions.getTransactionById(id);
await sdk.transactions.createTransaction(txData);
const history = await sdk.transactions.getUserTransactionHistory('all');

Defined in

pers-sdk.ts:796


purchases

get purchases(): PurchaseManager

Purchase manager - High-level purchase operations

Returns

PurchaseManager

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();

Defined in

pers-sdk.ts:813


files

get files(): FileManager

File manager - High-level file operations

Returns

FileManager

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);

Defined in

pers-sdk.ts:830


tenants

get tenants(): TenantManager

Tenant manager - High-level tenant operations

Returns

TenantManager

Example

const tenant = await sdk.tenant.getTenantInfo();
const config = await sdk.tenant.getClientConfig();
const admins = await sdk.tenant.getAdmins();

Defined in

pers-sdk.ts:847


apiKeys

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.

Returns

ApiKeyManager

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');

Defined in

pers-sdk.ts:875


analytics

get analytics(): AnalyticsManager

Analytics manager - High-level analytics operations

Returns

AnalyticsManager

Example

const analytics = await sdk.analytics.getTransactionAnalytics(request);

Defined in

pers-sdk.ts:890


donations

get donations(): DonationManager

Donation manager - High-level donation operations

Returns

DonationManager

Example

const types = await sdk.donations.getDonationTypes();

Defined in

pers-sdk.ts:905


triggerSources

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.

Returns

TriggerSourceManager

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);

Defined in

pers-sdk.ts:940


webhooks

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.

Returns

WebhookManager

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

Defined in

pers-sdk.ts:980


customFields

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.

Returns

CustomFieldDefinitionManager

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);

Defined in

pers-sdk.ts:1013


bookings

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.

Returns

BookingManager

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
}

Defined in

pers-sdk.ts:1055


walletEvents

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.

Returns

WalletEventsManager

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

Defined in

pers-sdk.ts:1103


notifications

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.

Returns

NotificationManager

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

Defined in

pers-sdk.ts:1148

Constructors

constructor

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.

Parameters

NameTypeDescription
httpClientHttpClientPlatform-specific HTTP client implementation
configPersConfigSDK configuration options

Returns

PersSDK

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'
  });
}

Defined in

pers-sdk.ts:324

Methods

connectWalletEvents

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.

Returns

Promise<void>

Example

await sdk.connectWalletEvents();

Defined in

pers-sdk.ts:439


restoreSession

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).

Returns

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);
}

Defined in

pers-sdk.ts:500


configureWalletEvents

configureWalletEvents(config): void

Configure wallet events (call before accessing walletEvents)

Parameters

NameTypeDescription
configWalletEventsConfigEvents configuration including wsUrl

Returns

void

Defined in

pers-sdk.ts:1115


setDataSource

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'.

Parameters

NameTypeDescription
dataSourceDataSourceData source configuration

Returns

void

Example

sdk.setDataSource({
  medium: 'email',
  campaign: 'summer_2026',
  source: 'mailchimp',
});

Example

sdk.setDataSource({
  channel: 'mobile',
  medium: 'push',
  campaign: 'retention_30d',
});

Defined in

pers-sdk.ts:1186


updateDataSource

updateDataSource(dataSource): void

Update data source (merges with existing values)

Parameters

NameTypeDescription
dataSourcePartial<DataSource>Partial data source to merge

Returns

void

Example

sdk.updateDataSource({ campaign: 'new_campaign' });

Defined in

pers-sdk.ts:1200


setPlatform

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.

Parameters

NameTypeDescription
platformPlatformPlatform information

Returns

void

Example

sdk.setPlatform({
  os: 'iOS',
  osVersion: '17.4',
  app: 'MyApp',
  appVersion: '2.3.1',
  deviceType: 'phone',
});

Defined in

pers-sdk.ts:1223


api

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.

Returns

PersApiClient

Configured PersApiClient instance

Example

const apiClient = sdk.api();
const customData = await apiClient.get<CustomType>('/custom-endpoint');
await apiClient.post('/custom-endpoint', customData);

Defined in

pers-sdk.ts:1242


isProduction

isProduction(): boolean

Checks if SDK is configured for production environment

Returns

boolean

True if environment is 'production', false otherwise

Defined in

pers-sdk.ts:1251


isInitialized

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).

Returns

boolean

True if authentication provider is configured, false otherwise

Defined in

pers-sdk.ts:1263