From 0ea0dfe39c022132a9ba713b6b375845d12159f2 Mon Sep 17 00:00:00 2001 From: Aman-engg-sdk Date: Tue, 16 Dec 2025 17:09:13 +0530 Subject: [PATCH 1/6] feat: Add ChatGPT App sample with MoEngage integration - Next.js 14 app with TypeScript - Full MoEngage WebSDK integration - ChatGPT Apps SDK integration - AI bot detection and blocking - AI-assisted browser detection - Comprehensive event tracking - User identification and session management - Complete documentation and testing guides --- .eslintrc.json | 4 + DEPLOYMENT_INSTRUCTIONS.md | 188 +++++++++ INTEGRATION_EXAMPLES.md | 280 +++++++++++++ QUICKSTART.md | 119 ++++++ README.md | 356 ++++++++++++++++- TESTING_GUIDE.md | 476 +++++++++++++++++++++++ app/globals.css | 51 +++ app/layout.tsx | 26 ++ app/page.tsx | 81 ++++ components/AIDetection.module.css | 63 +++ components/AIDetection.tsx | 50 +++ components/EventTracking.module.css | 112 ++++++ components/EventTracking.tsx | 125 ++++++ components/SessionManagement.module.css | 67 ++++ components/SessionManagement.tsx | 32 ++ components/TrackingLogs.module.css | 74 ++++ components/TrackingLogs.tsx | 32 ++ components/UserIdentification.module.css | 57 +++ components/UserIdentification.tsx | 72 ++++ hooks/useAIDetection.ts | 63 +++ hooks/useMoEngage.ts | 29 ++ hooks/useTracking.ts | 113 ++++++ lib/ai-detection.ts | 159 ++++++++ lib/chatgpt-apps.ts | 45 +++ lib/moengage.ts | 155 ++++++++ next.config.js | 25 ++ package.json | 37 ++ public/.well-known/openai-apps.json | 59 +++ tsconfig.json | 29 ++ 29 files changed, 2961 insertions(+), 18 deletions(-) create mode 100644 .eslintrc.json create mode 100644 DEPLOYMENT_INSTRUCTIONS.md create mode 100644 INTEGRATION_EXAMPLES.md create mode 100644 QUICKSTART.md create mode 100644 TESTING_GUIDE.md create mode 100644 app/globals.css create mode 100644 app/layout.tsx create mode 100644 app/page.tsx create mode 100644 components/AIDetection.module.css create mode 100644 components/AIDetection.tsx create mode 100644 components/EventTracking.module.css create mode 100644 components/EventTracking.tsx create mode 100644 components/SessionManagement.module.css create mode 100644 components/SessionManagement.tsx create mode 100644 components/TrackingLogs.module.css create mode 100644 components/TrackingLogs.tsx create mode 100644 components/UserIdentification.module.css create mode 100644 components/UserIdentification.tsx create mode 100644 hooks/useAIDetection.ts create mode 100644 hooks/useMoEngage.ts create mode 100644 hooks/useTracking.ts create mode 100644 lib/ai-detection.ts create mode 100644 lib/chatgpt-apps.ts create mode 100644 lib/moengage.ts create mode 100644 next.config.js create mode 100644 package.json create mode 100644 public/.well-known/openai-apps.json create mode 100644 tsconfig.json diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 00000000..f18272b8 --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,4 @@ +{ + "extends": "next/core-web-vitals" +} + diff --git a/DEPLOYMENT_INSTRUCTIONS.md b/DEPLOYMENT_INSTRUCTIONS.md new file mode 100644 index 00000000..899cfb95 --- /dev/null +++ b/DEPLOYMENT_INSTRUCTIONS.md @@ -0,0 +1,188 @@ +# Deployment Instructions + +## Option 1: Deploy via Vercel Dashboard (Recommended - No CLI needed) + +### Step 1: Push to GitHub + +1. Create a new repository on GitHub +2. Push your code: + ```bash + git init + git add . + git commit -m "Initial commit" + git remote add origin https://github.com/YOUR_USERNAME/YOUR_REPO.git + git push -u origin main + ``` + +### Step 2: Deploy on Vercel + +1. Go to [https://vercel.com](https://vercel.com) +2. Sign up/Login with your GitHub account +3. Click **"New Project"** +4. Import your GitHub repository +5. Configure project: + - **Framework Preset:** Next.js (auto-detected) + - **Root Directory:** `./` (default) + - **Build Command:** `npm run build` (default) + - **Output Directory:** `.next` (default) +6. Add Environment Variables: + - Click **"Environment Variables"** + - Add: + - **Name:** `NEXT_PUBLIC_MOENGAGE_DATACENTER` + - **Value:** `dc_01` + - Add: + - **Name:** `NEXT_PUBLIC_MOENGAGE_APP_ID` + - **Value:** `3RADPYNEBZ2MCOJ43EEW5FWV` +7. Click **"Deploy"** +8. Wait for deployment to complete +9. Note your deployment URL (e.g., `https://your-app.vercel.app`) + +### Step 3: Update ChatGPT Manifest + +1. After deployment, update `public/.well-known/openai-apps.json`: + ```json + { + "homepage_url": "https://your-app.vercel.app", + ... + } + ``` +2. Commit and push the change +3. Vercel will automatically redeploy + +### Step 4: Verify Manifest + +1. Open: `https://your-app.vercel.app/.well-known/openai-apps.json` +2. Should see the JSON file +3. Verify `homepage_url` matches your Vercel URL + +--- + +## Option 2: Deploy via Vercel CLI (If SSL issue is resolved) + +### Step 1: Login to Vercel + +```bash +vercel login +``` + +### Step 2: Deploy + +```bash +vercel --prod +``` + +Follow the prompts: +- Set up and deploy? **Yes** +- Which scope? (Select your account) +- Link to existing project? **No** +- Project name? (Press Enter for default) +- Directory? (Press Enter for current directory) + +### Step 3: Set Environment Variables + +```bash +vercel env add NEXT_PUBLIC_MOENGAGE_DATACENTER +# Enter: dc_01 + +vercel env add NEXT_PUBLIC_MOENGAGE_APP_ID +# Enter: 3RADPYNEBZ2MCOJ43EEW5FWV +``` + +### Step 4: Redeploy + +```bash +vercel --prod +``` + +--- + +## Option 3: Deploy to Other Platforms + +### Netlify + +1. Go to [https://netlify.com](https://netlify.com) +2. Drag and drop your `.next` folder (after `npm run build`) +3. Or connect GitHub repository +4. Set environment variables in Netlify dashboard +5. Deploy + +### Railway + +1. Go to [https://railway.app](https://railway.app) +2. Create new project from GitHub +3. Set environment variables +4. Deploy + +### Render + +1. Go to [https://render.com](https://render.com) +2. Create new Web Service +3. Connect GitHub repository +4. Set environment variables +5. Deploy + +--- + +## After Deployment + +### 1. Update ChatGPT App Manifest + +Edit `public/.well-known/openai-apps.json` and set: +```json +{ + "homepage_url": "https://YOUR-DEPLOYMENT-URL.com" +} +``` + +### 2. Register with OpenAI + +1. Go to [https://platform.openai.com](https://platform.openai.com) +2. Navigate to Apps section +3. Create new app +4. Set manifest URL: `https://YOUR-DEPLOYMENT-URL.com/.well-known/openai-apps.json` + +### 3. Test Deployment + +1. Open your deployment URL +2. Verify app loads correctly +3. Check MoEngage SDK initializes +4. Test tracking events +5. Verify in MoEngage dashboard + +--- + +## Troubleshooting + +### SSL Certificate Error (CLI) + +If you get SSL certificate errors with Vercel CLI: +- Use Option 1 (Dashboard deployment) instead +- Or check your network/proxy settings +- Or try: `NODE_TLS_REJECT_UNAUTHORIZED=0 vercel --prod` (not recommended for production) + +### Environment Variables Not Working + +- Ensure variables start with `NEXT_PUBLIC_` for client-side access +- Redeploy after adding environment variables +- Check Vercel dashboard → Settings → Environment Variables + +### Manifest Not Accessible + +- Ensure file is in `public/.well-known/` directory +- Check file permissions +- Verify URL is correct: `https://your-app.vercel.app/.well-known/openai-apps.json` + +--- + +## Quick Reference + +**Your MoEngage Credentials:** +- Data Center: `dc_01` +- App ID: `3RADPYNEBZ2MCOJ43EEW5FWV` + +**Environment Variables to Set:** +``` +NEXT_PUBLIC_MOENGAGE_DATACENTER=dc_01 +NEXT_PUBLIC_MOENGAGE_APP_ID=3RADPYNEBZ2MCOJ43EEW5FWV +``` + diff --git a/INTEGRATION_EXAMPLES.md b/INTEGRATION_EXAMPLES.md new file mode 100644 index 00000000..2a53b8c5 --- /dev/null +++ b/INTEGRATION_EXAMPLES.md @@ -0,0 +1,280 @@ +# Integration Examples + +## Example 1: E-commerce Product Tracking + +```javascript +// Track product view +trackingManager.trackEvent('product_view', { + product_id: 'PROD123', + product_name: 'Wireless Headphones', + product_category: 'Electronics', + product_price: 199.99, + currency: 'USD', + brand: 'TechBrand' +}); + +// Track add to cart +trackingManager.trackEvent('add_to_cart', { + product_id: 'PROD123', + product_name: 'Wireless Headphones', + quantity: 2, + price: 199.99, + currency: 'USD', + cart_value: 399.98 +}); + +// Track purchase +trackingManager.trackEvent('purchase', { + order_id: 'ORD789', + product_id: 'PROD123', + product_name: 'Wireless Headphones', + quantity: 2, + total_amount: 399.98, + currency: 'USD', + payment_method: 'credit_card', + shipping_method: 'express' +}); +``` + +## Example 2: User Journey Tracking + +```javascript +// Identify user on login +trackingManager.handleIdentifyUser(); + +// Track key milestones +trackingManager.trackEvent('user_signed_up', { + signup_method: 'email', + referral_source: 'organic' +}); + +trackingManager.trackEvent('onboarding_completed', { + steps_completed: 5, + time_taken: 120 +}); + +trackingManager.trackEvent('feature_used', { + feature_name: 'advanced_search', + usage_count: 3 +}); +``` + +## Example 3: AI-Assisted User Segmentation + +```javascript +// The app automatically detects AI-assisted browsers +// You can use this in MoEngage to create segments: + +// Segment 1: AI-Assisted Users +// Condition: ai_assisted_browser == true + +// Segment 2: GPT App Users +// Condition: gpt_app_user == true + +// Segment 3: High-Intent AI Users +// Condition: ai_assisted_browser == true AND purchase_count > 0 + +// Track specific events for AI-assisted users +if (aiDetection.getDetectionResults().isAIAssisted) { + trackingManager.trackEvent('ai_assisted_interaction', { + interaction_type: 'product_search', + ai_features_used: ['voice_search', 'smart_suggestions'] + }); +} +``` + +## Example 4: Custom Event with Rich Properties + +```javascript +// Track a custom event with detailed properties +trackingManager.trackEvent('content_engagement', { + content_type: 'article', + content_id: 'ART456', + content_title: 'How to Use AI in Marketing', + reading_time: 180, + scroll_depth: 85, + shares: 3, + likes: 12, + comments: 5 +}); +``` + +## Example 5: Form Tracking + +```javascript +// Track form submissions +trackingManager.trackEvent('form_submitted', { + form_type: 'contact', + form_id: 'contact_form_1', + fields_completed: 5, + time_to_complete: 45, + submission_successful: true +}); + +// Track form abandonment +trackingManager.trackEvent('form_abandoned', { + form_type: 'checkout', + form_id: 'checkout_form', + fields_completed: 3, + total_fields: 8, + abandonment_reason: 'timeout' +}); +``` + +## Example 6: Search and Discovery + +```javascript +// Track search queries +trackingManager.trackEvent('search', { + search_query: 'wireless headphones', + search_category: 'electronics', + results_count: 24, + filters_applied: ['price_range', 'brand'], + search_source: 'header' +}); + +// Track search result clicks +trackingManager.trackEvent('search_result_clicked', { + search_query: 'wireless headphones', + result_position: 3, + result_id: 'PROD123', + click_through: true +}); +``` + +## Example 7: Campaign Engagement + +```javascript +// MoEngage automatically tracks campaign events +// But you can also track custom campaign interactions: + +trackingManager.trackEvent('campaign_interaction', { + campaign_id: 'SUMMER_SALE_2024', + campaign_type: 'banner', + interaction_type: 'click', + campaign_name: 'Summer Sale 2024' +}); +``` + +## Example 8: Error and Performance Tracking + +```javascript +// Track errors +trackingManager.trackEvent('error_occurred', { + error_type: 'javascript_error', + error_message: 'Failed to load product data', + error_location: 'product_page', + user_agent: navigator.userAgent +}); + +// Track performance +trackingManager.trackEvent('performance_metric', { + metric_name: 'page_load_time', + metric_value: 1250, + page_url: window.location.href +}); +``` + +## Example 9: Multi-Step Process Tracking + +```javascript +// Track multi-step processes +const steps = ['view_product', 'add_to_cart', 'checkout', 'payment', 'confirmation']; + +steps.forEach((step, index) => { + trackingManager.trackEvent('checkout_step', { + step_name: step, + step_number: index + 1, + total_steps: steps.length, + timestamp: new Date().toISOString() + }); +}); +``` + +## Example 10: Conditional Tracking Based on AI Detection + +```javascript +// Track differently based on AI detection +const detection = aiDetection.getDetectionResults(); + +if (detection.isAIBot) { + // Don't track - already handled by shouldBlockTracking() + console.log('Bot detected - tracking blocked'); +} else if (detection.isGPTApp) { + // Enhanced tracking for GPT app users + trackingManager.trackEvent('gpt_app_interaction', { + interaction_type: 'product_inquiry', + gpt_context: 'user_asked_about_product', + response_provided: true + }); +} else if (detection.isAIAssisted) { + // Track AI-assisted features + trackingManager.trackEvent('ai_feature_used', { + feature_type: 'smart_suggestions', + user_satisfaction: 'high' + }); +} else { + // Standard tracking for regular users + trackingManager.trackEvent('standard_interaction', { + interaction_type: 'page_view' + }); +} +``` + +## Example 11: User Attribute Updates + +```javascript +// Update user attributes +if (typeof Moengage !== 'undefined' && Moengage) { + Moengage.add_user_attribute({ + subscription_status: 'premium', + subscription_tier: 'pro', + last_purchase_date: '2024-01-15', + total_purchases: 5, + lifetime_value: 499.95, + favorite_category: 'electronics' + }); +} +``` + +## Example 12: Session-Based Tracking + +```javascript +// Track session start +trackingManager.trackEvent('session_start', { + referrer: document.referrer, + landing_page: window.location.href, + device_type: /Mobile|Android|iPhone/i.test(navigator.userAgent) ? 'mobile' : 'desktop' +}); + +// Track session end (automatically handled on beforeunload) +// But you can also track manually: +window.addEventListener('beforeunload', () => { + trackingManager.trackEvent('session_end_manual', { + session_duration: performance.now(), + pages_viewed: 5 + }); +}); +``` + +## Best Practices + +1. **Always identify users before tracking events** - This ensures proper attribution +2. **Use consistent event names** - Follow a naming convention (e.g., snake_case) +3. **Include relevant context** - Add properties that help with analysis +4. **Respect AI bot detection** - Don't override the blocking mechanism +5. **Track user journey** - Track key milestones in user flows +6. **Use custom events wisely** - Don't over-track, focus on meaningful events +7. **Test in MoEngage dashboard** - Verify events appear correctly +8. **Monitor event volume** - Be mindful of event limits + +## Integration with MoEngage Dashboard + +After tracking events, you can: + +1. **Create Segments** - Use event properties and user attributes +2. **Build Journeys** - Create user journey flows based on events +3. **Set up Campaigns** - Target users based on behavior +4. **Analyze Funnels** - Track conversion funnels +5. **Create Reports** - Build custom reports with tracked events + diff --git a/QUICKSTART.md b/QUICKSTART.md new file mode 100644 index 00000000..880a97bd --- /dev/null +++ b/QUICKSTART.md @@ -0,0 +1,119 @@ +# Quick Start Guide - Next.js + +## Prerequisites + +- Node.js 18+ (or Node 12 via nvm as per project requirements) +- npm or yarn + +## 5-Minute Setup + +### Step 1: Install Dependencies + +```bash +npm install +``` + +### Step 2: Configure MoEngage + +Create `.env.local` file: + +```env +NEXT_PUBLIC_MOENGAGE_DATACENTER=dc_01 +NEXT_PUBLIC_MOENGAGE_APP_ID=YOUR_MOENGAGE_APP_ID +``` + +Or edit `app/page.tsx` directly: + +```typescript +const MOENGAGE_CONFIG = { + dataCenter: 'dc_01', // Your Data Center + appId: 'YOUR_MOENGAGE_APP_ID', // Your App ID + // ... +}; +``` + +### Step 3: Run Development Server + +```bash +npm run dev +``` + +### Step 4: Open in Browser + +Navigate to: `http://localhost:3000` + +### Step 5: Test Tracking + +1. Wait for "MoEngage SDK Ready ✓" message +2. Click "Track Page View" - Check logs +3. Enter user info and click "Identify User" +4. Click other tracking buttons +5. Check MoEngage dashboard for events + +## For ChatGPT Integration + +### Step 1: Build and Deploy + +```bash +npm run build +``` + +Deploy to a platform like Vercel, Netlify, or any HTTPS server. + +### Step 2: Update Manifest + +Edit `public/.well-known/openai-apps.json`: +- Update `homepage_url` to your domain + +### Step 3: Verify Manifest Access + +Ensure the file is accessible at: +``` +https://your-domain.com/.well-known/openai-apps.json +``` + +### Step 4: Register with OpenAI + +Follow OpenAI's ChatGPT Apps registration process. + +## Development Commands + +```bash +npm run dev # Start development server +npm run build # Build for production +npm start # Start production server +npm run lint # Run ESLint +``` + +## Project Structure + +- `app/` - Next.js App Router pages and layouts +- `components/` - React components +- `hooks/` - Custom React hooks +- `lib/` - Utility functions and SDK wrappers +- `public/` - Static files including ChatGPT manifest + +## Common Issues + +**SDK not loading?** +- Check Data Center and App ID in `.env.local` or `app/page.tsx` +- Verify internet connection +- Check browser console + +**Build errors?** +- Clear `.next` folder: `rm -rf .next` +- Reinstall dependencies: `rm -rf node_modules && npm install` +- Check Node.js version: `node --version` + +**Events not tracking?** +- Verify SDK initialized (check UI status) +- Check if AI bot is blocking (see detection section) +- Ensure user is identified + +## Next Steps + +- Review `README.md` for detailed documentation +- Check `INTEGRATION_EXAMPLES.md` for code examples +- Customize tracking events for your use case +- Configure MoEngage campaigns +- Set up user segmentation diff --git a/README.md b/README.md index e49d643a..dc38623b 100644 --- a/README.md +++ b/README.md @@ -1,34 +1,354 @@ -# webSDK-sample -Sample WebSDK integration +# MoEngage Sample App - ChatGPT Integration (Next.js) -[Basic Integration](index.html) +A modern Next.js application demonstrating MoEngage WebSDK integration with ChatGPT Apps, including comprehensive tracking, AI detection, and user engagement capabilities. -[Integration with Debugging enabled](debug.html) +## Features -[Self Handled Opt-in Sample](self-handled-push.html) +- ✅ **Next.js 14** - Modern React framework with App Router +- ✅ **TypeScript** - Full type safety +- ✅ **MoEngage WebSDK Integration** - Full tracking and analytics +- ✅ **ChatGPT Apps SDK Integration** - Compatible with OpenAI's ChatGPT Apps platform +- ✅ **AI Bot Detection** - Automatically detects and blocks AI bot traffic +- ✅ **AI-Assisted Browser Detection** - Identifies users on AI-assisted browsers +- ✅ **GPT App Detection** - Detects when app is running within ChatGPT +- ✅ **Comprehensive Event Tracking** - Tracks all user interactions +- ✅ **User Identification** - Full user profile management +- ✅ **Session Management** - Session tracking and management +- ✅ **Real-time Logging** - Visual feedback for all tracking events +- ✅ **React Hooks** - Custom hooks for easy integration +- ✅ **CSS Modules** - Scoped styling -[Custom Service Worker](custom-serviceworker.html) +## Project Structure -[Web Personalization](web-personalization.html) +``` +OPEN_AI_SDK/ +├── app/ +│ ├── layout.tsx # Root layout with metadata +│ ├── page.tsx # Main page component +│ └── globals.css # Global styles +├── components/ +│ ├── UserIdentification.tsx +│ ├── EventTracking.tsx +│ ├── AIDetection.tsx +│ ├── SessionManagement.tsx +│ └── TrackingLogs.tsx +├── hooks/ +│ ├── useMoEngage.ts # MoEngage initialization hook +│ ├── useAIDetection.ts # AI detection hook +│ └── useTracking.ts # Tracking utilities hook +├── lib/ +│ ├── moengage.ts # MoEngage SDK wrapper +│ ├── ai-detection.ts # AI detection logic +│ └── chatgpt-apps.ts # ChatGPT Apps SDK wrapper +├── public/ +│ └── .well-known/ +│ └── openai-apps.json # ChatGPT Apps manifest +├── next.config.js # Next.js configuration +├── tsconfig.json # TypeScript configuration +└── package.json # Dependencies +``` -[Angular App Sample Code](angular-sample/) +## Prerequisites -[React App Sample Code](react-sample/) +- Node.js 18+ (or use nvm with Node 12 as per project requirements) +- npm or yarn +- MoEngage account with App ID and Data Center +- (Optional) ChatGPT Apps access for testing -[Nuxt JS SPA](nuxt-spa/) +## Setup Instructions -[Next JS](nextjs/) +### 1. Install Dependencies -[Google Tag Manager](google-tag-manager/) +```bash +npm install +``` -[LG Web OS](lg-web-os/) +### 2. Configure Environment Variables -[Samsung Tizen OS](samsung-tizen-os/samsungTizenOs/) +Create a `.env.local` file in the root directory: -[PWA](pwa/) +```env +NEXT_PUBLIC_MOENGAGE_DATACENTER=dc_01 +NEXT_PUBLIC_MOENGAGE_APP_ID=YOUR_MOENGAGE_APP_ID +``` -[npm](npm/) +Or update directly in `app/page.tsx`: -[Chrome Extension](chrome-extension/) +```typescript +const MOENGAGE_CONFIG = { + dataCenter: 'dc_01', // Your Data Center + appId: 'YOUR_MOENGAGE_APP_ID', // Your App ID + sdkVersion: '2', + debugLogs: 1, +}; +``` -[Magento](magento/) +### 3. Run Development Server + +```bash +npm run dev +``` + +Open [http://localhost:3000](http://localhost:3000) in your browser. + +### 4. Build for Production + +```bash +npm run build +npm start +``` + +## Configuration + +### MoEngage Setup + +1. **Get your MoEngage credentials:** + - Log in to your MoEngage dashboard + - Navigate to Settings → Apps → Web + - Copy your **App ID** (Workspace ID) + - Note your **Data Center** (e.g., `dc_01`, `dc_02`, etc.) + +2. **Update configuration:** + - Set environment variables in `.env.local` + - Or update `MOENGAGE_CONFIG` in `app/page.tsx` + +### ChatGPT App Integration + +1. **Update `public/.well-known/openai-apps.json`:** + - Set `homepage_url` to your deployed app URL + - Ensure the file is accessible at `https://your-domain.com/.well-known/openai-apps.json` + +2. **Deploy to HTTPS:** + - The app must be served over HTTPS to work with ChatGPT Apps + - Use Vercel, Netlify, or any hosting provider with HTTPS + +3. **Register with OpenAI:** + - Follow OpenAI's ChatGPT Apps documentation to register your app + - Provide the URL to your `openai-apps.json` manifest + +## Usage + +### User Identification + +1. Enter user details (User ID, Name, Email, Mobile) +2. Click "Identify User" to send user data to MoEngage +3. User attributes including AI detection flags are automatically set + +### Event Tracking + +The app includes several pre-configured tracking events: + +- **Page View** - Tracks page loads +- **Button Click** - Generic button click tracking +- **Product View** - E-commerce product view tracking +- **Add to Cart** - Shopping cart events +- **Purchase** - Purchase/checkout events +- **Search** - Search query tracking +- **Custom Event** - Track any custom event with properties + +### AI Detection + +The app automatically detects: + +- **AI Bots** - Known AI crawlers (GPTBot, ClaudeBot, etc.) +- **AI-Assisted Browsers** - Browsers with AI features (Arc, etc.) +- **GPT App Environment** - When running inside ChatGPT + +Detection results are: +- Displayed in the UI +- Tracked as user attributes in MoEngage +- Used to enhance event properties + +### Session Management + +- **Destroy Session** - Ends the current session +- **Update User ID** - Changes the user identifier + +## Tracking Events + +All events are automatically enhanced with: + +- `ai_platform` - "chatgpt" or "web" +- `is_ai_assisted` - Boolean flag +- `is_gpt_app` - Boolean flag +- `timestamp` - ISO timestamp + +### Standard Events Tracked + +1. `page_view` - Page load events +2. `user_identified` - User identification events +3. `button_click` - Button interactions +4. `product_view` - Product viewing +5. `add_to_cart` - Cart additions +6. `purchase` - Purchase completions +7. `search` - Search queries +8. `ai_detection_performed` - AI detection results +9. `chatgpt_app_initialized` - ChatGPT app initialization +10. `chatgpt_action` - Actions from ChatGPT +11. `gpt_app_session_start` - GPT app session start +12. `session_end` - Session termination +13. `app_loaded` - Application load event + +## User Attributes + +The following user attributes are automatically set: + +- `ai_bot_detected` - Boolean +- `ai_assisted_browser` - Boolean +- `gpt_app_user` - Boolean +- `ai_assisted` - Boolean (when AI-assisted browser detected) +- `user_agent` - Browser user agent string +- `detection_timestamp` - When detection was performed + +## AI Bot Detection + +The app blocks tracking for known AI bots to prevent data pollution: + +**Detected Bots:** +- GPTBot +- ChatGPT-User +- CCBot +- ClaudeBot +- PerplexityBot +- YouBot +- Google-Extended +- And more... + +When a bot is detected: +- Events are logged but not sent to MoEngage +- User attributes are not set +- Prevents anonymous user creation + +## React Hooks + +### useMoEngage + +Initializes and manages MoEngage SDK: + +```typescript +const { isReady } = useMoEngage(config); +``` + +### useAIDetection + +Performs AI detection and tracks results: + +```typescript +const { detectionResults, isDetecting, refreshDetection, shouldBlockTracking } = useAIDetection(); +``` + +### useTracking + +Provides tracking utilities: + +```typescript +const { track, identify, destroy, updateId, log } = useTracking(onLog); +``` + +## Deployment + +### Vercel (Recommended) + +1. Push your code to GitHub +2. Import project in Vercel +3. Add environment variables +4. Deploy + +### Other Platforms + +The app can be deployed to any platform that supports Next.js: +- Netlify +- AWS Amplify +- Railway +- Render +- Any Node.js hosting + +## Testing + +### Local Testing + +1. Run `npm run dev` +2. Open `http://localhost:3000` +3. Check browser console for MoEngage SDK logs +4. Verify events in MoEngage dashboard + +### ChatGPT Testing + +1. Deploy app to HTTPS server +2. Register app with OpenAI +3. Test within ChatGPT interface +4. Verify GPT app detection works +5. Check events include `ai_platform: "chatgpt"` + +## Troubleshooting + +### MoEngage SDK Not Loading + +- Check Data Center and App ID are correct +- Verify internet connection +- Check browser console for errors +- Ensure environment variables are set + +### Events Not Tracking + +- Verify MoEngage SDK is initialized (check UI status) +- Check if AI bot detection is blocking events +- Review browser console for errors +- Ensure user is identified (for some events) + +### ChatGPT App Not Working + +- Verify HTTPS is enabled +- Check `openai-apps.json` is accessible +- Ensure CSP domains are correct +- Verify ChatGPT Apps SDK is loaded + +### Build Errors + +- Ensure Node.js version is compatible +- Clear `.next` folder and rebuild +- Check TypeScript errors with `npm run lint` + +## Development + +### Adding New Components + +1. Create component in `components/` directory +2. Use CSS Modules for styling +3. Import and use in `app/page.tsx` + +### Adding New Tracking Events + +1. Use the `track` function from `useTracking` hook +2. Add event properties as needed +3. Events are automatically enhanced with AI context + +### Customizing AI Detection + +1. Update `lib/ai-detection.ts` +2. Add new bot patterns or markers +3. Detection runs automatically on page load + +## Security & Privacy + +- All tracking respects user privacy +- No sensitive data is tracked by default +- User consent should be obtained before tracking +- GDPR/CCPA compliance should be implemented as needed + +## Support + +For issues or questions: + +- **MoEngage Documentation:** https://developers.moengage.com/ +- **ChatGPT Apps Documentation:** https://platform.openai.com/docs/guides/apps +- **Next.js Documentation:** https://nextjs.org/docs +- **MoEngage Support:** Contact your MoEngage account manager + +## License + +This is a sample application for demonstration purposes. + +## Version History + +- **v1.0.0** - Initial Next.js release with full MoEngage and ChatGPT Apps integration diff --git a/TESTING_GUIDE.md b/TESTING_GUIDE.md new file mode 100644 index 00000000..2d2a38ab --- /dev/null +++ b/TESTING_GUIDE.md @@ -0,0 +1,476 @@ +# Testing Guide + +Complete guide for testing the MoEngage Sample App locally and in ChatGPT. + +## Part 1: Local Testing + +### Prerequisites + +- Node.js 18+ installed (or Node 12 via nvm as per project requirements) +- npm or yarn installed +- MoEngage account with App ID and Data Center +- A modern web browser (Chrome, Firefox, Safari, Edge) + +### Step 1: Install Dependencies + +```bash +cd /Users/aman.verma/Desktop/Projects/OPEN_AI_SDK +npm install +``` + +Expected output: +``` +added 200+ packages in 30s +``` + +### Step 2: Configure MoEngage + +**Option A: Using Environment Variables (Recommended)** + +1. Create `.env.local` file in the root directory: +```bash +touch .env.local +``` + +2. Add your MoEngage credentials: +```env +NEXT_PUBLIC_MOENGAGE_DATACENTER=dc_01 +NEXT_PUBLIC_MOENGAGE_APP_ID=YOUR_ACTUAL_APP_ID +``` + +**Option B: Direct Configuration** + +Edit `app/page.tsx` and update the `MOENGAGE_CONFIG` object: + +```typescript +const MOENGAGE_CONFIG = { + dataCenter: 'dc_01', // Replace with your Data Center + appId: 'YOUR_ACTUAL_APP_ID', // Replace with your App ID + sdkVersion: '2', + debugLogs: 1, +}; +``` + +**How to Get Your MoEngage Credentials:** + +1. Log in to your MoEngage dashboard: https://app.moengage.com +2. Navigate to **Settings** → **Apps** → **Web** +3. Copy your **App ID** (also called Workspace ID) +4. Note your **Data Center** (usually `dc_01`, `dc_02`, etc.) + - You can find this in the SDK integration code provided by MoEngage + - Or check the URL pattern: `https://api-XX.moengage.com` where XX is your data center number + +### Step 3: Start Development Server + +```bash +npm run dev +``` + +Expected output: +``` +▲ Next.js 14.0.0 +- Local: http://localhost:3000 +- Ready in 2.5s +``` + +### Step 4: Open in Browser + +1. Open your browser +2. Navigate to: `http://localhost:3000` +3. You should see the MoEngage Sample App interface + +### Step 5: Verify MoEngage SDK Initialization + +1. **Check the UI:** + - Look for "MoEngage SDK Ready ✓" message at the top + - If you see "Initializing MoEngage SDK...", wait a few seconds + +2. **Check Browser Console:** + - Open Developer Tools (F12 or Cmd+Option+I on Mac) + - Go to Console tab + - You should see: `MoEngage Web SDK initialised` or similar messages + - No red error messages related to MoEngage + +3. **Check Network Tab:** + - Go to Network tab in Developer Tools + - Filter by "moengage" + - You should see requests to MoEngage CDN and API endpoints + - Status should be 200 (success) + +### Step 6: Test User Identification + +1. Fill in the User Identification form: + - **User ID:** `test_user_123` + - **Name:** `Test User` + - **Email:** `test@example.com` + - **Mobile:** `1234567890` + +2. Click **"Identify User"** button + +3. **Verify:** + - Check the Tracking Logs section - should show "User identified: test_user_123" + - Check browser console - should see MoEngage API calls + - Check MoEngage dashboard → Users → Search for `test_user_123` + +### Step 7: Test Event Tracking + +1. **Test Pre-configured Events:** + - Click **"Track Page View"** - Check logs show success + - Click **"Track Button Click"** - Check logs + - Click **"Track Product View"** - Check logs + - Click **"Track Add to Cart"** - Check logs + - Click **"Track Purchase"** - Check logs + - Click **"Track Search"** - Check logs + +2. **Test Custom Event:** + - Enter Event Name: `custom_test_event` + - Enter Event Properties: `{"test_key": "test_value", "number": 123}` + - Click **"Track Custom Event"** + - Verify in logs and MoEngage dashboard + +3. **Verify in MoEngage Dashboard:** + - Go to MoEngage Dashboard → Analytics → Events + - You should see all tracked events + - Click on an event to see properties + +### Step 8: Test AI Detection + +1. **Check AI Detection Section:** + - Should automatically show detection results on page load + - **User Agent:** Should show your browser's user agent + - **AI Bot Detected:** Should show "No" (unless you're using a bot) + - **AI-Assisted Browser:** May show "Yes" if using Arc, etc. + - **GPT App User:** Should show "No" (you're testing locally) + +2. **Test Refresh:** + - Click **"Refresh Detection"** button + - Results should update + +3. **Verify in MoEngage:** + - Check user attributes in MoEngage dashboard + - Should see: `ai_bot_detected`, `ai_assisted_browser`, `gpt_app_user` attributes + +### Step 9: Test Session Management + +1. **Destroy Session:** + - Click **"Destroy Session"** button + - Check logs for confirmation + - Verify in MoEngage dashboard + +2. **Update User ID:** + - Click **"Update User ID"** button + - Enter new ID: `test_user_456` + - Check logs for confirmation + +### Step 10: Verify Tracking Logs + +1. All actions should appear in the **Tracking Logs** section +2. Logs should show: + - Timestamp + - Event/action description + - Color coding (green for success, red for errors, blue for info) + +### Step 11: Test AI Bot Detection (Optional) + +To test bot detection blocking: + +1. Open browser console +2. Temporarily modify user agent: + ```javascript + Object.defineProperty(navigator, 'userAgent', { + get: () => 'Mozilla/5.0 (compatible; GPTBot/1.0; +https://openai.com/gptbot)' + }); + ``` +3. Refresh the page +4. Try tracking an event +5. Should see "Event blocked (AI Bot detected)" in logs +6. Events should NOT appear in MoEngage dashboard + +### Troubleshooting Local Testing + +**Issue: SDK not loading** +- ✅ Check Data Center and App ID are correct +- ✅ Check internet connection +- ✅ Check browser console for errors +- ✅ Verify MoEngage CDN is accessible + +**Issue: Events not appearing in MoEngage** +- ✅ Wait 1-2 minutes (events may be delayed) +- ✅ Check MoEngage dashboard → Settings → Data Pipeline +- ✅ Verify App ID is correct +- ✅ Check browser console for API errors + +**Issue: Build errors** +- ✅ Clear `.next` folder: `rm -rf .next` +- ✅ Reinstall dependencies: `rm -rf node_modules && npm install` +- ✅ Check Node.js version: `node --version` (should be 18+) + +--- + +## Part 2: Testing in ChatGPT + +### Prerequisites + +- Completed local testing successfully +- HTTPS server/hosting (required for ChatGPT Apps) +- OpenAI account with ChatGPT Apps access +- Domain name (or use a hosting service like Vercel) + +### Step 1: Build the Application + +```bash +npm run build +``` + +Expected output: +``` +✓ Compiled successfully +✓ Linting +✓ Collecting page data +✓ Generating static pages +``` + +### Step 2: Deploy to HTTPS Server + +**Option A: Deploy to Vercel (Recommended - Free & Easy)** + +1. **Install Vercel CLI:** + ```bash + npm install -g vercel + ``` + +2. **Login to Vercel:** + ```bash + vercel login + ``` + +3. **Deploy:** + ```bash + vercel + ``` + - Follow prompts + - Choose production deployment + - Note the deployment URL (e.g., `https://your-app.vercel.app`) + +4. **Set Environment Variables in Vercel:** + - Go to Vercel Dashboard → Your Project → Settings → Environment Variables + - Add: + - `NEXT_PUBLIC_MOENGAGE_DATACENTER` = `dc_01` + - `NEXT_PUBLIC_MOENGAGE_APP_ID` = `YOUR_APP_ID` + - Redeploy if needed + +**Option B: Deploy to Netlify** + +1. **Install Netlify CLI:** + ```bash + npm install -g netlify-cli + ``` + +2. **Build and Deploy:** + ```bash + npm run build + netlify deploy --prod + ``` + +3. **Set Environment Variables:** + - Go to Netlify Dashboard → Site Settings → Environment Variables + - Add your MoEngage credentials + +**Option C: Deploy to Your Own Server** + +1. Build the app: `npm run build` +2. Copy `.next`, `public`, `package.json`, `node_modules` to your server +3. Install dependencies: `npm install --production` +4. Start server: `npm start` +5. Ensure HTTPS is configured (use Let's Encrypt or similar) + +### Step 3: Update ChatGPT App Manifest + +1. **Edit `public/.well-known/openai-apps.json`:** + + ```json + { + "name": "MoEngage Sample App", + "description": "Sample application with MoEngage WebSDK integration", + "version": "1.0.0", + "author": "MoEngage", + "homepage_url": "https://your-deployed-url.com", + ... + } + ``` + + Replace `https://your-deployed-url.com` with your actual deployment URL. + +2. **Verify Manifest is Accessible:** + - Open: `https://your-deployed-url.com/.well-known/openai-apps.json` + - Should see the JSON file in browser + - Check that `Content-Type` is `application/json` + +### Step 4: Register App with OpenAI + +1. **Access ChatGPT Apps Platform:** + - Go to: https://platform.openai.com + - Navigate to **Apps** section (or check OpenAI documentation for current URL) + +2. **Create New App:** + - Click "Create App" or "New App" + - Fill in app details: + - **Name:** MoEngage Sample App + - **Description:** Sample app with MoEngage tracking + - **Manifest URL:** `https://your-deployed-url.com/.well-known/openai-apps.json` + +3. **Configure App Settings:** + - Set app permissions (user_data, analytics) + - Review CSP settings (should match your manifest) + - Save configuration + +4. **Get App ID/Token:** + - Note your app's unique identifier + - May need this for advanced configurations + +### Step 5: Test in ChatGPT + +1. **Open ChatGPT:** + - Go to: https://chat.openai.com + - Log in to your account + +2. **Access Your App:** + - Look for your app in the ChatGPT interface + - May be in a sidebar, menu, or accessible via command + - Or use the app URL directly if provided by OpenAI + +3. **Verify App Loads:** + - App should load within ChatGPT interface + - Should see "MoEngage Sample App" interface + - Check for "MoEngage SDK Ready ✓" message + +### Step 6: Test GPT App Detection + +1. **Check AI Detection Section:** + - **GPT App User:** Should now show **"Yes"** ✅ + - This confirms the app is running in ChatGPT environment + +2. **Verify in Logs:** + - Should see `gpt_app_session_start` event in logs + - Should see `chatgpt_app_initialized` event + +3. **Check MoEngage Dashboard:** + - User attributes should show `gpt_app_user: true` + - Events should have `ai_platform: "chatgpt"` + +### Step 7: Test Tracking in ChatGPT + +1. **Test User Identification:** + - Fill in user details + - Click "Identify User" + - Verify in MoEngage dashboard + - Check that `gpt_app_user: true` attribute is set + +2. **Test Events:** + - Track various events + - Verify they appear in MoEngage + - Check that events have `ai_platform: "chatgpt"` property + +3. **Test ChatGPT Actions:** + - If your app receives actions from ChatGPT, they should be tracked + - Check logs for `chatgpt_action` events + +### Step 8: Verify MoEngage Integration + +1. **Check MoEngage Dashboard:** + - Go to Users → Search for your test user + - Verify attributes: + - `gpt_app_user: true` + - `ai_platform: "chatgpt"` (in events) + - Other user attributes + +2. **Check Events:** + - Go to Analytics → Events + - Filter by your test user + - Verify all events are tracked + - Check event properties include `ai_platform: "chatgpt"` + +3. **Check Segments:** + - Create a segment: `gpt_app_user == true` + - Should include your test user + +### Troubleshooting ChatGPT Integration + +**Issue: App not loading in ChatGPT** +- ✅ Verify HTTPS is enabled +- ✅ Check manifest URL is accessible +- ✅ Verify CSP configuration in manifest +- ✅ Check OpenAI app registration status +- ✅ Review OpenAI console for errors + +**Issue: GPT App detection not working** +- ✅ Check if app is actually running in ChatGPT (not just iframe) +- ✅ Verify `window.parent` detection logic +- ✅ Check browser console for errors + +**Issue: Events not tracking in ChatGPT** +- ✅ Verify MoEngage SDK loads (check console) +- ✅ Check CSP allows MoEngage domains +- ✅ Verify network requests to MoEngage API +- ✅ Check MoEngage dashboard for events (may be delayed) + +**Issue: CSP errors** +- ✅ Verify all MoEngage domains are in manifest +- ✅ Check your data center matches the domains +- ✅ Review browser console for CSP violations + +### Step 9: Advanced Testing + +1. **Test Multiple Users:** + - Identify different users + - Track events for each + - Verify segmentation works + +2. **Test Campaigns:** + - Create MoEngage campaigns targeting `gpt_app_user == true` + - Verify campaigns appear in app + - Test campaign interactions + +3. **Test Analytics:** + - Create funnels in MoEngage + - Build reports with GPT app events + - Verify attribution works correctly + +### Checklist + +**Local Testing:** +- [ ] Dependencies installed +- [ ] MoEngage configured +- [ ] App runs on localhost:3000 +- [ ] SDK initializes successfully +- [ ] User identification works +- [ ] Events track correctly +- [ ] AI detection works +- [ ] Logs display properly +- [ ] Events appear in MoEngage dashboard + +**ChatGPT Testing:** +- [ ] App built successfully +- [ ] Deployed to HTTPS server +- [ ] Manifest accessible +- [ ] App registered with OpenAI +- [ ] App loads in ChatGPT +- [ ] GPT app detection works +- [ ] Tracking works in ChatGPT +- [ ] Events have correct properties +- [ ] User attributes set correctly +- [ ] MoEngage dashboard shows GPT app users + +## Support + +If you encounter issues: + +1. Check browser console for errors +2. Review MoEngage dashboard for data +3. Verify all configuration steps +4. Check OpenAI/OpenAI Apps documentation +5. Review this guide's troubleshooting sections + +For MoEngage-specific issues, contact MoEngage support. +For ChatGPT Apps issues, check OpenAI documentation or support. + diff --git a/app/globals.css b/app/globals.css new file mode 100644 index 00000000..78f4c04d --- /dev/null +++ b/app/globals.css @@ -0,0 +1,51 @@ +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +body { + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + min-height: 100vh; + padding: 20px; + color: #333; +} + +.container { + max-width: 1200px; + margin: 0 auto; + background: white; + border-radius: 12px; + box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1); + padding: 30px; +} + +header { + text-align: center; + margin-bottom: 40px; + padding-bottom: 20px; + border-bottom: 2px solid #f0f0f0; +} + +header h1 { + color: #667eea; + font-size: 2.5em; + margin-bottom: 10px; +} + +.subtitle { + color: #666; + font-size: 1.1em; +} + +@media (max-width: 768px) { + .container { + padding: 20px; + } + + header h1 { + font-size: 2em; + } +} + diff --git a/app/layout.tsx b/app/layout.tsx new file mode 100644 index 00000000..d9e27c49 --- /dev/null +++ b/app/layout.tsx @@ -0,0 +1,26 @@ +import type { Metadata } from 'next'; +import './globals.css'; + +export const metadata: Metadata = { + title: 'MoEngage Sample App - ChatGPT Integration', + description: 'Sample application with MoEngage WebSDK integration for ChatGPT Apps', +}; + +export default function RootLayout({ + children, +}: { + children: React.ReactNode; +}) { + return ( + + +