0.0.17 • Published 7 months ago

@flowly/sdk v0.0.17

Weekly downloads
-
License
MIT
Repository
-
Last release
7 months ago

Flowly Attribution SDK

npm version license

Flowly Attribution SDK helps you measure user acquisition, conversion events, and revenue with a privacy-first, lightweight approach. Ideal for modern web applications looking for accurate marketing attribution without sacrificing speed or user experience.

🌐 Website | šŸ“š Documentation


Features

  • šŸ“ˆ Accurate Attribution — Track page visits, events, conversions, and revenue.
  • šŸ”’ Privacy-First — GDPR-compliant by design.
  • ⚔ Lightweight & Fast — Minimal performance impact.
  • šŸ”§ Highly Configurable — Customize logging, session management, and more.
  • šŸš€ Built for Developers — TypeScript support out of the box.

Installation

Install via npm or yarn:

npm install @flowly/sdk
# or
yarn add @flowly/sdk

Or use directly in the browser via CDN:

<script src="https://cdn.jsdelivr.net/npm/@flowly/sdk@latest/dist/flowly-sdk.js"></script>

Replace latest with the specific version number if needed.

When included this way, the SDK is available globally via the Flowly object.

Example:

<script src="https://cdn.jsdelivr.net/npm/@flowly/sdk@0.0.9/dist/flowly-sdk.js"></script>
<script>
  const builder = Flowly.builder();
  const flowly = builder
    .apiKey('your-api-key')
    .secret('your-secret-key')
    .productId('your-product-id')
    .productName('your-product-name')
    .build();

  flowly.pageVisit('HomePage');
</script>

Quick Start

import { builder, LogLevel } from '@flowly/sdk';

const flowly = builder()
  .apiKey('your-api-key')
  .secret('your-secret-key')
  .productId('your-product-id')
  .productName('your-product-name')
  .logLevel(LogLevel.Info)
  .sessionTimeout(1800) // Optional: Session timeout in seconds
  .consentSettings({ // Optional: Configure user consent
    isConsentGiven: true,
    analyticsEnabled: true,
    adsPersonalizationEnabled: true
  })
  .build();

// Track page visit
flowly.pageVisit('HomePage');

// Track a custom event using EventBuilder
flowly.newEvent('Signup')
  .withParameter('plan', 'Pro')
  .track();

// Track a conversion event
flowly.conversionEvent('PurchaseCompleted', { orderId: '12345' });

// Track revenue
flowly.revenue('Purchase', 'USD', 99.99, { productId: 'sku_123' });

// Identify and login a user
flowly.login('custom-user-id');

// Logout the current user
flowly.logout();

// Flush pending events
flowly.flush();

API Reference

Builder Methods

MethodDescription
apiKey(apiKey: string)Set the API key for authentication.
secret(secret: string)Set the API secret for secure authentication.
productId(productId: string)Set your product ID.
productName(productName: string)Set your product name.
customUserId(customUserId: string)Set a custom user identifier.
logLevel(logLevel: LogLevel)Define the logging level (Verbose, Debug, Info, etc.).
sessionTimeout(sessionTimeout: number)Set session timeout (seconds).
flowlyDeviceId(deviceId: string)Optionally set a custom device ID.
autoPersistDomain(autoPersistDomain: string)Auto-persist across subdomains.
baseUrl(baseUrl: string)Override the default API base URL.
consentSettings(settings: ConsentSettings): FlowlyBuilderConfigure initial user consent settings.
build()Initialize and build the FlowlyController instance.

FlowlyController Methods

