CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-ionic-native

Native plugin wrappers for Cordova and Ionic with TypeScript, ES6+, Promise and Observable support

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

analytics-monetization.mddocs/

Analytics & Monetization

App analytics, advertising integration, and monetization features for tracking user behavior, revenue generation, and business intelligence.

Capabilities

Google Analytics

Comprehensive analytics tracking for user behavior, events, and app performance monitoring.

/**
 * GoogleAnalytics class for app analytics and tracking
 */
class GoogleAnalytics {
  /**
   * Initialize Google Analytics with tracking ID
   * @param id Google Analytics tracking ID
   * @returns Promise indicating initialization completion
   */
  static startTrackerWithId(id: string): Promise<any>;

  /**
   * Track screen view
   * @param title Screen or page title
   * @returns Promise indicating tracking completion
   */
  static trackView(title: string): Promise<any>;

  /**
   * Track custom event
   * @param category Event category
   * @param action Event action
   * @param label Event label (optional)
   * @param value Event value (optional)
   * @returns Promise indicating tracking completion
   */
  static trackEvent(category: string, action: string, label?: string, value?: number): Promise<any>;

  /**
   * Track exception/error
   * @param description Exception description
   * @param fatal Whether exception was fatal
   * @returns Promise indicating tracking completion
   */
  static trackException(description: string, fatal: boolean): Promise<any>;

  /**
   * Track timing measurement
   * @param category Timing category
   * @param intervalInMilliseconds Duration in milliseconds
   * @param variable Timing variable name
   * @param label Timing label
   * @returns Promise indicating tracking completion
   */
  static trackTiming(category: string, intervalInMilliseconds: number, variable: string, label: string): Promise<any>;

  /**
   * Add custom dimension
   * @param key Custom dimension index
   * @param value Custom dimension value
   * @returns Promise indicating completion
   */
  static addCustomDimension(key: number, value: string): Promise<any>;

  /**
   * Add e-commerce transaction
   * @param transactionId Transaction ID
   * @param affiliation Store or affiliation
   * @param revenue Total revenue
   * @param tax Tax amount
   * @param shipping Shipping cost
   * @param currency Currency code
   * @returns Promise indicating completion
   */
  static addTransaction(transactionId: string, affiliation: string, revenue: number, tax: number, shipping: number, currency: string): Promise<any>;

  /**
   * Add e-commerce transaction item
   * @param transactionId Transaction ID
   * @param name Item name
   * @param sku Item SKU
   * @param category Item category
   * @param price Item price
   * @param quantity Item quantity
   * @param currency Currency code
   * @returns Promise indicating completion
   */
  static addTransactionItem(transactionId: string, name: string, sku: string, category: string, price: number, quantity: number, currency: string): Promise<any>;

  /**
   * Enable uncaught exception reporting
   * @param enable Whether to enable exception reporting
   * @returns Promise indicating completion
   */
  static enableUncaughtExceptionReporting(enable: boolean): Promise<any>;
}

Usage Examples:

import { GoogleAnalytics } from 'ionic-native';

// Analytics service for comprehensive tracking
class AnalyticsService {
  private isInitialized = false;
  
  async initialize(trackingId: string): Promise<void> {
    try {
      await GoogleAnalytics.startTrackerWithId(trackingId);
      await GoogleAnalytics.enableUncaughtExceptionReporting(true);
      
      this.isInitialized = true;
      console.log('Google Analytics initialized');
      
      // Track app startup
      this.trackEvent('App', 'Start', 'User opened app');
    } catch (error) {
      console.error('Analytics initialization failed:', error);
    }
  }
  
  async trackPageView(pageName: string, additionalData?: any): Promise<void> {
    if (!this.isInitialized) return;
    
    try {
      await GoogleAnalytics.trackView(pageName);
      
      // Track additional custom dimensions if provided
      if (additionalData) {
        await this.setCustomDimensions(additionalData);
      }
      
      console.log('Page view tracked:', pageName);
    } catch (error) {
      console.error('Page view tracking failed:', error);
    }
  }
  
