or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

analytics-monetization.mdcamera-media.mddevice-sensors.mddevice-system.mdindex.mdinput-hardware.mdlocation-maps.mdnetwork-communication.mdnotifications-ui.mdsecurity-auth.mdsocial-sharing.mdstorage-files.md
tile.json

analytics-monetization.mddocs/

0

# Analytics & Monetization

1

2

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

3

4

## Capabilities

5

6

### Google Analytics

7

8

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

9

10

```typescript { .api }

11

/**

12

* GoogleAnalytics class for app analytics and tracking

13

*/

14

class GoogleAnalytics {

15

/**

16

* Initialize Google Analytics with tracking ID

17

* @param id Google Analytics tracking ID

18

* @returns Promise indicating initialization completion

19

*/

20

static startTrackerWithId(id: string): Promise<any>;

21

22

/**

23

* Track screen view

24

* @param title Screen or page title

25

* @returns Promise indicating tracking completion

26

*/

27

static trackView(title: string): Promise<any>;

28

29

/**

30

* Track custom event

31

* @param category Event category

32

* @param action Event action

33

* @param label Event label (optional)

34

* @param value Event value (optional)

35

* @returns Promise indicating tracking completion

36

*/

37

static trackEvent(category: string, action: string, label?: string, value?: number): Promise<any>;

38

39

/**

40

* Track exception/error

41

* @param description Exception description

42

* @param fatal Whether exception was fatal

43

* @returns Promise indicating tracking completion

44

*/

45

static trackException(description: string, fatal: boolean): Promise<any>;

46

47

/**

48

* Track timing measurement

49

* @param category Timing category

50

* @param intervalInMilliseconds Duration in milliseconds

51

* @param variable Timing variable name

52

* @param label Timing label

53

* @returns Promise indicating tracking completion

54

*/

55

static trackTiming(category: string, intervalInMilliseconds: number, variable: string, label: string): Promise<any>;

56

57

/**

58

* Add custom dimension

59

* @param key Custom dimension index

60

* @param value Custom dimension value

61

* @returns Promise indicating completion

62

*/

63

static addCustomDimension(key: number, value: string): Promise<any>;

64

65

/**

66

* Add e-commerce transaction

67

* @param transactionId Transaction ID

68

* @param affiliation Store or affiliation

69

* @param revenue Total revenue

70

* @param tax Tax amount

71

* @param shipping Shipping cost

72

* @param currency Currency code

73

* @returns Promise indicating completion

74

*/

75

static addTransaction(transactionId: string, affiliation: string, revenue: number, tax: number, shipping: number, currency: string): Promise<any>;

76

77

/**

78

* Add e-commerce transaction item

79

* @param transactionId Transaction ID

80

* @param name Item name

81

* @param sku Item SKU

82

* @param category Item category

83

* @param price Item price

84

* @param quantity Item quantity

85

* @param currency Currency code

86

* @returns Promise indicating completion

87

*/

88

static addTransactionItem(transactionId: string, name: string, sku: string, category: string, price: number, quantity: number, currency: string): Promise<any>;

89

90

/**

91

* Enable uncaught exception reporting

92

* @param enable Whether to enable exception reporting

93

* @returns Promise indicating completion

94

*/

95

static enableUncaughtExceptionReporting(enable: boolean): Promise<any>;

96

}

97

```

98

99

**Usage Examples:**

100

101

