Ignitech Modules - Facebook Pixel Integration
npm install @ignitech/modules-facebook-pixelbash
npm install @ignitech/modules-facebook-pixel
`
---
🚀 Quick Start
`typescript
import { initFacebookPixel, trackEvent } from '@ignitech/modules-facebook-pixel';
// Initialize
await initFacebookPixel({
websiteId: '550e8400-e29b-41d4-a716-446655440000',
apiBaseUrl: 'https://api.example.com',
});
// Track events
trackEvent('PageView');
trackEvent('ViewContent', { content_name: 'Product Name' });
`
---
📝 API Reference
$3
Khởi tạo Facebook Pixel module.
Parameters:
`typescript
interface InitConfig {
websiteId: string; // Required: Website ID
apiBaseUrl: string; // Required: Backend API base URL
autoTrackPageView?: boolean; // Optional: Auto track PageView (default: true)
debug?: boolean; // Optional: Enable debug logs (default: false)
}
`
Example:
`typescript
await initFacebookPixel({
websiteId: '550e8400-e29b-41d4-a716-446655440000',
apiBaseUrl: 'https://api.example.com',
autoTrackPageView: true,
debug: false,
});
`
Returns: Promise
---
$3
Track event đến Facebook Pixel và backend.
Parameters:
`typescript
trackEvent(
eventName: string, // Facebook Pixel event name
eventData?: object, // Event data
options?: {
sendToBackend?: boolean; // Also send to backend (default: true)
eventId?: string; // Custom event ID (auto-generated if not provided)
}
)
`
Example:
`typescript
// Simple event
trackEvent('PageView');
// Event with data
trackEvent('ViewContent', {
content_name: 'Laptop Dell XPS 15',
content_ids: ['prod_123'],
content_type: 'product',
value: 25000000,
currency: 'VND',
});
// Event with custom ID
trackEvent('Purchase', {
value: 50000000,
currency: 'VND',
}, {
eventId: 'custom_event_id_123',
});
`
---
$3
Helper function để track e-commerce events với format chuẩn.
Parameters:
`typescript
trackEcommerceEvent(
eventType: 'ViewContent' | 'AddToCart' | 'InitiateCheckout' | 'Purchase' | ...,
data: {
product?: {
productId: string;
productName: string;
productPrice: number;
quantity?: number;
};
products?: Array<{...}>; // For purchase events
orderId?: string;
orderValue?: number;
currency?: string;
}
)
`
Example:
`typescript
// View Product
trackEcommerceEvent('ViewContent', {
product: {
productId: 'prod_123',
productName: 'Laptop Dell XPS 15',
productPrice: 25000000,
},
currency: 'VND',
});
// Add to Cart
trackEcommerceEvent('AddToCart', {
product: {
productId: 'prod_123',
productName: 'Laptop Dell XPS 15',
productPrice: 25000000,
quantity: 1,
},
currency: 'VND',
});
// Purchase
trackEcommerceEvent('Purchase', {
orderId: 'ORD-2025-01-20-0001',
orderValue: 50000000,
products: [
{
productId: 'prod_123',
productName: 'Laptop Dell XPS 15',
productPrice: 25000000,
quantity: 1,
},
],
currency: 'VND',
});
`
---
$3
Kiểm tra xem Pixel có được enable không.
Returns: Promise
Example:
`typescript
const enabled = await isPixelEnabled();
if (enabled) {
trackEvent('CustomEvent');
}
`
---
$3
Lấy Pixel ID hiện tại.
Returns: Promise
---
🎯 Implementation Example
$3
`typescript
// app.ts or main.ts
import {
initFacebookPixel,
trackEcommerceEvent,
trackEvent
} from '@ignitech/modules-facebook-pixel';
// Initialize on app start
async function init() {
try {
await initFacebookPixel({
websiteId: '550e8400-e29b-41d4-a716-446655440000',
apiBaseUrl: process.env.API_BASE_URL || 'https://api.example.com',
autoTrackPageView: true,
debug: process.env.NODE_ENV === 'development',
});
console.log('Facebook Pixel initialized');
} catch (error) {
console.error('Failed to initialize Facebook Pixel:', error);
}
}
// Track product view
function onProductView(product: any) {
trackEcommerceEvent('ViewContent', {
product: {
productId: product.id,
productName: product.name,
productPrice: product.price,
},
currency: 'VND',
});
}
// Track add to cart
function onAddToCart(product: any, quantity: number = 1) {
trackEcommerceEvent('AddToCart', {
product: {
productId: product.id,
productName: product.name,
productPrice: product.price,
quantity,
},
currency: 'VND',
});
}
// Track purchase
function onPurchase(order: any) {
trackEcommerceEvent('Purchase', {
orderId: order.id,
orderValue: order.total,
products: order.items.map((item: any) => ({
productId: item.productId,
productName: item.productName,
productPrice: item.price,
quantity: item.quantity,
})),
currency: 'VND',
});
}
// Initialize
init();
`
---
🔄 Event Deduplication
Module tự động xử lý event deduplication:
1. Generate Event ID: Tự động tạo unique event ID cho mỗi event
2. Send to Pixel: Gửi event đến Facebook Pixel với eventID
3. Send to Backend: Gửi cùng event đến backend với facebookEventId
Facebook sẽ tự động deduplicate events có cùng event_id.
Example:
`typescript
// Module tự động:
// 1. Generate: eventId = "fbp_1705747200000_abc123"
// 2. fbq('track', 'AddToCart', data, { eventID: eventId })
// 3. POST /analytics/track/ecommerce { ..., facebookEventId: eventId }
`
---
⚙️ Configuration
$3
`env
.env
REACT_APP_API_BASE_URL=https://api.example.com
REACT_APP_WEBSITE_ID=550e8400-e29b-41d4-a716-446655440000
REACT_APP_PIXEL_DEBUG=false
`
$3
`typescript
// config.ts
export const pixelConfig = {
websiteId: process.env.REACT_APP_WEBSITE_ID!,
apiBaseUrl: process.env.REACT_APP_API_BASE_URL!,
autoTrackPageView: true,
debug: process.env.REACT_APP_PIXEL_DEBUG === 'true',
};
`
---
🎨 React Integration
$3
`typescript
// hooks/useFacebookPixel.ts
import { useEffect } from 'react';
import { initFacebookPixel, trackEvent } from '@ignitech/modules-facebook-pixel';
export function useFacebookPixel(websiteId: string) {
useEffect(() => {
initFacebookPixel({
websiteId,
apiBaseUrl: process.env.REACT_APP_API_BASE_URL!,
});
}, [websiteId]);
return {
trackEvent,
};
}
// Usage
function ProductPage({ product }) {
const { trackEvent } = useFacebookPixel(websiteId);
useEffect(() => {
trackEvent('ViewContent', {
content_name: product.name,
content_ids: [product.id],
value: product.price,
currency: 'VND',
});
}, [product]);
return ...;
}
`
$3
`typescript
// components/FacebookPixelProvider.tsx
import React, { useEffect, createContext, useContext } from 'react';
import { initFacebookPixel, trackEvent } from '@ignitech/modules-facebook-pixel';
const FacebookPixelContext = createContext<{
trackEvent: typeof trackEvent;
} | null>(null);
export function FacebookPixelProvider({
websiteId,
children,
}: {
websiteId: string;
children: React.ReactNode;
}) {
useEffect(() => {
initFacebookPixel({
websiteId,
apiBaseUrl: process.env.REACT_APP_API_BASE_URL!,
});
}, [websiteId]);
return (
{children}
);
}
export function useFacebookPixel() {
const context = useContext(FacebookPixelContext);
if (!context) {
throw new Error('useFacebookPixel must be used within FacebookPixelProvider');
}
return context;
}
// Usage in App.tsx
function App() {
return (
);
}
`
---
🛠️ Vue.js Integration
`typescript
// plugins/facebook-pixel.ts
import { initFacebookPixel, trackEvent } from '@ignitech/modules-facebook-pixel';
export default {
install(app: any, options: { websiteId: string; apiBaseUrl: string }) {
initFacebookPixel({
websiteId: options.websiteId,
apiBaseUrl: options.apiBaseUrl,
});
app.config.globalProperties.$trackEvent = trackEvent;
},
};
// main.ts
import FacebookPixel from './plugins/facebook-pixel';
app.use(FacebookPixel, {
websiteId: '550e8400-e29b-41d4-a716-446655440000',
apiBaseUrl: 'https://api.example.com',
});
// Usage in component
this.$trackEvent('ViewContent', { ... });
`
---
📊 Supported Events
Module hỗ trợ tất cả Facebook Pixel Standard Events:
| Event | Description | Usage |
|-------|-------------|-------|
| PageView | Page view | Auto-tracked |
| ViewContent | View product/content | trackEcommerceEvent('ViewContent', {...}) |
| AddToCart | Add item to cart | trackEcommerceEvent('AddToCart', {...}) |
| InitiateCheckout | Begin checkout | trackEcommerceEvent('InitiateCheckout', {...}) |
| AddPaymentInfo | Add payment info | trackEcommerceEvent('AddPaymentInfo', {...}) |
| Purchase | Complete purchase | trackEcommerceEvent('Purchase', {...}) |
| Lead | Form submission | trackEvent('Lead', {...}) |
| Search | Search query | trackEvent('Search', {...}) |
| ViewCategory | View category | trackEvent('ViewCategory', {...}) |
| AddToWishlist | Add to wishlist | trackEvent('AddToWishlist', {...}) |
---
🐛 Error Handling
Module tự động xử lý errors:
- ✅ Pixel không được cấu hình → Silent fail
- ✅ Pixel bị disable → Silent fail
- ✅ API error → Log warning, không break app
- ✅ Network error → Retry logic
Debug Mode:
`typescript
initFacebookPixel({
websiteId: '...',
apiBaseUrl: '...',
debug: true, // Enable console logs
});
`
---
📦 Build & Distribution
$3
`bash
Install dependencies
npm install
Build
npm run build
Output:
- dist/index.js (CommonJS)
- dist/index.mjs (ES Module)
- dist/index.d.ts (TypeScript definitions)
`
$3
`bash
npm publish --access public
`
---
✅ Integration Checklist
Cho mỗi website mới:
- [ ] Install module: npm install @ignitech/modules-facebook-pixel
- [ ] Import và init trong app entry point
- [ ] Pass websiteId và apiBaseUrl
- [ ] Test với một event (PageView)
- [ ] Verify events trong Facebook Events Manager
- [ ] Test event deduplication
---
🆘 Troubleshooting
$3
1. Kiểm tra websiteId đúng chưa
2. Kiểm tra apiBaseUrl có thể access được không
3. Kiểm tra Pixel có được enable trong admin panel không
4. Enable debug mode để xem logs
$3
1. Kiểm tra Network tab xem API calls có thành công không
2. Kiểm tra Facebook Events Manager > Test Events
3. Kiểm tra Pixel ID đúng chưa
4. Kiểm tra console logs (nếu debug mode)
$3
1. Đảm bảo chỉ init module 1 lần
2. Kiểm tra event_id được generate đúng
3. Verify backend nhận được facebookEventId`