  async trackEvent(category: string, action: string, label?: string, value?: number): Promise<void> {
    if (!this.isInitialized) return;
    
    try {
      await GoogleAnalytics.trackEvent(category, action, label, value);
      console.log('Event tracked:', { category, action, label, value });
    } catch (error) {
      console.error('Event tracking failed:', error);
    }
  }
  
  async trackUserAction(action: string, details?: any): Promise<void> {
    await this.trackEvent('User', action, details?.label, details?.value);
  }
  
  async trackError(error: Error, isFatal: boolean = false): Promise<void> {
    if (!this.isInitialized) return;
    
    try {
      const description = `${error.name}: ${error.message}`;
      await GoogleAnalytics.trackException(description, isFatal);
      console.log('Exception tracked:', description);
    } catch (trackingError) {
      console.error('Exception tracking failed:', trackingError);
    }
  }
  
  async trackTiming(category: string, variable: string, timeMs: number, label?: string): Promise<void> {
    if (!this.isInitialized) return;
    
    try {
      await GoogleAnalytics.trackTiming(category, timeMs, variable, label || '');
      console.log('Timing tracked:', { category, variable, timeMs, label });
    } catch (error) {
      console.error('Timing tracking failed:', error);
    }
  }
  
  private async setCustomDimensions(data: { [key: string]: string }): Promise<void> {
    // Map custom dimensions (configure these in GA dashboard)
    const dimensionMap: { [key: string]: number } = {
      userType: 1,
      appVersion: 2,
      platform: 3,
      language: 4
    };
    
    for (const [key, value] of Object.entries(data)) {
      const dimensionIndex = dimensionMap[key];
      if (dimensionIndex) {
        await GoogleAnalytics.addCustomDimension(dimensionIndex, value);
      }
    }
  }
  
  // E-commerce tracking
  async trackPurchase(transaction: {
    id: string;
    affiliation: string;
    revenue: number;
    tax?: number;
    shipping?: number;
    currency?: string;
    items: Array<{
      name: string;
      sku: string;
      category: string;
      price: number;
      quantity: number;
    }>;
  }): Promise<void> {
    if (!this.isInitialized) return;
    
    try {
      // Track main transaction
      await GoogleAnalytics.addTransaction(
        transaction.id,
        transaction.affiliation,
        transaction.revenue,
        transaction.tax || 0,
        transaction.shipping || 0,
        transaction.currency || 'USD'
      );
      
      // Track individual items
      for (const item of transaction.items) {
        await GoogleAnalytics.addTransactionItem(
          transaction.id,
          item.name,
          item.sku,
          item.category,
          item.price,
          item.quantity,
          transaction.currency || 'USD'
        );
      }
      
      console.log('Purchase tracked:', transaction.id);
    } catch (error) {
      console.error('Purchase tracking failed:', error);
    }
  }
}

// Enhanced analytics with automatic tracking
class SmartAnalytics extends AnalyticsService {
  private sessionStartTime: number = 0;
  private pageStartTime: number = 0;
  private userProperties: any = {};
  
  async initialize(trackingId: string, userProperties?: any): Promise<void> {
    await super.initialize(trackingId);
    
    this.sessionStartTime = Date.now();
    this.userProperties = userProperties || {};
    
    // Set up automatic tracking
    this.setupAutomaticTracking();
  }
  
  private setupAutomaticTracking(): void {
    // Track app lifecycle events
    document.addEventListener('visibilitychange', () => {
      if (document.hidden) {
        this.trackEvent('App', 'Background', 'App went to background');
      } else {
        this.trackEvent('App', 'Foreground', 'App came to foreground');
      }
    });
    
    // Track unhandled errors
    window.addEventListener('error', (event) => {
      this.trackError(new Error(event.message), false);
    });
    
    // Track navigation (for SPAs)
    this.setupNavigationTracking();
  }
  
  private setupNavigationTracking(): void {
    // Track route changes (example for hash-based routing)
    window.addEventListener('hashchange', () => {
      const pageName = window.location.hash.substring(1) || 'home';
      this.trackPageView(pageName);
    });
    
    // Track initial page
    const initialPage = window.location.hash.substring(1) || 'home';
    this.trackPageView(initialPage);
  }
  