```typescript

102

import { GoogleAnalytics } from 'ionic-native';

103

104

// Analytics service for comprehensive tracking

105

class AnalyticsService {

106

private isInitialized = false;

107

108

async initialize(trackingId: string): Promise<void> {

109

try {

110

await GoogleAnalytics.startTrackerWithId(trackingId);

111

await GoogleAnalytics.enableUncaughtExceptionReporting(true);

112

113

this.isInitialized = true;

114

console.log('Google Analytics initialized');

115

116

// Track app startup

117

this.trackEvent('App', 'Start', 'User opened app');

118

} catch (error) {

119

console.error('Analytics initialization failed:', error);

120

}

121

}

122

123

async trackPageView(pageName: string, additionalData?: any): Promise<void> {

124

if (!this.isInitialized) return;

125

126

try {

127

await GoogleAnalytics.trackView(pageName);

128

129

// Track additional custom dimensions if provided

130

if (additionalData) {

131

await this.setCustomDimensions(additionalData);

132

}

133

134

console.log('Page view tracked:', pageName);

135

} catch (error) {

136

console.error('Page view tracking failed:', error);

137

}

138

}

139

140

async trackEvent(category: string, action: string, label?: string, value?: number): Promise<void> {

141

if (!this.isInitialized) return;

142

143

try {

144

await GoogleAnalytics.trackEvent(category, action, label, value);

145

console.log('Event tracked:', { category, action, label, value });

146

} catch (error) {

147

console.error('Event tracking failed:', error);

148

}

149

}

150

151

async trackUserAction(action: string, details?: any): Promise<void> {

152

await this.trackEvent('User', action, details?.label, details?.value);

153

}

154

155

async trackError(error: Error, isFatal: boolean = false): Promise<void> {

156

if (!this.isInitialized) return;

157

158

try {

159

const description = `${error.name}: ${error.message}`;

160

await GoogleAnalytics.trackException(description, isFatal);

161

console.log('Exception tracked:', description);

162

} catch (trackingError) {

163

console.error('Exception tracking failed:', trackingError);

164

}

165

}

166

167

async trackTiming(category: string, variable: string, timeMs: number, label?: string): Promise<void> {

168

if (!this.isInitialized) return;

169

170

try {

171

await GoogleAnalytics.trackTiming(category, timeMs, variable, label || '');

172

console.log('Timing tracked:', { category, variable, timeMs, label });

173

} catch (error) {

174

console.error('Timing tracking failed:', error);

175

}

176

}

177

178

private async setCustomDimensions(data: { [key: string]: string }): Promise<void> {

179

// Map custom dimensions (configure these in GA dashboard)

180

const dimensionMap: { [key: string]: number } = {

181

userType: 1,

182

appVersion: 2,

183

platform: 3,

184

language: 4

185

};

186

187

for (const [key, value] of Object.entries(data)) {

188

const dimensionIndex = dimensionMap[key];

189

if (dimensionIndex) {

190

await GoogleAnalytics.addCustomDimension(dimensionIndex, value);

191

}

192

}

193

}

194

195

// E-commerce tracking

196

async trackPurchase(transaction: {

197

id: string;

198

affiliation: string;

199

revenue: number;

200

tax?: number;

201

shipping?: number;

202

currency?: string;

203

items: Array<{

204

name: string;

205

sku: string;

206

category: string;

207

price: number;

208

quantity: number;

209

}>;

210

}): Promise<void> {

211

if (!this.isInitialized) return;

212

213

try {

214

// Track main transaction

215

await GoogleAnalytics.addTransaction(

216

transaction.id,

217

transaction.affiliation,

218

transaction.revenue,

219

transaction.tax || 0,

220

transaction.shipping || 0,

221

transaction.currency || 'USD'

222

);

223

224

// Track individual items

225

for (const item of transaction.items) {

226

await GoogleAnalytics.addTransactionItem(

227

transaction.id,

228

item.name,

229

item.sku,

230

item.category,

231

item.price,

232

item.quantity,

233

transaction.currency || 'USD'

234

);

235

}

236

237

console.log('Purchase tracked:', transaction.id);

238

} catch (error) {

239

console.error('Purchase tracking failed:', error);

240

}

241

}

242

}

243

244

// Enhanced analytics with automatic tracking

245

class SmartAnalytics extends AnalyticsService {

246

private sessionStartTime: number = 0;

247

private pageStartTime: number = 0;

248

private userProperties: any = {};

249

250

async initialize(trackingId: string, userProperties?: any): Promise<void> {

251

await super.initialize(trackingId);

252

253

this.sessionStartTime = Date.now();

254

this.userProperties = userProperties || {};

255

256

// Set up automatic tracking

257

this.setupAutomaticTracking();

258

}

259

260

private setupAutomaticTracking(): void {

261

// Track app lifecycle events

262

document.addEventListener('visibilitychange', () => {

263

if (document.hidden) {

264

this.trackEvent('App', 'Background', 'App went to background');

265

} else {

266

this.trackEvent('App', 'Foreground', 'App came to foreground');

267

}

268

});

269

270

// Track unhandled errors

271

window.addEventListener('error', (event) => {

272

this.trackError(new Error(event.message), false);

273

});

274

275

// Track navigation (for SPAs)

276

this.setupNavigationTracking();

277

}

278

279

private setupNavigationTracking(): void {

280

// Track route changes (example for hash-based routing)

281

window.addEventListener('hashchange', () => {

282

const pageName = window.location.hash.substring(1) || 'home';

283

this.trackPageView(pageName);

284

});

285

286

// Track initial page

287

const initialPage = window.location.hash.substring(1) || 'home';

288

this.trackPageView(initialPage);

289

}

290

291

async trackPageView(pageName: string, additionalData?: any): Promise<void> {

292

// Track time on previous page

293

if (this.pageStartTime > 0) {

294

const timeOnPage = Date.now() - this.pageStartTime;

295

await this.trackTiming('Navigation', 'PageTime', timeOnPage, pageName);

296

}

297

298

this.pageStartTime = Date.now();

299

300

// Include user properties in tracking

301

const trackingData = { ...this.userProperties, ...additionalData };

302

await super.trackPageView(pageName, trackingData);

303

}

304

305

async trackUserEngagement(engagementType: string, details?: any): Promise<void> {

306

const engagementEvents = {

307

'scroll_75': { category: 'Engagement', action: 'Scroll', label: '75%' },

308

'time_10s': { category: 'Engagement', action: 'Time', label: '10 seconds' },

309

'time_30s': { category: 'Engagement', action: 'Time', label: '30 seconds' },

310

'time_60s': { category: 'Engagement', action: 'Time', label: '1 minute' },

311

'button_click': { category: 'Engagement', action: 'Click', label: details?.button },

312

'form_submit': { category: 'Engagement', action: 'Submit', label: details?.form }

313

};

314

315

const event = engagementEvents[engagementType];

316

if (event) {

317

await this.trackEvent(event.category, event.action, event.label, details?.value);

318

}

319

}

320

321

async trackPerformanceMetrics(): Promise<void> {

322

if (!window.performance) return;

323

324

const navigation = window.performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming;

325

326

if (navigation) {

327

await this.trackTiming('Performance', 'DOMLoad', navigation.domContentLoadedEventEnd - navigation.domContentLoadedEventStart);

328

await this.trackTiming('Performance', 'PageLoad', navigation.loadEventEnd - navigation.loadEventStart);

329

await this.trackTiming('Performance', 'TTFB', navigation.responseStart - navigation.requestStart);

330

}

331

}

332

333

getSessionDuration(): number {

334

return Date.now() - this.sessionStartTime;

335

}

336

337

async endSession(): Promise<void> {

338

const sessionDuration = this.getSessionDuration();

339

await this.trackTiming('Session', 'Duration', sessionDuration);

340

await this.trackEvent('Session', 'End', 'User ended session');

341

}

342

}

343

```

