# Meta Lead Ads Integration — Setup Guide

This guide covers how to connect a **new client** in FormHub to Meta (Facebook) Lead Ads so leads flow into **Submissions** automatically.

---

## Overview

| Layer | What it does |
|-------|----------------|
| **FormHub Meta App** (one-time) | Shared Facebook app credentials in `.env` |
| **Client** | Each customer in FormHub (e.g. Attrarre) |
| **Meta Page connection** | Links a Facebook Page to that client |
| **Form mapping** | Links each Meta instant form → a FormHub **Project** |
| **Webhook** | Meta sends new leads to FormHub in real time |

**Flow:** Meta Lead Ad submitted → Facebook webhook → FormHub queue → Submission created → email sent (new leads only).

---

## Part 1 — One-time setup (already done for production)

Skip this if FormHub Meta is already working for another client (e.g. Attrarre).

### 1.1 Meta Developer App

1. Go to [developers.facebook.com/apps](https://developers.facebook.com/apps)
2. Use the shared app (e.g. **Form Hub**)
3. Add use case: **Capture & manage ad leads with Marketing API**
4. Ensure these permissions are enabled:
   - `business_management`
   - `pages_manage_ads`
   - `pages_manage_metadata`
   - `pages_read_engagement`
   - `pages_show_list`
   - `leads_retrieval`
5. **Publish** the app (required for real leads; test webhooks only work in Development mode)

### 1.2 FormHub environment (`.env`)

```env
META_APP_ID=your_app_id
META_APP_SECRET=your_app_secret
META_VERIFY_TOKEN=your_random_verify_string
APP_URL=https://formhub.dsignxt.com
QUEUE_CONNECTION=database
```

After changes:

```bash
php artisan config:clear
php artisan optimize:clear
```

### 1.3 Meta Developer Console — URLs

In the app settings, configure:

| Setting | URL |
|---------|-----|
| **Webhook callback** | `https://formhub.dsignxt.com/webhooks/meta/leads` |
| **Verify token** | Same as `META_VERIFY_TOKEN` in `.env` |
| **OAuth redirect** | `https://formhub.dsignxt.com/meta/oauth/callback` |

**Webhook subscription:** Subscribe to **Page** object, field **`leadgen`**.

Verify webhook (should return the challenge string):

```bash
curl "https://formhub.dsignxt.com/webhooks/meta/leads?hub.mode=subscribe&hub.verify_token=YOUR_VERIFY_TOKEN&hub.challenge=test123"
```

### 1.4 Scheduler + queue (for new leads)

Webhook leads are queued immediately. Woodscape and other pages also use a **recent-lead sync every 10 minutes** as a fallback when Meta webhooks lag or fail:

```bash
# Cron (required for scheduled sync)
* * * * * cd /var/www/html/projects/formhub && php artisan schedule:run >> /dev/null 2>&1
```

Manual catch-up for one Page:

```bash
php artisan meta:sync-recent-leads CONNECTION_ID
php artisan meta:sync-recent-leads --all
```

New webhook leads are processed by a background worker:

```bash
sudo supervisorctl status
```

If no worker exists, create `/etc/supervisor/conf.d/formhub-worker.conf`:

```ini
[program:formhub-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/html/projects/formhub/artisan queue:work database --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=1
redirect_stderr=true
stdout_logfile=/var/www/html/projects/formhub/storage/logs/worker.log
stopwaitsecs=3600
```

Then:

```bash
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start formhub-worker
```

---

## Part 2 — New client setup (do this for every client)

### Access

All Meta integration setup (connect Pages, sync forms, mappings, import) is **Super Admin only**. Client Admins and Project Users can still view **Submissions** from Meta leads but cannot manage the integration.

### Step 1 — Create the client in FormHub

1. Log in as **Super Admin**
2. **Clients → Add Client**
3. Fill company name, contact, status **Active**
4. Save

### Step 2 — Create project(s)

1. **Projects → Add Project**
2. Assign to the new client
3. Set status **Active**
4. Create one project per lead destination (e.g. “Client Name — Product Line”)

Each **Meta instant form** will be mapped to **one project**.

### Step 3 — Facebook / Meta prerequisites

The person connecting Pages must:

- Be **Admin** of the Facebook Page(s) in Meta Business Suite
- Have access to the Page in [facebook.com](https://facebook.com) Page settings → **Page access**
- Run lead ads from instant forms on those Pages

**Pages in Business Suite:** During OAuth, tick each Page when Facebook asks **“Choose the Pages…”** (Opt in to current Pages only).

### Step 4 — Connect Facebook Page(s)

1. **Clients → [Client name]**
2. Scroll to **Meta Lead Ads**
3. Click **Connect Facebook Page**
4. Log in with the Facebook account that manages the Pages
5. Allow all requested permissions
6. On **Choose the Pages**, tick every Page for this client → **Continue**
7. On **Select Meta Pages** in FormHub, tick Pages → **Connect Selected Pages**

**Expected result on client profile:**

| Column | Expected |
|--------|----------|
| Status | Active |
| Webhook | Subscribed |
| Mappings | 0 (until Step 6) |

### Step 5 — Sync lead forms

For each connected Page:

1. Click the **sync** button (circular arrows) on the Page row  
   — or use **Meta Integrations** overview page
2. Note the synced form names and IDs (shown in a flash message or on the project page)

If sync fails with permission errors, **disconnect and reconnect** the Page after confirming Meta app permissions include `pages_manage_ads`.

### Step 6 — Map forms to projects

1. **Projects → [Project name]**
2. Scroll to **Meta Form Mappings**
3. **Select Meta Page** → **Select Meta Form** → **Add Mapping**
4. Repeat for every instant form that should feed that project

**Important:** Unmapped forms are **ignored** — leads will not appear in Submissions.

Example:

| Meta Page | Meta Form | FormHub Project |
|-----------|-----------|-----------------|
| Brand Page A | Summer Promo Form | Brand — Campaigns |
| Brand Page B | Contact Form | Brand — General |

### Step 7 — Import past leads (optional)

To pull **historical** leads from Meta (no emails sent):

**Option A — UI**

1. **Clients → [Client]** → Meta Lead Ads
2. Click the green **cloud download** button on the Page row
3. Confirm

**Option B — Server command**

```bash
cd /var/www/html/projects/formhub

# List connection IDs
php artisan tinker --execute='App\Models\MetaConnection::with("client")->get(["id","client_id","page_name"])->each(fn($c) => print($c->id." ".$c->page_name.PHP_EOL));'

# Import for one Page (replace CONNECTION_ID)
php artisan meta:import-leads CONNECTION_ID

# Import all connected Pages
php artisan meta:import-leads --all
```

| Import type | Emails sent? |
|-------------|--------------|
| Historical import | **No** |
| New webhook leads | **Yes** (if project mail is configured) |

Already-imported leads (same Meta lead ID) are skipped automatically.

### Step 8 — Test a new lead

1. Submit a test lead from Meta Ads Manager or a live ad
2. Wait 1–2 minutes
3. Check **Submissions** under the mapped project

**Do not rely on** Meta Developer Console **Test** webhook for real Pages — it uses fake IDs. Use a real form submission or Ads Manager test lead.

---

## Part 3 — Checklist for a new client

```
[ ] Client created (Active)
[ ] Project(s) created (Active)
[ ] Facebook Page Admin access confirmed
[ ] Connect Facebook Page (OAuth + page selection)
[ ] Page shows Active + Subscribed
[ ] Forms synced from Meta
[ ] Each form mapped to correct project
[ ] (Optional) Historical leads imported
[ ] Test lead appears in Submissions
[ ] Queue worker running (for ongoing leads)
```

---

## Part 4 — Where to manage things

| Task | Location |
|------|----------|
| Connect / disconnect Pages | **Clients → [Client] → Meta Lead Ads** |
| Sync forms, resubscribe webhook, import past leads | Client profile or **Meta Integrations** |
| Map form → project | **Projects → [Project] → Meta Form Mappings** |
| View leads | **Submissions** |
| Monitor all Pages | **Meta Integrations** (Management menu) |
| Meta app URLs / config status | **Settings** (Super Admin) |

---

## Part 5 — Reconnect / refresh tokens

Do this when:

- Permissions were added in Meta app (`pages_manage_ads`, `business_management`, etc.)
- Sync forms returns 403
- Webhook shows “Not subscribed”

1. **Clients → [Client]**
2. Disconnect Page (X button) — or reconnect without disconnecting to refresh token
3. **Connect Facebook Page** again
4. Select Pages on Facebook OAuth screen
5. **Connect Selected Pages**
6. **Sync forms** again
7. Re-verify mappings still exist

---

## Part 6 — Troubleshooting

| Problem | Likely cause | Fix |
|---------|--------------|-----|
| No Facebook Pages found | Pages not selected during OAuth, or missing `business_management` | Reconnect; tick Pages on Facebook; add permission in Meta app |
| Unable to fetch lead forms (403) | Missing `pages_manage_ads` on token | Add permission in Meta app; disconnect & reconnect Page |
| Leads not arriving (real ads) | App unpublished, unmapped form, or queue worker down | Publish app; map form; check `sudo supervisorctl status` |
| Webhook test works but real leads don’t | App in Development mode | Publish Meta app |
| Lead ignored in logs: no active connection | Wrong `page_id` or Page disconnected | Reconnect Page |
| Lead ignored: no form mapping | Form not mapped to project | Add mapping on project page |
| Duplicate in Duplicate Leads | Same person submitted twice same day | Expected behaviour |
| Meta Integrations page empty | Pagination bug (fixed in latest code) | Deploy latest `MetaConnectionController.php` |

**Logs:**

```bash
cd /var/www/html/projects/formhub
grep -i "meta lead" storage/logs/laravel.log | tail -n 20
```

---

## Part 7 — Server deploy (after code updates)

When Meta-related code is updated:

```bash
cd /var/www/html/projects/formhub
php artisan migrate --force          # if new migrations
php artisan optimize:clear
sudo systemctl reload apache2
sudo supervisorctl restart formhub-worker   # if worker exists
```

---

## Quick reference — Attrarre example

| Item | Value |
|------|-------|
| Client | Attrarre |
| Pages | Attrarre Leathers, Attrarre Living |
| Project | Attrarre Hides (leather forms) |
| Webhook URL | `https://formhub.dsignxt.com/webhooks/meta/leads` |
| OAuth callback | `https://formhub.dsignxt.com/meta/oauth/callback` |

Use the same Meta app for all clients; each client gets its own Page connections and form mappings in the database.