  async trackPageView(pageName: string, additionalData?: any): Promise<void> {
    // Track time on previous page
    if (this.pageStartTime > 0) {
      const timeOnPage = Date.now() - this.pageStartTime;
      await this.trackTiming('Navigation', 'PageTime', timeOnPage, pageName);
    }
    
    this.pageStartTime = Date.now();
    
    // Include user properties in tracking
    const trackingData = { ...this.userProperties, ...additionalData };
    await super.trackPageView(pageName, trackingData);
  }
  
  async trackUserEngagement(engagementType: string, details?: any): Promise<void> {
    const engagementEvents = {
      'scroll_75': { category: 'Engagement', action: 'Scroll', label: '75%' },
      'time_10s': { category: 'Engagement', action: 'Time', label: '10 seconds' },
      'time_30s': { category: 'Engagement', action: 'Time', label: '30 seconds' },
      'time_60s': { category: 'Engagement', action: 'Time', label: '1 minute' },
      'button_click': { category: 'Engagement', action: 'Click', label: details?.button },
      'form_submit': { category: 'Engagement', action: 'Submit', label: details?.form }
    };
    
    const event = engagementEvents[engagementType];
    if (event) {
      await this.trackEvent(event.category, event.action, event.label, details?.value);
    }
  }
  
  async trackPerformanceMetrics(): Promise<void> {
    if (!window.performance) return;
    
    const navigation = window.performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming;
    
    if (navigation) {
      await this.trackTiming('Performance', 'DOMLoad', navigation.domContentLoadedEventEnd - navigation.domContentLoadedEventStart);
      await this.trackTiming('Performance', 'PageLoad', navigation.loadEventEnd - navigation.loadEventStart);
      await this.trackTiming('Performance', 'TTFB', navigation.responseStart - navigation.requestStart);
    }
  }
  
  getSessionDuration(): number {
    return Date.now() - this.sessionStartTime;
  }
  
  async endSession(): Promise<void> {
    const sessionDuration = this.getSessionDuration();
    await this.trackTiming('Session', 'Duration', sessionDuration);
    await this.trackEvent('Session', 'End', 'User ended session');
  }
}

AdMob Integration

Mobile advertising integration for banner ads, interstitial ads, and rewarded video ads.

/**
 * AdMob advertising configuration options
 */
interface AdMobOptions {
  /** Banner ad unit ID */
  bannerId?: string;
  /** Interstitial ad unit ID */
  interstitialId?: string;
  /** Rewarded video ad unit ID */
  rewardVideoId?: string;
  /** Whether app is in testing mode */
  isTesting?: boolean;
  /** Auto-show ads when loaded */
  autoShow?: boolean;
}

/**
 * AdMob class for mobile advertising
 */
class AdMob {
  /**
   * Create banner advertisement
   * @param adIdOrOptions Ad unit ID or configuration options
   * @returns Promise indicating banner creation completion
   */
  static createBanner(adIdOrOptions: string | AdMobOptions): Promise<any>;

  /**
   * Remove banner advertisement
   * @returns Promise indicating banner removal completion
   */
  static removeBanner(): Promise<any>;

  /**
   * Show banner at specific position
   * @param position Banner position (1: TOP_CENTER, 2: BOTTOM_CENTER, etc.)
   * @returns Promise indicating show completion
   */
  static showBanner(position: number): Promise<any>;

  /**
   * Show banner at specific coordinates
   * @param x X coordinate
   * @param y Y coordinate
   * @returns Promise indicating show completion
   */
  static showBannerAtXY(x: number, y: number): Promise<any>;

  /**
   * Hide banner advertisement
   * @returns Promise indicating hide completion
   */
  static hideBanner(): Promise<any>;

  /**
   * Prepare interstitial advertisement
   * @param adIdOrOptions Ad unit ID or configuration options
   * @returns Promise indicating preparation completion
   */
  static prepareInterstitial(adIdOrOptions: string | AdMobOptions): Promise<any>;

  /**
   * Show interstitial advertisement
   * @returns Promise indicating show completion
   */
  static showInterstitial(): Promise<any>;

  /**
   * Prepare rewarded video advertisement
   * @param adIdOrOptions Ad unit ID or configuration options
   * @returns Promise indicating preparation completion
   */
  static prepareRewardVideoAd(adIdOrOptions: string | AdMobOptions): Promise<any>;