344

345

### AdMob Integration

346

347

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

348

349

```typescript { .api }

350

/**

351

* AdMob advertising configuration options

352

*/

353

interface AdMobOptions {

354

/** Banner ad unit ID */

355

bannerId?: string;

356

/** Interstitial ad unit ID */

357

interstitialId?: string;

358

/** Rewarded video ad unit ID */

359

rewardVideoId?: string;

360

/** Whether app is in testing mode */

361

isTesting?: boolean;

362

/** Auto-show ads when loaded */

363

autoShow?: boolean;

364

}

365

366

/**

367

* AdMob class for mobile advertising

368

*/

369

class AdMob {

370

/**

371

* Create banner advertisement

372

* @param adIdOrOptions Ad unit ID or configuration options

373

* @returns Promise indicating banner creation completion

374

*/

375

static createBanner(adIdOrOptions: string | AdMobOptions): Promise<any>;

376

377

/**

378

* Remove banner advertisement

379

* @returns Promise indicating banner removal completion

380

*/

381

static removeBanner(): Promise<any>;

382

383

/**

384

* Show banner at specific position

385

* @param position Banner position (1: TOP_CENTER, 2: BOTTOM_CENTER, etc.)

386

* @returns Promise indicating show completion

387

*/

388

static showBanner(position: number): Promise<any>;

389

390

/**

391

* Show banner at specific coordinates

392

* @param x X coordinate

393

* @param y Y coordinate

394

* @returns Promise indicating show completion

395

*/

396

static showBannerAtXY(x: number, y: number): Promise<any>;

397

398

/**

399

* Hide banner advertisement

400

* @returns Promise indicating hide completion

401

*/

402

static hideBanner(): Promise<any>;

403

404

/**

405

* Prepare interstitial advertisement

406

* @param adIdOrOptions Ad unit ID or configuration options

407

* @returns Promise indicating preparation completion

408

*/

409

static prepareInterstitial(adIdOrOptions: string | AdMobOptions): Promise<any>;

410

411

/**

412

* Show interstitial advertisement

413

* @returns Promise indicating show completion

414

*/

415

static showInterstitial(): Promise<any>;

416

417

/**

418

* Prepare rewarded video advertisement

419

* @param adIdOrOptions Ad unit ID or configuration options

420

* @returns Promise indicating preparation completion

421

*/

422

static prepareRewardVideoAd(adIdOrOptions: string | AdMobOptions): Promise<any>;

423

424

/**

425

* Show rewarded video advertisement

426

* @returns Promise indicating show completion

427

*/

428

static showRewardVideoAd(): Promise<any>;

429

}

430

```

