npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@facebook-connector/client-sdk

v1.0.7

Published

Official SDK for Facebook Lead Ads Connector - Easy integration for tenants

Readme

Facebook Lead Ads Connector - Client SDK

Official SDK for integrating with Facebook Lead Ads Connector. Makes it dead simple for your tenants (CRM systems) to connect and receive leads.

🚀 Quick Start

Installation

npm install @facebook-connector/client-sdk

Basic Usage

import FacebookConnectorClient from '@facebook-connector/client-sdk';

const client = new FacebookConnectorClient({
  tenantId: 'your-tenant-id',
  apiBaseUrl: 'https://api.yourcompany.com/prod',
  apiKey: 'your-api-key', // Optional
});

// Initiate OAuth flow
client.initiateOAuth({
  successUrl: 'https://yourapp.com/oauth/success',
  errorUrl: 'https://yourapp.com/oauth/error',
});

📦 Installation Methods

Method 1: NPM Package (Recommended for Node.js/React/Vue)

npm install @facebook-connector/client-sdk
import FacebookConnectorClient, { WebhookValidator } from '@facebook-connector/client-sdk';

Method 2: CDN (For vanilla HTML/JS)

<script src="https://cdn.yourcompany.com/[email protected]/browser.min.js"></script>
<script>
  const client = new FacebookConnectorSDK.FacebookConnectorClient({
    tenantId: 'your-tenant-id',
    apiBaseUrl: 'https://api.yourcompany.com/prod',
  });
</script>

Method 3: Direct Download

Download facebook-connector-sdk.min.js from releases and include it:

<script src="/path/to/facebook-connector-sdk.min.js"></script>

🎯 Features

OAuth Flow - Simplified Facebook OAuth integration
Page Management - List, subscribe, and unsubscribe Facebook Pages
Webhook Validation - Secure HMAC-SHA256 signature verification
TypeScript Support - Full type definitions included
Browser & Node.js - Works everywhere
Zero Dependencies (browser bundle)

📖 Usage Examples

1. OAuth Integration (Frontend)

import FacebookConnectorClient from '@facebook-connector/client-sdk';

const client = new FacebookConnectorClient({
  tenantId: 'tenant-123',
  apiBaseUrl: 'https://api.yourcompany.com/prod',
});

// Button click handler
async function connectFacebook() {
  client.initiateOAuth({
    successUrl: window.location.origin + '/oauth/success',
    errorUrl: window.location.origin + '/oauth/error',
  });
}

2. Page Selection (After OAuth)

// After OAuth callback redirects to /oauth/success
async function selectPages() {
  // Get available pages
  const pages = await client.getPages();
  
  console.log('Available pages:', pages);
  
  // Let user select which pages to connect
  const selectedPageIds = ['page-123', 'page-456'];
  
  // Subscribe selected pages
  const result = await client.subscribePages({
    pageIds: selectedPageIds,
  });
  
  if (result.success) {
    console.log('✅ Subscribed:', result.subscribed);
  }
  
  if (result.failed.length > 0) {
    console.error('❌ Failed:', result.failed);
  }
}

3. Webhook Handler (Backend - Node.js/Express)

import express from 'express';
import { WebhookValidator } from '@facebook-connector/client-sdk';

const app = express();
const validator = new WebhookValidator('your-webhook-secret-min-32-chars');

// IMPORTANT: Use raw body for signature validation
app.post('/webhook/facebook-leads', 
  express.raw({ type: 'application/json' }),
  (req, res) => {
    const signature = req.headers['x-hub-signature-256'] as string;
    const result = validator.validate(req.body, signature);
    
    if (!result.valid) {
      console.error('Invalid webhook:', result.error);
      return res.sendStatus(401);
    }
    
    // Process lead
    const lead = result.payload!;
    console.log('New lead received:', {
      leadId: lead.leadId,
      formId: lead.formId,
      pageId: lead.pageId,
      data: lead.data,
    });
    
    // Store lead in your CRM
    await saveToCRM(lead);
    
    res.sendStatus(200);
  }
);

4. React Integration Example

import { useState, useEffect } from 'react';
import FacebookConnectorClient from '@facebook-connector/client-sdk';

const client = new FacebookConnectorClient({
  tenantId: process.env.REACT_APP_TENANT_ID!,
  apiBaseUrl: process.env.REACT_APP_API_URL!,
});