  /**
   * Show rewarded video advertisement
   * @returns Promise indicating show completion
   */
  static showRewardVideoAd(): Promise<any>;
}

Usage Examples:

import { AdMob, AdMobOptions } from 'ionic-native';

// AdMob advertising service
class AdvertisingService {
  private adConfig: AdMobOptions;
  private bannerVisible = false;
  private interstitialReady = false;
  private rewardVideoReady = false;
  
  constructor(config: AdMobOptions) {
    this.adConfig = config;
  }
  
  async initialize(): Promise<void> {
    try {
      console.log('Initializing AdMob with config:', this.adConfig);
      
      // Pre-load interstitial ad
      await this.prepareInterstitial();
      
      // Pre-load rewarded video
      await this.prepareRewardVideo();
      
      console.log('AdMob initialized successfully');
    } catch (error) {
      console.error('AdMob initialization failed:', error);
    }
  }
  
  // Banner ad management
  async showBanner(position: 'top' | 'bottom' = 'bottom'): Promise<void> {
    try {
      if (this.bannerVisible) {
        await this.hideBanner();
      }
      
      await AdMob.createBanner(this.adConfig);
      
      const positionCode = position === 'top' ? 1 : 2; // TOP_CENTER : BOTTOM_CENTER
      await AdMob.showBanner(positionCode);
      
      this.bannerVisible = true;
      console.log('Banner ad shown at:', position);
    } catch (error) {
      console.error('Banner ad failed:', error);
    }
  }
  
  async hideBanner(): Promise<void> {
    try {
      if (this.bannerVisible) {
        await AdMob.hideBanner();
        this.bannerVisible = false;
        console.log('Banner ad hidden');
      }
    } catch (error) {
      console.error('Hide banner failed:', error);
    }
  }
  
  async removeBanner(): Promise<void> {
    try {
      if (this.bannerVisible) {
        await AdMob.removeBanner();
        this.bannerVisible = false;
        console.log('Banner ad removed');
      }
    } catch (error) {
      console.error('Remove banner failed:', error);
    }
  }
  
  // Interstitial ad management
  async prepareInterstitial(): Promise<void> {
    try {
      await AdMob.prepareInterstitial(this.adConfig);
      this.interstitialReady = true;
      console.log('Interstitial ad prepared');
    } catch (error) {
      console.error('Interstitial preparation failed:', error);
      this.interstitialReady = false;
    }
  }
  
  async showInterstitial(): Promise<boolean> {
    try {
      if (!this.interstitialReady) {
        console.log('Interstitial not ready, preparing...');
        await this.prepareInterstitial();
      }
      
      if (this.interstitialReady) {
        await AdMob.showInterstitial();
        this.interstitialReady = false; // Need to prepare again after showing
        
        console.log('Interstitial ad shown');
        
        // Prepare next interstitial
        setTimeout(() => this.prepareInterstitial(), 1000);
        
        return true;
      }
      
      return false;
    } catch (error) {
      console.error('Interstitial ad failed:', error);
      return false;
    }
  }
  
  // Rewarded video ad management
  async prepareRewardVideo(): Promise<void> {
    try {
      await AdMob.prepareRewardVideoAd(this.adConfig);
      this.rewardVideoReady = true;
      console.log('Rewarded video ad prepared');
    } catch (error) {
      console.error('Rewarded video preparation failed:', error);
      this.rewardVideoReady = false;
    }
  }
  
  async showRewardVideo(): Promise<{ success: boolean; reward?: any }> {
    try {
      if (!this.rewardVideoReady) {
        console.log('Rewarded video not ready, preparing...');
        await this.prepareRewardVideo();
      }
      
      if (this.rewardVideoReady) {
        await AdMob.showRewardVideoAd();
        this.rewardVideoReady = false;
        
        console.log('Rewarded video ad shown');
        
        // Prepare next rewarded video
        setTimeout(() => this.prepareRewardVideo(), 1000);
        
        return { success: true, reward: { type: 'coins', amount: 100 } };
      }
      
      return { success: false };
    } catch (error) {
      console.error('Rewarded video ad failed:', error);
      return { success: false };
    }
  }
  