431

432

**Usage Examples:**

433

434

```typescript

435

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

436

437

// AdMob advertising service

438

class AdvertisingService {

439

private adConfig: AdMobOptions;

440

private bannerVisible = false;

441

private interstitialReady = false;

442

private rewardVideoReady = false;

443

444

constructor(config: AdMobOptions) {

445

this.adConfig = config;

446

}

447

448

async initialize(): Promise<void> {

449

try {

450

console.log('Initializing AdMob with config:', this.adConfig);

451

452

// Pre-load interstitial ad

453

await this.prepareInterstitial();

454

455

// Pre-load rewarded video

456

await this.prepareRewardVideo();

457

458

console.log('AdMob initialized successfully');

459

} catch (error) {

460

console.error('AdMob initialization failed:', error);

461

}

462

}

463

464

// Banner ad management

465

async showBanner(position: 'top' | 'bottom' = 'bottom'): Promise<void> {

466

try {

467

if (this.bannerVisible) {

468

await this.hideBanner();

469

}

470

471

await AdMob.createBanner(this.adConfig);

472

473

const positionCode = position === 'top' ? 1 : 2; // TOP_CENTER : BOTTOM_CENTER

474

await AdMob.showBanner(positionCode);

475

476

this.bannerVisible = true;

477

console.log('Banner ad shown at:', position);

478

} catch (error) {

479

console.error('Banner ad failed:', error);

480

}

481

}

482

483

async hideBanner(): Promise<void> {

484

try {

485

if (this.bannerVisible) {

486

await AdMob.hideBanner();

487

this.bannerVisible = false;

488

console.log('Banner ad hidden');

489

}

490

} catch (error) {

491

console.error('Hide banner failed:', error);

492

}

493

}

494

495

async removeBanner(): Promise<void> {

496

try {

497

if (this.bannerVisible) {

498

await AdMob.removeBanner();

499

this.bannerVisible = false;

500

console.log('Banner ad removed');

501

}

502

} catch (error) {

503

console.error('Remove banner failed:', error);

504

}

505

}

506

507

// Interstitial ad management

508

async prepareInterstitial(): Promise<void> {

509

try {

510

await AdMob.prepareInterstitial(this.adConfig);

511

this.interstitialReady = true;

512

console.log('Interstitial ad prepared');

513

} catch (error) {

514

console.error('Interstitial preparation failed:', error);

515

this.interstitialReady = false;

516

}

517

}

518

519

async showInterstitial(): Promise<boolean> {

520

try {

521

if (!this.interstitialReady) {

522

console.log('Interstitial not ready, preparing...');

523

await this.prepareInterstitial();

524

}

525

526

if (this.interstitialReady) {

527

await AdMob.showInterstitial();

528

this.interstitialReady = false; // Need to prepare again after showing

529

530

console.log('Interstitial ad shown');

531

532

// Prepare next interstitial

533

setTimeout(() => this.prepareInterstitial(), 1000);

534

535

return true;

536

}

537

538

return false;

539

} catch (error) {

540

console.error('Interstitial ad failed:', error);

541

return false;

542

}

543

}

544

545

// Rewarded video ad management

546

async prepareRewardVideo(): Promise<void> {

547

try {

548

await AdMob.prepareRewardVideoAd(this.adConfig);

549

this.rewardVideoReady = true;

550

console.log('Rewarded video ad prepared');

551

} catch (error) {

552

console.error('Rewarded video preparation failed:', error);

553

this.rewardVideoReady = false;

554

}

555

}

556

557

async showRewardVideo(): Promise<{ success: boolean; reward?: any }> {

558

try {

559

if (!this.rewardVideoReady) {

560

console.log('Rewarded video not ready, preparing...');

561

await this.prepareRewardVideo();

562

}

563

564

if (this.rewardVideoReady) {

565

await AdMob.showRewardVideoAd();

566

this.rewardVideoReady = false;

567

568

console.log('Rewarded video ad shown');

569

570

// Prepare next rewarded video

571

setTimeout(() => this.prepareRewardVideo(), 1000);

572

573

return { success: true, reward: { type: 'coins', amount: 100 } };

574

}

575

576

return { success: false };

577

} catch (error) {

578

console.error('Rewarded video ad failed:', error);

579

return { success: false };

580

}

581

}

582

583

// Ad availability checks

584

isBannerVisible(): boolean {

585

return this.bannerVisible;

586

}

587

588

isInterstitialReady(): boolean {

589

return this.interstitialReady;

590

}

591

592

isRewardVideoReady(): boolean {

593

return this.rewardVideoReady;

594

}

595

}

596

597

// Smart advertising manager with user experience optimization

598

class SmartAdManager extends AdvertisingService {

599

private adFrequency = {

600

interstitial: 3, // Show every 3rd app session

601

banner: 5 // Show banner after 5 minutes

602

};

603

private sessionCount = 0;

604

private lastInterstitialShow = 0;

605

private bannerTimer: any;

606

607

constructor(config: AdMobOptions) {

608

super(config);

609

this.loadAdState();

610

}

611

612

async initialize(): Promise<void> {

613

await super.initialize();

614

this.sessionCount++;

615

this.saveAdState();

616

617

// Schedule banner ads

618

this.scheduleBannerAds();

619

}

620

621

private loadAdState(): void {

622

const saved = localStorage.getItem('ad_state');

623

if (saved) {

624

const state = JSON.parse(saved);

625

this.sessionCount = state.sessionCount || 0;

626

this.lastInterstitialShow = state.lastInterstitialShow || 0;

627

}

628

}

629

630

private saveAdState(): void {

631

const state = {

632

sessionCount: this.sessionCount,

633

lastInterstitialShow: this.lastInterstitialShow

634

};

635

localStorage.setItem('ad_state', JSON.stringify(state));

636

}

637

638

private scheduleBannerAds(): void {

639

// Show banner after delay, but not immediately on app start

640

this.bannerTimer = setTimeout(() => {

641

this.showBanner('bottom');

642

}, this.adFrequency.banner * 60 * 1000); // Convert minutes to milliseconds

643

}

644

645

async showInterstitialIfAppropriate(context: string = 'general'): Promise<boolean> {

646

// Don't show interstitials too frequently

647

const timeSinceLastAd = Date.now() - this.lastInterstitialShow;

648

const minInterval = 5 * 60 * 1000; // 5 minutes minimum

649

650

if (timeSinceLastAd < minInterval) {

651

console.log('Interstitial skipped - too soon since last ad');

652

return false;

653

}

654

655

// Show based on session frequency

656

if (this.sessionCount % this.adFrequency.interstitial === 0) {

657

const shown = await this.showInterstitial();

658

659

if (shown) {

660

this.lastInterstitialShow = Date.now();

661

this.saveAdState();

662

663

// Track ad impression

664

this.trackAdEvent('interstitial', 'shown', context);

665

}

666

667

return shown;

668

}

669

670

return false;

671

}

672

673

async offerRewardVideo(rewardType: string, rewardAmount: number): Promise<{ accepted: boolean; reward?: any }> {

674

if (!this.isRewardVideoReady()) {

675

return { accepted: false };

676

}

677

678

// Show user a dialog to offer the reward

679

const userAccepted = await this.showRewardOfferDialog(rewardType, rewardAmount);

680

681

if (userAccepted) {

682

const result = await this.showRewardVideo();

683

684

if (result.success) {

685

// Grant reward to user

686

const reward = { type: rewardType, amount: rewardAmount };

687

await this.grantReward(reward);

688

689

this.trackAdEvent('reward_video', 'completed', rewardType);

690

691

return { accepted: true, reward };

692

}

693

}

694

695

return { accepted: false };

696

}

697

698

private async showRewardOfferDialog(rewardType: string, amount: number): Promise<boolean> {

699

return new Promise((resolve) => {

700

// Show custom dialog (implement with your UI framework)

701

const dialog = document.createElement('div');

702

dialog.innerHTML = `