function FacebookIntegration() {
  const [pages, setPages] = useState([]);
  const [loading, setLoading] = useState(false);

  // Connect Facebook account
  const handleConnect = () => {
    client.initiateOAuth({
      successUrl: window.location.origin + '/facebook/success',
      errorUrl: window.location.origin + '/facebook/error',
    });
  };

  // Load pages after OAuth
  useEffect(() => {
    loadPages();
  }, []);

  const loadPages = async () => {
    setLoading(true);
    try {
      const fbPages = await client.getPages();
      setPages(fbPages);
    } catch (error) {
      console.error('Failed to load pages:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSubscribe = async (pageIds: string[]) => {
    const result = await client.subscribePages({ pageIds });
    if (result.success) {
      alert('Pages connected successfully!');
      loadPages(); // Refresh list
    }
  };

  return (
    <div>
      <button onClick={handleConnect}>
        Connect Facebook Account
      </button>
      
      {loading ? (
        <p>Loading pages...</p>
      ) : (
        <ul>
          {pages.map(page => (
            <li key={page.page_id}>
              {page.page_name} - {page.status}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

5. Vanilla JavaScript (CDN)

<!DOCTYPE html>
<html>
<head>
  <title>Facebook Lead Ads Integration</title>
  <script src="https://cdn.yourcompany.com/facebook-connector-sdk.min.js"></script>
</head>
<body>
  <button id="connectBtn">Connect Facebook</button>
  <div id="pages"></div>

  <script>
    const client = new FacebookConnectorSDK.FacebookConnectorClient({
      tenantId: 'your-tenant-id',
      apiBaseUrl: 'https://api.yourcompany.com/prod',
    });

    document.getElementById('connectBtn').addEventListener('click', () => {
      client.initiateOAuth({
        successUrl: window.location.origin + '/success.html',
        errorUrl: window.location.origin + '/error.html',
      });
    });

    // Load pages (call this on success page)
    async function loadPages() {
      const pages = await client.getPages();
      const container = document.getElementById('pages');
      
      pages.forEach(page => {
        const div = document.createElement('div');
        div.textContent = `${page.page_name} - ${page.status}`;
        container.appendChild(div);
      });
    }
  </script>
</body>
</html>

🔐 Webhook Security

The SDK includes built-in HMAC-SHA256 signature verification:

import { WebhookValidator } from '@facebook-connector/client-sdk';

const validator = new WebhookValidator('your-webhook-secret');

// Validate incoming webhook
const result = validator.validate(requestBody, signature);

if (result.valid) {
  console.log('Lead data:', result.payload);
} else {
  console.error('Security error:', result.error);
}

Important: Always validate webhook signatures to prevent spoofed requests!

📚 API Reference

FacebookConnectorClient

Constructor

new FacebookConnectorClient(config: SDKConfig)

Parameters:

  • tenantId (string, required) - Your unique tenant ID
  • apiBaseUrl (string, required) - Base URL of the connector API
  • apiKey (string, optional) - API key for authentication
  • webhookSecret (string, optional) - Secret for webhook validation

Methods

initiateOAuth(options: OAuthInitOptions): Promise<void>

Redirects user to Facebook OAuth flow.

getOAuthUrl(options: OAuthInitOptions): string

Returns OAuth URL without redirecting (useful for server-side).

getPages(): Promise<FacebookPage[]>

Fetches all Facebook Pages for the tenant.

subscribePages(request: SubscribePagesRequest): Promise<SubscribePagesResponse>

Subscribes selected pages to webhook notifications.

unsubscribePage(pageId: string): Promise<UnsubscribePageResponse>

Unsubscribes a specific page.

getActivePages(): Promise<FacebookPage[]>

Returns only active subscribed pages.

WebhookValidator

Constructor

new WebhookValidator(webhookSecret: string)

Methods

validate(payload: string | Buffer, signature: string): WebhookValidationResult

Validates webhook signature and parses payload.

isValid(payload: string | Buffer, signature: string): boolean

Quick boolean validation check.

🛠️ Development

Build SDK

cd sdk
npm install
npm run build

Outputs:

  • dist/index.js - CommonJS for Node.js
  • dist/index.mjs - ES modules
  • dist/browser.js - Browser bundle (UMD)
  • dist/facebook-connector-sdk.min.js - Minified CDN version

Run Tests

npm test

🌍 Browser Compatibility

  • ✅ Chrome 90+
  • ✅ Firefox 88+
  • ✅ Safari 14+
  • ✅ Edge 90+
  • ✅ Node.js 18+

📄 License

MIT

🤝 Support

  • Documentation: https://docs.yourcompany.com
  • Issues: https://github.com/your-org/facebook-connector-sdk/issues
  • Email: [email protected]

🚨 Security

Report security vulnerabilities to: [email protected]


Made with ❤️ by Your Company