  // Ad availability checks
  isBannerVisible(): boolean {
    return this.bannerVisible;
  }
  
  isInterstitialReady(): boolean {
    return this.interstitialReady;
  }
  
  isRewardVideoReady(): boolean {
    return this.rewardVideoReady;
  }
}

// Smart advertising manager with user experience optimization
class SmartAdManager extends AdvertisingService {
  private adFrequency = {
    interstitial: 3, // Show every 3rd app session
    banner: 5 // Show banner after 5 minutes
  };
  private sessionCount = 0;
  private lastInterstitialShow = 0;
  private bannerTimer: any;
  
  constructor(config: AdMobOptions) {
    super(config);
    this.loadAdState();
  }
  
  async initialize(): Promise<void> {
    await super.initialize();
    this.sessionCount++;
    this.saveAdState();
    
    // Schedule banner ads
    this.scheduleBannerAds();
  }
  
  private loadAdState(): void {
    const saved = localStorage.getItem('ad_state');
    if (saved) {
      const state = JSON.parse(saved);
      this.sessionCount = state.sessionCount || 0;
      this.lastInterstitialShow = state.lastInterstitialShow || 0;
    }
  }
  
  private saveAdState(): void {
    const state = {
      sessionCount: this.sessionCount,
      lastInterstitialShow: this.lastInterstitialShow
    };
    localStorage.setItem('ad_state', JSON.stringify(state));
  }
  
  private scheduleBannerAds(): void {
    // Show banner after delay, but not immediately on app start
    this.bannerTimer = setTimeout(() => {
      this.showBanner('bottom');
    }, this.adFrequency.banner * 60 * 1000); // Convert minutes to milliseconds
  }
  
  async showInterstitialIfAppropriate(context: string = 'general'): Promise<boolean> {
    // Don't show interstitials too frequently
    const timeSinceLastAd = Date.now() - this.lastInterstitialShow;
    const minInterval = 5 * 60 * 1000; // 5 minutes minimum
    
    if (timeSinceLastAd < minInterval) {
      console.log('Interstitial skipped - too soon since last ad');
      return false;
    }
    
    // Show based on session frequency
    if (this.sessionCount % this.adFrequency.interstitial === 0) {
      const shown = await this.showInterstitial();
      
      if (shown) {
        this.lastInterstitialShow = Date.now();
        this.saveAdState();
        
        // Track ad impression
        this.trackAdEvent('interstitial', 'shown', context);
      }
      
      return shown;
    }
    
    return false;
  }
  
  async offerRewardVideo(rewardType: string, rewardAmount: number): Promise<{ accepted: boolean; reward?: any }> {
    if (!this.isRewardVideoReady()) {
      return { accepted: false };
    }
    
    // Show user a dialog to offer the reward
    const userAccepted = await this.showRewardOfferDialog(rewardType, rewardAmount);
    
    if (userAccepted) {
      const result = await this.showRewardVideo();
      
      if (result.success) {
        // Grant reward to user
        const reward = { type: rewardType, amount: rewardAmount };
        await this.grantReward(reward);
        
        this.trackAdEvent('reward_video', 'completed', rewardType);
        
        return { accepted: true, reward };
      }
    }
    
    return { accepted: false };
  }
  
  private async showRewardOfferDialog(rewardType: string, amount: number): Promise<boolean> {
    return new Promise((resolve) => {
      // Show custom dialog (implement with your UI framework)
      const dialog = document.createElement('div');
      dialog.innerHTML = `
        <div class="reward-offer-dialog">
          <h3>Free Reward!</h3>
          <p>Watch a short video to earn ${amount} ${rewardType}</p>
          <button id="accept-reward">Watch Video</button>
          <button id="decline-reward">No Thanks</button>
        </div>
      `;
      
      document.body.appendChild(dialog);
      
      dialog.querySelector('#accept-reward')?.addEventListener('click', () => {
        dialog.remove();
        resolve(true);
      });
      
      dialog.querySelector('#decline-reward')?.addEventListener('click', () => {
        dialog.remove();
        resolve(false);
      });
    });
  }
  