703

<div class="reward-offer-dialog">

704

<h3>Free Reward!</h3>

705

<p>Watch a short video to earn ${amount} ${rewardType}</p>

706

<button id="accept-reward">Watch Video</button>

707

<button id="decline-reward">No Thanks</button>

708

</div>

709

`;

710

711

document.body.appendChild(dialog);

712

713

dialog.querySelector('#accept-reward')?.addEventListener('click', () => {

714

dialog.remove();

715

resolve(true);

716

});

717

718

dialog.querySelector('#decline-reward')?.addEventListener('click', () => {

719

dialog.remove();

720

resolve(false);

721

});

722

});

723

}

724

725

private async grantReward(reward: { type: string; amount: number }): Promise<void> {

726

// Implement reward granting logic

727

console.log('Granting reward:', reward);

728

729

// Example: Add coins to user balance

730

const currentBalance = parseInt(localStorage.getItem('user_coins') || '0');

731

localStorage.setItem('user_coins', (currentBalance + reward.amount).toString());

732

}

733

734

private trackAdEvent(adType: string, action: string, context?: string): void {

735

// Track ad events for analytics

736

console.log('Ad event:', { adType, action, context });

737

738

// Example: Send to analytics service

739

// analytics.trackEvent('Advertising', action, `${adType}_${context}`);

740

}

741

742

destroy(): void {

743

if (this.bannerTimer) {

744

clearTimeout(this.bannerTimer);

745

}

746

747

this.removeBanner();

748

this.saveAdState();

749

}

750

}

751

```