MethodDescription
pageVisit(pageName: string)Track a page visit.
event(eventName: string, args: any)Track a generic custom event.
conversionEvent(eventName: string, args: any)Track a conversion-specific event.
revenue(eventName: string, currency: string, amount: number, args: any)Track revenue-related events.
login(customUserId: string)Identify and login a user.
logout()Logout the current user.
flush()Force send all pending events immediately.
getDeviceId()Retrieve the device identifier used by the SDK.
newEvent(eventName: string): EventBuilderStart building a custom event. Returns an EventBuilder.
newConversionEvent(eventName: string): EventBuilderStart building a conversion event. Returns an EventBuilder.
newRevenueEvent(eventName: string, currency: string, amount: number): EventBuilderStart building a revenue event. Returns an EventBuilder.
getState(): ControllerStateGet the current state of the SDK controller (e.g., STARTED, PAUSED).
pause(): voidPause event tracking. Events will be queued or discarded based on SDK policy when paused.
resume(): voidResume event tracking if previously paused.
getConsentSettings(): ConsentSettingsGet the current consent settings applied to the SDK.
updateConsentSettings(settings: ConsentSettings): voidUpdate user consent settings at runtime. Changes take effect immediately.
getSessionId(): stringGet the identifier for the current user session.
getGlobalProperties(): anyGet the currently set global properties that are automatically included with events.
setGlobalProperties(properties: any): voidSet global properties to be included with all subsequent events.
handleDeepLink(url: string): voidProcess a deep link URL for attribution purposes.
adRevenue(adPlatform: string, adSource: string, adUnitId: string, adFormat: string, value: number, currency: string, args?: object): voidTrack revenue generated from advertisements.
getAttributionInfo(callback: (attributionData: AttributionData | null) => void): voidRetrieves attribution information. The callback receives an AttributionData object or null.
setEventSentCallback(callback: ((eventName: string, eventType: string, eventArgs: object | null) => void) | null): voidSet a callback to be invoked after an event is processed by the SDK.
setSessionStartCallback(callback: ((sessionId: string) => void) | null): voidSet a callback to be invoked when a new session starts.
verifyPurchase(purchaseInfo: PurchaseData, callback: (result: VerificationResult) => void): voidSend purchase information for verification or tracking.
trackSubscriptionStart(productId: string, details?: object): voidTrack the start of a subscription.
trackSubscriptionRenewal(productId: string, details?: object): voidTrack a subscription renewal.
trackSubscriptionCancel(productId: string, details?: object): voidTrack a subscription cancellation.
trackTrialStart(productId: string, details?: object): voidTrack the start of a trial period.

Utilities

FunctionDescription
isEnabled(): booleanReturns true if tracking is currently enabled.
setEnabled(enabled: boolean)Enable or disable event tracking at runtime.
isInitialized(): booleanCheck if the SDK has been initialized.
getInstance(): FlowlyController \| nullGet the existing FlowlyController instance.

LogLevel Enum

Control the verbosity of SDK logs:

LogLevel.Verbose  // Detailed logs
LogLevel.Debug    // Debugging information
LogLevel.Info     // General information
LogLevel.Warn     // Warnings
LogLevel.Error    // Errors
LogLevel.Assert   // Assertions

EventBuilder Interface

The EventBuilder provides a fluent interface to construct and send events with multiple custom parameters. You obtain an EventBuilder instance by calling newEvent(), newConversionEvent(), or newRevenueEvent() on the FlowlyController.

MethodDescription
withParameter(key: string, value: any): EventBuilderAdd a custom key-value parameter to the event.
track(): voidFinalize and send the event.

Example:

flowly.newEvent('PlayerUpdate')
  .withParameter('level', 5)
  .withParameter('score', 1500)
  .track();

ControllerState Enum

Represents the operational state of the Flowly SDK. Accessed via flowly.getState().

StateDescription
NOT_STARTEDThe SDK has not been initialized or has been shut down.
STARTEDThe SDK is initialized and actively tracking events.
PAUSEDThe SDK is initialized but event tracking is temporarily paused.

ConsentSettings Object

The ConsentSettings object allows you to specify user consent preferences. It's used with builder.consentSettings() during initialization and flowly.updateConsentSettings() at runtime.

Properties:

PropertyTypeDescription
isConsentGivenbooleanGeneral consent for tracking. If false, other flags are typically ignored.
analyticsEnabledbooleanConsent for tracking general analytics and usage patterns.
adsPersonalizationEnabledbooleanConsent for collecting data for personalized advertising.

Example:

// To be used with builder.consentSettings() or flowly.updateConsentSettings()
const userConsent = {
  isConsentGiven: true,
  analyticsEnabled: true,
  adsPersonalizationEnabled: false // User opted out of ad personalization
};