  private async grantReward(reward: { type: string; amount: number }): Promise<void> {
    // Implement reward granting logic
    console.log('Granting reward:', reward);
    
    // Example: Add coins to user balance
    const currentBalance = parseInt(localStorage.getItem('user_coins') || '0');
    localStorage.setItem('user_coins', (currentBalance + reward.amount).toString());
  }
  
  private trackAdEvent(adType: string, action: string, context?: string): void {
    // Track ad events for analytics
    console.log('Ad event:', { adType, action, context });
    
    // Example: Send to analytics service
    // analytics.trackEvent('Advertising', action, `${adType}_${context}`);
  }
  
  destroy(): void {
    if (this.bannerTimer) {
      clearTimeout(this.bannerTimer);
    }
    
    this.removeBanner();
    this.saveAdState();
  }
}

Mixpanel Analytics

Advanced user analytics and engagement tracking with Mixpanel integration.

/**
 * Mixpanel class for advanced user analytics
 */
class Mixpanel {
  /**
   * Initialize Mixpanel with project token
   * @param token Mixpanel project token
   * @returns Promise indicating initialization completion
   */
  static init(token: string): Promise<any>;

  /**
   * Track custom event
   * @param eventName Name of the event
   * @param eventProperties Event properties object (optional)
   * @returns Promise indicating tracking completion
   */
  static track(eventName: string, eventProperties?: any): Promise<any>;

  /**
   * Flush pending events to server
   * @returns Promise indicating flush completion
   */
  static flush(): Promise<any>;

  /**
   * Identify user with unique ID
   * @param distinctId Unique user identifier
   * @returns Promise indicating identification completion
   */
  static identify(distinctId: string): Promise<any>;

  /**
   * Create alias for user identification
   * @param aliasId Alias identifier
   * @param originalId Original user identifier
   * @returns Promise indicating alias creation completion
   */
  static alias(aliasId: string, originalId: string): Promise<any>;

  /**
   * Get current distinct ID
   * @returns Promise resolving to distinct ID
   */
  static distinctId(): Promise<string>;

  /**
   * Register super properties (sent with every event)
   * @param superProperties Properties to register
   * @returns Promise indicating registration completion
   */
  static registerSuperProperties(superProperties: any): Promise<any>;

  /**
   * Reset Mixpanel data
   * @returns Promise indicating reset completion
   */
  static reset(): Promise<any>;

  /**
   * Show in-app survey
   * @returns Promise indicating survey display completion
   */
  static showSurvey(): Promise<any>;
}

Usage Examples:

import { Mixpanel } from 'ionic-native';

// Advanced user analytics service
class UserAnalyticsService {
  private isInitialized = false;
  private userId: string | null = null;
  
  async initialize(projectToken: string): Promise<void> {
    try {
      await Mixpanel.init(projectToken);
      
      // Set up super properties that go with every event
      await Mixpanel.registerSuperProperties({
        'App Version': '1.0.0',
        'Platform': Device.platform,
        'Device Model': Device.model,
        'OS Version': Device.version
      });
      
      this.isInitialized = true;
      console.log('Mixpanel initialized');
      
      // Track app open
      await this.trackEvent('App Opened');
    } catch (error) {
      console.error('Mixpanel initialization failed:', error);
    }
  }
  
  async identifyUser(userId: string, userProperties?: any): Promise<void> {
    if (!this.isInitialized) return;
    
    try {
      await Mixpanel.identify(userId);
      this.userId = userId;
      
      if (userProperties) {
        // Set user properties as super properties
        await Mixpanel.registerSuperProperties({
          'User Type': userProperties.type,
          'Subscription': userProperties.subscription,
          'Registration Date': userProperties.registrationDate,
          'Language': userProperties.language
        });
      }
      
      console.log('User identified:', userId);
    } catch (error) {
      console.error('User identification failed:', error);
    }
  }
  
  async trackEvent(eventName: string, properties?: any): Promise<void> {
    if (!this.isInitialized) return;
    
    try {
      const eventProperties = {
        ...properties,
        'Timestamp': new Date().toISOString(),
        'User ID': this.userId
      };
      
      await Mixpanel.track(eventName, eventProperties);
      console.log('Event tracked:', eventName, eventProperties);
    } catch (error) {
      console.error('Event tracking failed:', error);
    }
  }
  