752

753

### Mixpanel Analytics

754

755

Advanced user analytics and engagement tracking with Mixpanel integration.

756

757

```typescript { .api }

758

/**

759

* Mixpanel class for advanced user analytics

760

*/

761

class Mixpanel {

762

/**

763

* Initialize Mixpanel with project token

764

* @param token Mixpanel project token

765

* @returns Promise indicating initialization completion

766

*/

767

static init(token: string): Promise<any>;

768

769

/**

770

* Track custom event

771

* @param eventName Name of the event

772

* @param eventProperties Event properties object (optional)

773

* @returns Promise indicating tracking completion

774

*/

775

static track(eventName: string, eventProperties?: any): Promise<any>;

776

777

/**

778

* Flush pending events to server

779

* @returns Promise indicating flush completion

780

*/

781

static flush(): Promise<any>;

782

783

/**

784

* Identify user with unique ID

785

* @param distinctId Unique user identifier

786

* @returns Promise indicating identification completion

787

*/

788

static identify(distinctId: string): Promise<any>;

789

790

/**

791

* Create alias for user identification

792

* @param aliasId Alias identifier

793

* @param originalId Original user identifier

794

* @returns Promise indicating alias creation completion

795

*/

796

static alias(aliasId: string, originalId: string): Promise<any>;

797

798

/**

799

* Get current distinct ID

800

* @returns Promise resolving to distinct ID

801

*/

802

static distinctId(): Promise<string>;

803

804

/**

805

* Register super properties (sent with every event)

806

* @param superProperties Properties to register

807

* @returns Promise indicating registration completion

808

*/

809

static registerSuperProperties(superProperties: any): Promise<any>;

810

811

/**

812

* Reset Mixpanel data

813

* @returns Promise indicating reset completion

814

*/

815

static reset(): Promise<any>;

816

817

/**

818

* Show in-app survey

819

* @returns Promise indicating survey display completion

820

*/

821

static showSurvey(): Promise<any>;

822

}

823

```

824

825

**Usage Examples:**

826

827