// Example: Set initial consent during SDK build
// const flowly = builder()
//   .apiKey('your-api-key')
//   // ... other builder methods
//   .consentSettings(userConsent)
//   .build();

// Example: Update consent at runtime
// flowly.updateConsentSettings(userConsent);

(Note: The ConsentSettings object in Kotlin has static helper methods noConsent() and fullConsent(). Their availability in JS depends on JsExport of companion objects. If not directly available, create the object manually as shown above.)

AttributionData Object

Describes the resolved attribution information for the user. Accessed via flowly.getAttributionInfo().

PropertyTypeDescription
network?stringThe ad network or source that the attribution is credited to.
campaign?stringThe specific campaign name.
adgroup?stringThe ad group name.
creative?stringThe ad creative name or identifier.
clickLabel?stringUnique identifier for the touchpoint (e.g., click ID).
attributedAt?numberTimestamp (milliseconds since epoch) when the attribution was resolved.
rawData?objectA map containing any other raw parameters associated with the attribution.

Example:

// Structure of AttributionData object received in getAttributionInfo callback
// const attribution = {
//   network: "some_network",
//   campaign: "campaign_name",
//   attributedAt: 1678886400000, // Example timestamp
//   rawData: { custom_param: "value" }
// };

PurchaseData Object

Used with flowly.verifyPurchase() to send purchase details.

PropertyTypeDescription
productIdstringIdentifier for the product purchased.
transactionIdstringUnique identifier for the transaction.
receiptDatastringReceipt data (e.g., base64 encoded string, or JSON string from store).
currencystringISO 4217 currency code for the transaction amount (e.g., "USD").
amountnumberThe monetary value of the transaction.
extras?objectOptional map for any additional custom key-value data related to the purchase.

VerificationResult Object

Received in the callback from flowly.verifyPurchase().

PropertyTypeDescription
successbooleanIndicates if the SDK successfully processed/sent the verification request.
message?stringOptional message providing more details about the outcome.
transactionId?stringEchoes back the transaction ID from the PurchaseData.

Example

import { builder, LogLevel, isInitialized, getInstance } from '@flowly/sdk';

if (!isInitialized()) {
  builder()
    .apiKey('your-api-key')
    .secret('your-secret-key')
    .productId('your-product-id')
    .productName('your-product-name')
    .logLevel(LogLevel.Warn)
    .sessionTimeout(1800)
    .consentSettings({ // Example: Configure user consent
      isConsentGiven: true,
      analyticsEnabled: true,
      adsPersonalizationEnabled: false // User opts out of ad personalization
    })
    .build();
}

const flowlyInstance = getInstance();
flowlyInstance?.pageVisit('LandingPage');

// Example of using EventBuilder
flowlyInstance?.newEvent('NewsletterSignup')
  .withParameter('newsletter', 'TechWeekly')
  .track();

// Example of setting an event callback
flowlyInstance?.setEventSentCallback((eventName, eventType, eventArgs) => {
  console.log(`Event Sent: ${eventType} - ${eventName}`, eventArgs || {});
});

// Example of getting attribution info
flowlyInstance?.getAttributionInfo(attr => {
  if (attr) {
    console.log('Attribution:', attr.network, attr.campaign);
  } else {
    console.log('No attribution data yet.');
  }
});

Best Practices

  • šŸš€ Initialize Early — Initialize Flowly SDK as soon as your app loads to capture all events.
  • šŸ“– Use Meaningful Event Names — Helps with better analytics and attribution reports.
  • šŸ”’ Respect Privacy — Never log sensitive personal information.
  • šŸ“¦ Flush Before Exit — Flush events before page unload or user logout to ensure data is sent.

License

This project is licensed under the MIT License.


Support

If you encounter any issues or have questions, please reach out:

0.0.17

7 months ago

0.0.16

7 months ago

0.0.15

7 months ago

0.0.14

7 months ago

0.0.13

7 months ago

0.0.12

7 months ago

0.0.11

7 months ago

0.0.10

7 months ago

0.0.9

7 months ago

0.0.8

7 months ago

0.0.7

7 months ago

0.0.6

7 months ago

0.0.5

7 months ago

0.0.4

7 months ago

0.0.3

7 months ago

0.0.2

7 months ago

0.0.1

7 months ago