  // User journey tracking
  async trackUserJourney(step: string, details?: any): Promise<void> {
    await this.trackEvent('User Journey Step', {
      'Step': step,
      'Details': details,
      'Session Duration': this.getSessionDuration()
    });
  }
  
  // Feature usage tracking
  async trackFeatureUsage(featureName: string, action: string, metadata?: any): Promise<void> {
    await this.trackEvent('Feature Used', {
      'Feature': featureName,
      'Action': action,
      'Metadata': metadata
    });
  }
  
  // Conversion tracking
  async trackConversion(conversionType: string, value?: number, currency?: string): Promise<void> {
    await this.trackEvent('Conversion', {
      'Type': conversionType,
      'Value': value,
      'Currency': currency,
      'Conversion Time': new Date().toISOString()
    });
  }
  
  // Engagement tracking
  async trackEngagement(engagementType: string, duration?: number): Promise<void> {
    await this.trackEvent('User Engagement', {
      'Type': engagementType,
      'Duration': duration,
      'Session Count': this.getSessionCount()
    });
  }
  
  // Error tracking
  async trackError(error: Error, context?: string): Promise<void> {
    await this.trackEvent('Error Occurred', {
      'Error Name': error.name,
      'Error Message': error.message,
      'Stack Trace': error.stack,
      'Context': context,
      'User Agent': navigator.userAgent
    });
  }
  
  // Performance tracking
  async trackPerformance(metric: string, value: number, unit: string): Promise<void> {
    await this.trackEvent('Performance Metric', {
      'Metric': metric,
      'Value': value,
      'Unit': unit,
      'Device Memory': (navigator as any).deviceMemory || 'unknown',
      'Connection Type': (navigator as any).connection?.effectiveType || 'unknown'
    });
  }
  
  private getSessionDuration(): number {
    const sessionStart = parseInt(sessionStorage.getItem('session_start') || '0');
    return sessionStart ? Date.now() - sessionStart : 0;
  }
  
  private getSessionCount(): number {
    return parseInt(localStorage.getItem('session_count') || '0');
  }
  
  async flushEvents(): Promise<void> {
    if (!this.isInitialized) return;
    
    try {
      await Mixpanel.flush();
      console.log('Mixpanel events flushed');
    } catch (error) {
      console.error('Event flush failed:', error);
    }
  }
  
  async resetUserData(): Promise<void> {
    if (!this.isInitialized) return;
    
    try {
      await Mixpanel.reset();
      this.userId = null;
      console.log('Mixpanel data reset');
    } catch (error) {
      console.error('Data reset failed:', error);
    }
  }
}

// Complete analytics and monetization manager
class AnalyticsMonetizationManager {
  private analytics: SmartAnalytics;
  private userAnalytics: UserAnalyticsService;
  private adManager: SmartAdManager;
  
  constructor(config: {
    googleAnalyticsId: string;
    mixpanelToken: string;
    adMobConfig: AdMobOptions;
  }) {
    this.analytics = new SmartAnalytics();
    this.userAnalytics = new UserAnalyticsService();
    this.adManager = new SmartAdManager(config.adMobConfig);
  }
  
  async initialize(userInfo?: any): Promise<void> {
    // Initialize all services
    await Promise.all([
      this.analytics.initialize('GA123456789'), // Replace with actual ID
      this.userAnalytics.initialize('mixpanel_token_here'), // Replace with actual token
      this.adManager.initialize()
    ]);
    
    if (userInfo) {
      await this.identifyUser(userInfo.id, userInfo);
    }
    
    console.log('Analytics and monetization initialized');
  }
  
  async identifyUser(userId: string, userProperties?: any): Promise<void> {
    await this.userAnalytics.identifyUser(userId, userProperties);
  }
  
  async trackPageView(page: string, data?: any): Promise<void> {
    await Promise.all([
      this.analytics.trackPageView(page, data),
      this.userAnalytics.trackUserJourney(page, data)
    ]);
  }
  
  async trackEvent(category: string, action: string, label?: string, value?: number): Promise<void> {
    await Promise.all([
      this.analytics.trackEvent(category, action, label, value),
      this.userAnalytics.trackEvent(`${category} - ${action}`, { label, value })
    ]);
  }
  