```typescript

828

import { Mixpanel } from 'ionic-native';

829

830

// Advanced user analytics service

831

class UserAnalyticsService {

832

private isInitialized = false;

833

private userId: string | null = null;

834

835

async initialize(projectToken: string): Promise<void> {

836

try {

837

await Mixpanel.init(projectToken);

838

839

// Set up super properties that go with every event

840

await Mixpanel.registerSuperProperties({

841

'App Version': '1.0.0',

842

'Platform': Device.platform,

843

'Device Model': Device.model,

844

'OS Version': Device.version

845

});

846

847

this.isInitialized = true;

848

console.log('Mixpanel initialized');

849

850

// Track app open

851

await this.trackEvent('App Opened');

852

} catch (error) {

853

console.error('Mixpanel initialization failed:', error);

854

}

855

}

856

857

async identifyUser(userId: string, userProperties?: any): Promise<void> {

858

if (!this.isInitialized) return;

859

860

try {

861

await Mixpanel.identify(userId);

862

this.userId = userId;

863

864

if (userProperties) {

865

// Set user properties as super properties

866

await Mixpanel.registerSuperProperties({

867

'User Type': userProperties.type,

868

'Subscription': userProperties.subscription,

869

'Registration Date': userProperties.registrationDate,

870

'Language': userProperties.language

871

});

872

}

873

874

console.log('User identified:', userId);

875

} catch (error) {

876

console.error('User identification failed:', error);

877

}

878

}

879

880

async trackEvent(eventName: string, properties?: any): Promise<void> {

881

if (!this.isInitialized) return;

882

883

try {

884

const eventProperties = {

885

...properties,

886

'Timestamp': new Date().toISOString(),

887

'User ID': this.userId

888

};

889

890

await Mixpanel.track(eventName, eventProperties);

891

console.log('Event tracked:', eventName, eventProperties);

892

} catch (error) {

893

console.error('Event tracking failed:', error);

894

}

895

}

896

897

// User journey tracking

898

async trackUserJourney(step: string, details?: any): Promise<void> {

899

await this.trackEvent('User Journey Step', {

900

'Step': step,

901

'Details': details,

902

'Session Duration': this.getSessionDuration()

903

});

904

}

905

906

// Feature usage tracking

907

async trackFeatureUsage(featureName: string, action: string, metadata?: any): Promise<void> {

908

await this.trackEvent('Feature Used', {

909

'Feature': featureName,

910

'Action': action,

911

'Metadata': metadata

912

});

913

}

914

915

// Conversion tracking

916

async trackConversion(conversionType: string, value?: number, currency?: string): Promise<void> {

917

await this.trackEvent('Conversion', {

918

'Type': conversionType,

919

'Value': value,

920

'Currency': currency,

921

'Conversion Time': new Date().toISOString()

922

});

923

}

924

925

// Engagement tracking

926

async trackEngagement(engagementType: string, duration?: number): Promise<void> {

927

await this.trackEvent('User Engagement', {

928

'Type': engagementType,

929

'Duration': duration,

930

'Session Count': this.getSessionCount()

931

});

932

}

933

934

// Error tracking

935

async trackError(error: Error, context?: string): Promise<void> {

936

await this.trackEvent('Error Occurred', {

937

'Error Name': error.name,

938

'Error Message': error.message,

939

'Stack Trace': error.stack,

940

'Context': context,

941

'User Agent': navigator.userAgent

942

});

943

}

944

945

// Performance tracking

946

async trackPerformance(metric: string, value: number, unit: string): Promise<void> {

947

await this.trackEvent('Performance Metric', {

948

'Metric': metric,

949

'Value': value,

950

'Unit': unit,

951

'Device Memory': (navigator as any).deviceMemory || 'unknown',

952

'Connection Type': (navigator as any).connection?.effectiveType || 'unknown'

953

});

954

}

955

956

private getSessionDuration(): number {

957

const sessionStart = parseInt(sessionStorage.getItem('session_start') || '0');

958

return sessionStart ? Date.now() - sessionStart : 0;

959

}

960

961

private getSessionCount(): number {

962

return parseInt(localStorage.getItem('session_count') || '0');

963

}

964

965

async flushEvents(): Promise<void> {

966

if (!this.isInitialized) return;

967

968

try {

969

await Mixpanel.flush();

970

console.log('Mixpanel events flushed');

971

} catch (error) {

972

console.error('Event flush failed:', error);

973

}

974

}

975

976

async resetUserData(): Promise<void> {

977

if (!this.isInitialized) return;

978

979

try {

980

await Mixpanel.reset();

981

this.userId = null;

982

console.log('Mixpanel data reset');

983

} catch (error) {

984

console.error('Data reset failed:', error);

985

}

986

}

987

}

988

989

// Complete analytics and monetization manager

990

class AnalyticsMonetizationManager {

991

private analytics: SmartAnalytics;

992

private userAnalytics: UserAnalyticsService;

993

private adManager: SmartAdManager;

994

995

constructor(config: {

996

googleAnalyticsId: string;

997

mixpanelToken: string;

998

adMobConfig: AdMobOptions;

999

}) {

1000

this.analytics = new SmartAnalytics();

1001

this.userAnalytics = new UserAnalyticsService();

1002

this.adManager = new SmartAdManager(config.adMobConfig);

1003

}

1004

1005

async initialize(userInfo?: any): Promise<void> {

1006

// Initialize all services

1007

await Promise.all([

1008

this.analytics.initialize('GA123456789'), // Replace with actual ID

1009

this.userAnalytics.initialize('mixpanel_token_here'), // Replace with actual token

1010

this.adManager.initialize()

1011

]);

1012

1013

if (userInfo) {

1014

await this.identifyUser(userInfo.id, userInfo);

1015

}

1016

1017

console.log('Analytics and monetization initialized');

1018

}

1019

1020

async identifyUser(userId: string, userProperties?: any): Promise<void> {

1021

await this.userAnalytics.identifyUser(userId, userProperties);

1022

}

1023

1024

async trackPageView(page: string, data?: any): Promise<void> {

1025

await Promise.all([

1026

this.analytics.trackPageView(page, data),

1027

this.userAnalytics.trackUserJourney(page, data)

1028

]);

1029

}

1030

1031

async trackEvent(category: string, action: string, label?: string, value?: number): Promise<void> {

1032

await Promise.all([

1033

this.analytics.trackEvent(category, action, label, value),

1034

this.userAnalytics.trackEvent(`${category} - ${action}`, { label, value })

1035

]);

1036

}

1037

1038

async trackPurchase(transaction: any): Promise<void> {

1039

await Promise.all([

1040

this.analytics.trackPurchase(transaction),

1041

this.userAnalytics.trackConversion('purchase', transaction.revenue, transaction.currency)

1042

]);

1043

}

1044

1045

async showInterstitialAd(context: string): Promise<boolean> {

1046

const shown = await this.adManager.showInterstitialIfAppropriate(context);

1047

1048

if (shown) {

1049

await this.trackEvent('Monetization', 'Interstitial Shown', context);

1050

}

1051

1052

return shown;

1053

}

1054

1055

async offerRewardedVideo(rewardType: string, amount: number): Promise<any> {

1056

const result = await this.adManager.offerRewardVideo(rewardType, amount);

1057

1058

if (result.accepted) {

1059

await this.trackEvent('Monetization', 'Reward Video Completed', rewardType, amount);

1060

}

1061

1062

return result;

1063

}

1064

1065

async trackError(error: Error, context?: string): Promise<void> {

1066

await Promise.all([

1067

this.analytics.trackError(error, false),

1068

this.userAnalytics.trackError(error, context)

1069

]);

1070

}

1071

1072

async endSession(): Promise<void> {

1073

await Promise.all([

1074

this.analytics.endSession(),

1075

this.userAnalytics.flushEvents()

1076

]);

1077

1078

this.adManager.destroy();

1079

}

1080

}

1081

1082

// Usage example

1083

const analyticsManager = new AnalyticsMonetizationManager({

1084

googleAnalyticsId: 'UA-XXXXXXXXX-X',

1085

mixpanelToken: 'your_mixpanel_project_token',

1086

adMobConfig: {

1087

bannerId: 'ca-app-pub-XXXXXXXXXXXXXXXX/XXXXXXXXXX',

1088

interstitialId: 'ca-app-pub-XXXXXXXXXXXXXXXX/XXXXXXXXXX',

1089

rewardVideoId: 'ca-app-pub-XXXXXXXXXXXXXXXX/XXXXXXXXXX',

1090

isTesting: true // Set to false in production

1091

}

1092

});

1093

```

