Meta Lead Ads to Google Sheets to a Database with Apps Script (No Zapier)

By Rohan Babbar6 min read
Meta Lead Ads to Google Sheets to a Database with Apps Script (No Zapier)

Meta tells you how many leads a campaign produced. It doesn't tell you which of those leads became customers. To answer that, I built a pipeline that moves every lead from Google Sheets into a Postgres database with Google Apps Script, cleans it, and joins it to bookings. No Zapier, and no paid connector.

This is how it works, with the code patterns, what broke along the way, and what it now shows. I built it for an Ayurvedic wellness group with three brands, syncing Meta Lead Ads, website enquiries and bookings.

Why not just use Zapier or a lead connector?

  • Cost and limits. Lead connectors charge per task or per lead, and a premium Meta integration usually needs a paid plan.
  • Control. I needed to clean phone numbers, flag bad leads and match leads to bookings. That logic has to live somewhere I can read and change.
  • Everything in one place. Meta leads, website leads and bookings all needed to land in the same database to be joined.

How the pipeline works

  1. Leads land in Google Sheets. In my setup, each lead source already arrives in its own Google Sheet: Meta Lead Ads instant forms, website enquiries, and bookings. Everything after this step is Apps Script.
  2. Apps Script reads only the new rows, maps each one to a standard lead record, and cleans it.
  3. Bad or suspicious leads are flagged, not deleted.
  4. Rows are pushed to a Postgres database (Supabase) through its REST API.
  5. A schedule keeps it current: leads every 15 minutes (only new rows), bookings once a day (a full rescan, because bookings change status).
  6. In the database, leads are joined to bookings, so revenue can be traced back to the channel that produced it.

Step 1: One config for every sheet

Each source is a single config entry. Adding a new brand or lead source means adding one line, not new code:

const SOURCES = {
  brandAFacebook: { id: 'SHEET_ID', gid: 0, type: 'facebook', brand: 'brand_a' },
  brandAWebsite:  { id: 'SHEET_ID', gid: 0, type: 'website',  brand: 'brand_a' },
  brandABookings: { id: 'SHEET_ID', gid: 0, type: 'bookings', headerRow: 8, rescanAll: true },
};

rescanAll marks sources that are re-read in full each time, like bookings. Everything else is synced incrementally.

Step 2: Sync only the new rows

Re-reading thousands of rows every 15 minutes is slow and creates duplicates. Instead, the script stores the last synced row number for each sheet in Script Properties, and only reads rows after it:

const props = PropertiesService.getScriptProperties();
const last = parseInt(props.getProperty('lastRow_' + key) || String(headerRow), 10);
if (sheet.getLastRow() <= last) return; // nothing new

const values = sheet.getRange(last + 1, 1, sheet.getLastRow() - last, lastCol).getValues();
const records = values.map(toObject).map(r => mapFacebookRow(r, cfg.brand)).filter(Boolean);

if (records.length && !pushToDatabase('leads', records)) return; // push failed: don't move the pointer
props.setProperty('lastRow_' + key, String(lastNonEmptyRow));

The most important line is the last one. The pointer only moves after a successful push. If the database rejects a batch, the next run retries the same rows instead of skipping them.

Step 3: Clean the data before it lands

Raw lead data is messy. Phone numbers are the worst: "+91 98xxxxxxxx", "098xxxxxxxx", two numbers in one cell separated by a slash. Matching leads to bookings later depends on every number being stored the same way:

function normalizePhone(raw) {
  const candidates = String(raw).split(/[/,;]/)
    .map(p => p.replace(/\D/g, '')).filter(Boolean);
  // score(): prefers a valid 10-digit Indian mobile, then longer international numbers
  let best = candidates.sort((a, b) => score(b) - score(a))[0];
  if (best.length === 12 && best.startsWith('91')) best = best.slice(2); // drop country code
  if (best.length === 11 && best.startsWith('0'))  best = best.slice(1); // drop leading 0
  return { normalized: best, ambiguous: candidates.length > 1 };
}