  async trackPurchase(transaction: any): Promise<void> {
    await Promise.all([
      this.analytics.trackPurchase(transaction),
      this.userAnalytics.trackConversion('purchase', transaction.revenue, transaction.currency)
    ]);
  }
  
  async showInterstitialAd(context: string): Promise<boolean> {
    const shown = await this.adManager.showInterstitialIfAppropriate(context);
    
    if (shown) {
      await this.trackEvent('Monetization', 'Interstitial Shown', context);
    }
    
    return shown;
  }
  
  async offerRewardedVideo(rewardType: string, amount: number): Promise<any> {
    const result = await this.adManager.offerRewardVideo(rewardType, amount);
    
    if (result.accepted) {
      await this.trackEvent('Monetization', 'Reward Video Completed', rewardType, amount);
    }
    
    return result;
  }
  
  async trackError(error: Error, context?: string): Promise<void> {
    await Promise.all([
      this.analytics.trackError(error, false),
      this.userAnalytics.trackError(error, context)
    ]);
  }
  
  async endSession(): Promise<void> {
    await Promise.all([
      this.analytics.endSession(),
      this.userAnalytics.flushEvents()
    ]);
    
    this.adManager.destroy();
  }
}

// Usage example
const analyticsManager = new AnalyticsMonetizationManager({
  googleAnalyticsId: 'UA-XXXXXXXXX-X',
  mixpanelToken: 'your_mixpanel_project_token',
  adMobConfig: {
    bannerId: 'ca-app-pub-XXXXXXXXXXXXXXXX/XXXXXXXXXX',
    interstitialId: 'ca-app-pub-XXXXXXXXXXXXXXXX/XXXXXXXXXX',
    rewardVideoId: 'ca-app-pub-XXXXXXXXXXXXXXXX/XXXXXXXXXX',
    isTesting: true // Set to false in production
  }
});

Stripe Payment Processing

Stripe payment processing with native SDKs for secure credit card tokenization and payments.

/**
 * Stripe card token parameters for creating payment tokens
 */
interface StripeCardTokenParams {
  /** Card number */
  number: string;
  /** Expiry month */
  expMonth: number;
  /** Expiry year */
  expYear: number;
  /** CVC / CVV code */
  cvc?: string;
  /** Cardholder name */
  name?: string;
  /** Address line 1 */
  address_line1?: string;
  /** Address line 2 */
  address_line2?: string;
  /** City */
  address_city?: string;
  /** State / Province */
  address_state?: string;
  /** Country */
  address_country?: string;
  /** Postal code / ZIP Code */
  postal_code?: string;
  /** 3-letter ISO code for currency */
  currency?: string;
}

/**
 * Stripe payment processing class
 */
class Stripe {
  /**
   * Set publishable key for Stripe operations
   * @param publishableKey Stripe publishable key
   * @returns Promise indicating key setup completion
   */
  static setPublishableKey(publishableKey: string): Promise<void>;

  /**
   * Create credit card token for secure payment processing
   * @param params Credit card information and billing details
   * @returns Promise that resolves with payment token
   */
  static createCardToken(params: StripeCardTokenParams): Promise<string>;
}

Usage Examples:

import { Stripe, StripeCardTokenParams } from 'ionic-native';

// Initialize Stripe with publishable key
await Stripe.setPublishableKey('pk_test_XXXXXXXXXXXXXXXXXXXXXXXXXX');

// Create payment token from card details
const cardParams: StripeCardTokenParams = {
  number: '4242424242424242',
  expMonth: 12,
  expYear: 2025,
  cvc: '123',
  name: 'John Doe',
  address_line1: '123 Main St',
  address_city: 'San Francisco',
  address_state: 'CA',
  postal_code: '94105',
  address_country: 'US',
  currency: 'usd'
};

try {
  const token = await Stripe.createCardToken(cardParams);
  console.log('Payment token created:', token);
  // Send token to your server for payment processing
} catch (error) {
  console.error('Payment token creation failed:', error);
}

docs

analytics-monetization.md

camera-media.md

device-sensors.md

device-system.md

index.md

input-hardware.md

location-maps.md

network-communication.md

notifications-ui.md

security-auth.md

social-sharing.md

storage-files.md

tile.json