1094

1095

### Stripe Payment Processing

1096

1097

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

1098

1099

```typescript { .api }

1100

/**

1101

* Stripe card token parameters for creating payment tokens

1102

*/

1103

interface StripeCardTokenParams {

1104

/** Card number */

1105

number: string;

1106

/** Expiry month */

1107

expMonth: number;

1108

/** Expiry year */

1109

expYear: number;

1110

/** CVC / CVV code */

1111

cvc?: string;

1112

/** Cardholder name */

1113

name?: string;

1114

/** Address line 1 */

1115

address_line1?: string;

1116

/** Address line 2 */

1117

address_line2?: string;

1118

/** City */

1119

address_city?: string;

1120

/** State / Province */

1121

address_state?: string;

1122

/** Country */

1123

address_country?: string;

1124

/** Postal code / ZIP Code */

1125

postal_code?: string;

1126

/** 3-letter ISO code for currency */

1127

currency?: string;

1128

}

1129

1130

/**

1131

* Stripe payment processing class

1132

*/

1133

class Stripe {

1134

/**

1135

* Set publishable key for Stripe operations

1136

* @param publishableKey Stripe publishable key

1137

* @returns Promise indicating key setup completion

1138

*/

1139

static setPublishableKey(publishableKey: string): Promise<void>;

1140

1141

/**

1142

* Create credit card token for secure payment processing

1143

* @param params Credit card information and billing details

1144

* @returns Promise that resolves with payment token

1145

*/

1146

static createCardToken(params: StripeCardTokenParams): Promise<string>;

1147

}

1148

```

1149

1150

**Usage Examples:**

1151

1152

```typescript

1153

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

1154

1155

// Initialize Stripe with publishable key

1156

await Stripe.setPublishableKey('pk_test_XXXXXXXXXXXXXXXXXXXXXXXXXX');

1157

1158

// Create payment token from card details

1159

const cardParams: StripeCardTokenParams = {

1160

number: '4242424242424242',

1161

expMonth: 12,

1162

expYear: 2025,

1163

cvc: '123',

1164

name: 'John Doe',

1165

address_line1: '123 Main St',

1166

address_city: 'San Francisco',

1167

address_state: 'CA',

1168

postal_code: '94105',

1169

address_country: 'US',

1170

currency: 'usd'

1171

};

1172

1173

try {

1174

const token = await Stripe.createCardToken(cardParams);

1175

console.log('Payment token created:', token);

1176

// Send token to your server for payment processing

1177

} catch (error) {

1178

console.error('Payment token creation failed:', error);

1179

}

1180

```