Emails are trimmed and lowercased the same way. The original values are kept next to the cleaned ones, so nothing is lost.

Step 4: Flag bad leads, don't delete them

Every lead gets checked, and anything suspicious is flagged with a reason:

  • Multiple phone numbers in one field
  • Phone number in an unusual format
  • Bot-like email addresses (lots of very short dot-separated segments)
  • Internal emails from the company's own domain (test submissions)
  • Duplicates already marked by the source

Flagged leads stay in the database with is_flagged and a flag_reason. Reports can then exclude them, and you can see which campaigns produce the most junk.

Step 5: Website leads need a channel

Website enquiries don't arrive labelled "Google" or "Meta". The script works it out from what the form captured, in order:

  1. UTM source (google, facebook, meta and similar)
  2. UTM medium (cpc, ppc, metaads and similar)
  3. A Google click ID (gclid) on the form
  4. Google click ID patterns found inside the message text

If none match, the lead isn't counted as paid. Guessing would inflate a channel's numbers.

Step 6: Push in chunks, upsert where rows change

Rows go to the database through its REST API in chunks of 500. Leads are inserted. Bookings are upserted on brand + order_id, so a booking that changes status updates its existing row instead of creating a duplicate:

UrlFetchApp.fetch(`${url}/rest/v1/bookings?on_conflict=brand,order_id`, {
  method: 'post', contentType: 'application/json',
  headers: { apikey: key, Authorization: `Bearer ${key}`,
             Prefer: 'resolution=merge-duplicates,return=minimal' },
  payload: JSON.stringify(chunk), muteHttpExceptions: true,
});

The database URL and key live in Script Properties, never in the code.

What broke (and the fixes)

  • One brand showed 0.00x ROAS on every channel. The bookings were there, but that brand's bookings live in a different sheet layout where the status fields the "active booking" check reads were empty. Every row failed the check. The fix was a separate check for that brand's layout, leaving the original untouched so the verified numbers for the other brands couldn't move.
  • A sync pointer stalled. For one sheet, the stored row number ended up at or past the sheet's real last row, so new leads stopped syncing without any error. I added a read-only diagnostic that prints each sheet's last row, its pointer and how many rows are pending, and flags any pointer that's stuck.
  • Revenue queries got too big. Matching bookings to leads with filters in the request URL hit a "414 URI Too Large" error. Moving the matching into a SQL function inside the database fixed it.

What it shows now

Joined with ad spend, the lead and booking data shows where the funnel breaks: creative fatigue, wasted spend, gaps in negative keywords, and which regions send leads that actually convert. It feeds the marketing dashboards I use to manage ₹15L+/month across Google Ads, YouTube and Meta, at 10–15x ROAS on high-intent campaigns.

More on the systems around it: systems I've built. If you want a pipeline like this for your own leads, or help with paid media, see Google Ads expert in India.

FAQ

Can I send Meta Lead Ads leads to Google Sheets without Zapier?

Once your leads are in a Google Sheet, Apps Script can do everything after that for free: clean the data, flag bad leads and push it to a database on a schedule. How leads first reach the sheet depends on your setup.

How often can Apps Script sync leads?

Time-based triggers can run as often as every few minutes. I sync new leads every 15 minutes and re-read bookings once a day.

How do you avoid duplicate leads?

By syncing incrementally from a stored row pointer that only moves after a successful push, and by upserting rows that change, like bookings, on a unique key.

Where should the database key go?

In Script Properties, not in the code. Anyone who can see the code shouldn't automatically see your keys.

Why flag bad leads instead of deleting them?

Deleted leads can't be analysed. Flagged leads can be excluded from reports and still show which campaigns produce junk.


I'm Rohan Babbar, a Digital Marketing Manager in Delhi who builds the systems that measure paid media and SEO. Connect with me on LinkedIn.

meta adslead adsgoogle sheetsapps scriptsupabaseattribution
ShareLinkedInX
Rohan Babbar
Rohan Babbar

Digital marketing, SEO and paid media. Connect on LinkedIn