opscms-meta-plugin 0.0.0-stage → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/CHANGELOG.md +189 -0
  2. package/LICENSE +21 -0
  3. package/README.md +338 -2
  4. package/dist/chunk-HCQSD757.mjs +142 -0
  5. package/dist/chunk-QEVRQKSQ.mjs +26 -0
  6. package/dist/components/MetaCatalogSync/index.d.mts +10 -0
  7. package/dist/components/MetaCatalogSync/index.d.ts +10 -0
  8. package/dist/components/MetaCatalogSync/index.js +195 -0
  9. package/dist/components/MetaCatalogSync/index.mjs +108 -0
  10. package/dist/components/MetaConnectPanel/index.d.mts +20 -0
  11. package/dist/components/MetaConnectPanel/index.d.ts +20 -0
  12. package/dist/components/MetaConnectPanel/index.js +723 -0
  13. package/dist/components/MetaConnectPanel/index.mjs +554 -0
  14. package/dist/components/MetaLoginButton/index.d.mts +5 -0
  15. package/dist/components/MetaLoginButton/index.d.ts +5 -0
  16. package/dist/components/MetaLoginButton/index.js +82 -0
  17. package/dist/components/MetaLoginButton/index.mjs +58 -0
  18. package/dist/components/MetaPixelSelect/index.d.mts +11 -0
  19. package/dist/components/MetaPixelSelect/index.d.ts +11 -0
  20. package/dist/components/MetaPixelSelect/index.js +202 -0
  21. package/dist/components/MetaPixelSelect/index.mjs +115 -0
  22. package/dist/components/ThreadsConnectPanel/index.d.mts +10 -0
  23. package/dist/components/ThreadsConnectPanel/index.d.ts +10 -0
  24. package/dist/components/ThreadsConnectPanel/index.js +163 -0
  25. package/dist/components/ThreadsConnectPanel/index.mjs +56 -0
  26. package/dist/index.d.mts +376 -0
  27. package/dist/index.d.ts +376 -0
  28. package/dist/index.js +3563 -0
  29. package/dist/index.mjs +3503 -0
  30. package/icon.svg +1 -0
  31. package/package.json +109 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,189 @@
1
+ # Changelog
2
+
3
+ ## 0.4.2
4
+
5
+ ### Fixed
6
+
7
+ - **An admin's page load no longer fires a dozen of the heaviest queries at once.** To scope an admin to the sites of their organization, each
8
+ collection's access rule looked the sites up, reading whole site rows (every menu, footer column and translation) just to keep the ids, and
9
+ all of a request's rules did so at the same moment, each sending its own copy. For an admin with several sites that was enough to time the
10
+ database out ("Failed query: select ... from sites ..."). The lookup now asks for the ids alone and the rules of one request share one query.
11
+
12
+ ## 0.4.1
13
+
14
+ ### Changed
15
+
16
+ - **Facebook sign-in is closed to two kinds of account.** The platform owner (super-admin) signs in with email and password only, and
17
+ an account that has two-factor sign-in switched on cannot be signed in by Facebook (Facebook cannot give a one-time code, so it
18
+ would be a way round the second factor). Both are checked before any account is linked. The login page explains why with two new
19
+ messages (`not_allowed`, `two_factor`).
20
+
21
+ ## 0.4.0
22
+
23
+ ### Added
24
+
25
+ - **Sign in to the platform with Facebook.** The login page gets a "Continue with Facebook" button (shown only when the Meta app
26
+ is configured). Facebook is asked for the person's name and email only. If an account already uses that Facebook account, they are
27
+ signed in; otherwise an account whose email is the same as their Facebook email is joined to it, and from then on they sign in by
28
+ Facebook id. Nobody is ever signed in on a different email, and signing in never creates an account (accounts are made by
29
+ invitation). A suspended account is refused, and an account already joined to a different Facebook account is not overwritten.
30
+ The session is the same one a password login creates (the platform's own sign-in hooks run, so audit rows and the sign-in event
31
+ behave as usual). Endpoints: `GET /api/meta-login/status`, `/start`, `/callback`, and `POST /api/meta-login/unlink` for a person
32
+ to disconnect their own Facebook account. A one-time cookie guards against forged sign-ins. The host gains one column on its
33
+ users collection (`facebookId`, unique): it needs a migration. Register `<server>/api/meta-login/callback` as a valid OAuth
34
+ redirect URI in the Meta app's Facebook Login settings. New optional `host.rateLimit` throttles the endpoints.
35
+ - The plugin delivers the WhatsApp notification channel itself. A site that
36
+ connected an official WhatsApp number on its Facebook login sends the host
37
+ CMS's notifications from that number, through the Cloud API. The plugin
38
+ registers the service with the host's notification channel registry when it
39
+ is added to the config, so the host needs no Meta code of its own.
40
+ - A message goes out as an approved template when the host names one
41
+ (`template: { name, languageCode, bodyParameters }`) and as free text when it
42
+ does not. Building that reference from the user's template is the host's job.
43
+ - `META_PHONE_NUMBER_ID` and `META_ACCESS_TOKEN` in the environment are the
44
+ fallback for a host with no connected site.
45
+
46
+ - **Template approval.** When a workflow that sends a notification template by
47
+ WhatsApp is saved, and the site's WhatsApp carrier is Meta, the plugin submits
48
+ that template's message text to Meta for approval. It is the same plain-text
49
+ message SMS sends: there is no separate "Meta template". The wording is
50
+ converted to Meta's format (the user's `{{doc.values.first_name}}` becomes a
51
+ named placeholder Meta accepts, remembered so the value can be filled in at
52
+ send time) and checked against Meta's rules first, so wording Meta would
53
+ refuse is reported in plain words without being sent. Changing a template's
54
+ wording submits it again; an unchanged one is never resubmitted.
55
+ - **Sending waits for approval.** A message goes out by naming the approved
56
+ template and giving the values; Meta fills in its wording. While Meta is still
57
+ reviewing, the message is held and sent once approved. If Meta rejects,
58
+ pauses or disables it, or it could not be submitted, the message is not sent
59
+ by WhatsApp and says why.
60
+ - **Alerts.** A template that is not approved raises the host event
61
+ `meta.template.needs_attention` (once per problem), with the template key,
62
+ Meta's reason and the site's name. The host's workflow tells the owner.
63
+ - **Status on the template.** The notification template shows a read-only
64
+ "WhatsApp delivery through Meta" line with where each of the signed-in
65
+ person's sites stands. It is computed, not stored, and reads through that
66
+ person's own access.
67
+ - Approval status comes back by the webhook below, and a scheduled job
68
+ (`meta-template-status`, every five minutes) asks Meta about templates still in
69
+ review and retries the ones that could not be submitted, so nothing waits for
70
+ ever if the callback is not registered yet. The bookkeeping lives in a hidden
71
+ `meta-approvals` collection (host migration required).
72
+ - A webhook for Meta to call: `GET /api/meta-webhook` answers the handshake and
73
+ `POST /api/meta-webhook` receives deliveries. Each delivery's signature
74
+ (`X-Hub-Signature-256`, checked with `META_APP_SECRET`) is verified before
75
+ the body is read. Template changes (approved, rejected, paused,
76
+ recategorised, quality) become host events: `meta.template.status_changed`,
77
+ `meta.template.category_changed`, `meta.template.quality_changed` and
78
+ `meta.template.components_changed`, one per site that connected that
79
+ business account, with a stable `eventId` so a repeat can be dropped. The
80
+ plugin reports; the host's workflows decide what to do. Pass the engine as
81
+ `metaPlugin({ host: { emitSystemEvent } })`.
82
+ - Choosing a WhatsApp number subscribes that business account to the app with
83
+ the site's own token, and Disconnect removes the subscription, so Meta sends
84
+ that account's events to the webhook.
85
+
86
+ ### Removed
87
+
88
+ - The three templates written into the plugin (`ops_enquiry_guest`,
89
+ `ops_enquiry_owner`, `ops_alerts_ready`), with their wording and their fixed
90
+ variable paths, and everything built on them: filing them with Meta when a
91
+ number is chosen, the `GET`/`POST /meta-whatsapp/templates` endpoints, the
92
+ alert-status card on the connect screen, the `whatsapp-alert-approval` job
93
+ and the `whatsappAlertsAnnouncedAt` field. Message templates are the user's,
94
+ written in the host's automation; submitting those for Meta's approval is
95
+ the next piece of work.
96
+ - `whatsappTemplateMessage`, `alertStatusForConfig`, `fileMissingAlertTemplates`
97
+ and `WHATSAPP_ALERTS_READY_KEY` are no longer exported.
98
+ `explainTemplateSendError` stays.
99
+ - The host no longer reads the older manual Cloud API fields from its own
100
+ notification settings. The connection screen is the way to set up an
101
+ official number.
102
+
103
+ ## 0.3.2
104
+
105
+ ### Fixed
106
+
107
+ - The workflow conversion step stays on the collection the plugin registers.
108
+ The previous release wrote that step onto the original collection and returned
109
+ a different object.
110
+
111
+ ## 0.3.1
112
+
113
+ ### Fixed
114
+
115
+ - An organization admin can configure Meta for every site in their organization.
116
+ Their account has no single site, and the previous check rejected that account.
117
+
118
+ ## 0.3.0
119
+
120
+ ### Added
121
+
122
+ - Each site connects with its own Facebook login. The connection screen shows
123
+ that account's name, and another site cannot reuse it.
124
+ - Commerce catalogue items sync to the site's Meta catalog when they are
125
+ saved or deleted. A "Sync commerce products now" action sends the whole
126
+ catalogue, the same way the WooCommerce Facebook plugin pushes products.
127
+ - After Facebook login, the same screen asks for the Page, catalog, and
128
+ Pixel. A site with none can create the catalog or Pixel there.
129
+ - Official WhatsApp numbers on that Facebook login can be chosen for Payload
130
+ notifications. The OpenWA bridge remains for sites that do not choose one.
131
+ - Choosing that number files the enquiry alert messages on the site's own
132
+ WhatsApp account, including a short note that alerts are ready. The connect
133
+ screen shows one status — preparing, Meta is reviewing (safe to leave),
134
+ ready, or a single retry — and official alerts send as those messages once
135
+ Meta approves them. The CMS keeps checking and tells the owner through a
136
+ workflow when that happens.
137
+
138
+ ## 0.2.2
139
+
140
+ ### Added
141
+
142
+ - Test suite for credential encryption, OAuth state signing, Conversions API
143
+ payloads, the catalog feed, and per-site access control.
144
+
145
+ ### Fixed
146
+
147
+ - Resetting the encryption key in tests left the OAuth state secret cached, so
148
+ a later test could accept a state token signed with the previous secret.
149
+
150
+ ### Changed
151
+
152
+ - Removed unsafe casts in the plugin source.
153
+ - Documented the canonical sources for the mirrored `organizationField` and
154
+ credential-crypto helpers.
155
+
156
+ ## 0.2.1
157
+
158
+ ### Fixed
159
+
160
+ - Removed a hardcoded fallback secret.
161
+
162
+ ### Changed
163
+
164
+ - Widened the `@payloadcms/ui` peer dependency to `^3.84.1 || ^3.86.0`.
165
+
166
+ ## 0.2.0
167
+
168
+ ### Added
169
+
170
+ - One platform Meta App (`META_APP_ID` / `META_APP_SECRET`) for every tenant.
171
+ Sites connect through it with OAuth. They do not create their own App, and
172
+ the admin UI shows a masked App ID plus the connected Page and Instagram
173
+ account.
174
+ - SHA-256 hashing of email and phone on the Trigger Meta Conversion Event
175
+ step, so match data sent to Meta is never the raw value.
176
+
177
+ ### Changed
178
+
179
+ - Commerce Catalog feed currency default is NGN.
180
+ - Production startup fails without `META_ENCRYPTION_KEY` unless
181
+ `ALLOW_PLAINTEXT_META_CREDS=true`.
182
+
183
+ ## 0.1.0
184
+
185
+ ### Added
186
+
187
+ - Initial release. Per-site `meta-config` with encrypted credentials, Meta
188
+ Business Login, Threads connect, server-side Conversions API, and a Commerce
189
+ Catalog CSV feed.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 puzzo-dev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,339 @@
1
- # Temporary Holding Version
1
+ # opscms-meta-plugin
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A self-contained **Payload CMS 3.x plugin** for connecting multi-tenant sites to Meta's network (Facebook, Instagram, WhatsApp).
4
+
5
+ Modeled on the official "Meta for WooCommerce"/"Facebook for WordPress" plugins, but **modular per-channel and per-site** — a site enables only the Meta channels it actually needs, instead of every site being wired to one hardcoded product line. A B2B services site might only want the Pixel + Conversions API; an e-commerce site might want Pixel + Commerce Catalog + WhatsApp.
6
+
7
+ It provides:
8
+
9
+ - **Meta Connection Configuration** per site (multi-tenant) with encrypted credentials — same architecture as [`opscms-erpnext-plugin`](../opscms-erpnext-plugin).
10
+ - **"Connect to Meta Business" OAuth flow** — the same connector UX as the official Meta for WordPress plugin: authorize once, pick a Facebook Page you manage, its linked Instagram Business account is auto-detected, then select an existing Pixel or create a new one. **Manual credential entry stays fully available side by side** — OAuth is a convenience, not a requirement.
11
+ - **Threads connect flow** — separate from the Facebook/Instagram connector (Threads is its own API/host, see [Connecting Facebook, Instagram, and Threads](#connecting-facebook-instagram-and-threads)), also with manual token entry as a fallback.
12
+ - **Server-Side Conversions API** — a `sendConversionEvent()` helper and a `meta-conversion-event` action registered into the CMS workflow engine, so any Workflow can fire a "Trigger Meta Conversion Event" step (order created → `Purchase`, contact form submitted → `Lead`, etc.).
13
+ - **Commerce Catalog Feed** — `GET /api/meta-catalog/feed?site=<slug>`, a CSV feed generated from whichever collection a site's config designates, for Facebook/Instagram Shop.
14
+ - **Connection Health Check** — verifies the stored access token against the Graph API and records connection status, same UX as `ErpnextConfig`'s auto-fetch.
15
+
16
+ > [!NOTE]
17
+ > This plugin does **not** duplicate WhatsApp webhook receiving or outbound sending — the host CMS already has a generic `webhooks` collection (`payload-cms/src/collections/Webhooks.ts`) + `webhookReceiver.ts` for inbound, and `lib/whatsapp.ts`'s `sendWhatsApp()` (Meta Cloud API provider) for outbound. See [Why Not Rebuild WhatsApp?](#why-not-rebuild-whatsapp) below.
18
+
19
+ > [!WARNING]
20
+ > In Development mode, Meta only allows OAuth for users added as Testers, Admins, or Developers on the App. Real customers cannot connect until the App is Live and App Review has granted the scopes you use. Set `META_ENCRYPTION_KEY` before connecting a live account; without it the plugin refuses to boot in production unless `ALLOW_PLAINTEXT_META_CREDS=true`, which stores tokens in plain text.
21
+ >
22
+ > Check Meta's current Graph API version (`GRAPH_API_VERSION` in `utils/metaGraphClient.ts`, currently `v21.0`) if any call returns a deprecation error — Meta bumps this periodically.
23
+
24
+ ---
25
+
26
+ ## Table of Contents
27
+
28
+ - [What This Plugin Actually Does](#what-this-plugin-actually-does)
29
+ - [Installation](#installation)
30
+ - [Quick Start](#quick-start)
31
+ - [Connecting Facebook, Instagram, and Threads](#connecting-facebook-instagram-and-threads)
32
+ - [Configuration](#configuration)
33
+ - [The `meta-config` Collection](#the-meta-config-collection)
34
+ - [Conversions API / Workflow Steps](#conversions-api--workflow-steps)
35
+ - [Commerce Catalog Feed](#commerce-catalog-feed)
36
+ - [Endpoints](#endpoints)
37
+ - [Why Not Rebuild WhatsApp?](#why-not-rebuild-whatsapp)
38
+ - [Security](#security)
39
+ - [What's Not Built Yet](#whats-not-built-yet)
40
+ - [License](#license)
41
+
42
+ ---
43
+
44
+ ## What This Plugin Actually Does
45
+
46
+ Before this plugin existed, "Meta integration" on this platform meant a hand-typed Pixel ID in a CMS global and a client-side `fbq()` call scattered per-site — no server-side tracking, no Commerce Catalog, no real connection health check, and it existed on exactly one site.
47
+
48
+ This plugin is the deliberate fix for that: **one place, per site, to connect to Meta**, and **Meta event tracking happens server-side only** — no client-side `fbq()` custom events anywhere in any frontend. This isn't a stylistic preference; it's a direct response to iOS 14.5+ ad-tracking loss and ad-blockers, both of which silently drop client-side Pixel events. Server-side Conversions API events don't have that problem.
49
+
50
+ **Why this matters for the business**: every Lead, Purchase, and AddToCart that reaches Meta's ad systems reliably is a signal Meta's algorithm uses to find more people like that customer. Client-only tracking under-reports these events — often by 20–30% depending on ad-blocker prevalence and iOS share — which directly degrades ad targeting and inflates cost-per-acquisition. Fixing the *reliability* of the signal is usually a bigger lever than fixing the ad creative.
51
+
52
+ ---
53
+
54
+ ## Installation
55
+
56
+ ```bash
57
+ npm install opscms-meta-plugin
58
+ # or
59
+ pnpm add opscms-meta-plugin
60
+ ```
61
+
62
+ Same release shape as `opscms-erpnext-plugin`: install the published package by semver. `prepublishOnly` builds `dist/` (gitignored) before `npm publish` uploads the tarball. Version history is in `CHANGELOG.md`.
63
+
64
+ ---
65
+
66
+ ## Quick Start
67
+
68
+ ### 1. Add the plugin to `payload.config.ts`
69
+
70
+ ```typescript
71
+ import { buildConfig } from 'payload'
72
+ import { metaPlugin } from 'opscms-meta-plugin'
73
+ import { actionRegistry } from './lib/actionRegistry' // your host application's registry
74
+
75
+ export default buildConfig({
76
+ // ... your config
77
+ plugins: [
78
+ metaPlugin({
79
+ registry: actionRegistry, // optional — omit to skip registering the Conversions API workflow action
80
+ }),
81
+ ],
82
+ })
83
+ ```
84
+
85
+ ### 2. Set the encryption key and the platform Meta App
86
+
87
+ ```bash
88
+ # .env
89
+ META_ENCRYPTION_KEY=$(openssl rand -hex 32)
90
+ META_APP_ID=your-meta-app-id
91
+ META_APP_SECRET=your-meta-app-secret
92
+ ```
93
+
94
+ Without `META_ENCRYPTION_KEY`, credentials are stored in plain text (allowed in development; the plugin **fails fast at startup in production** unless you explicitly set `ALLOW_PLAINTEXT_META_CREDS=true`, which you should not do).
95
+
96
+ `META_APP_ID`/`META_APP_SECRET` are the **one Meta App for the whole deployment** — same pattern as Buffer/Hootsuite/Zapier: every tenant site connects through this single App, they never create their own. There's no API to create a Meta App programmatically (unlike, say, ERPNext's OAuth Client doctype), so this is a one-time manual step:
97
+
98
+ 1. Create an App at [developers.facebook.com](https://developers.facebook.com), add the **Facebook Login for Business** product (and **Threads API** if you'll connect Threads).
99
+ 2. Add `{PAYLOAD_PUBLIC_SERVER_URL}/api/meta-oauth/callback` and `{PAYLOAD_PUBLIC_SERVER_URL}/api/threads-oauth/callback` as **Valid OAuth Redirect URIs**.
100
+ 3. Switch the App to **Live** mode and request **Advanced Access** (via App Review) for whichever scopes you need — `pages_show_list`, `pages_read_engagement`, `instagram_basic`, `business_management`, `ads_management`, etc. In Development mode, OAuth only works for users added as Testers/Admins/Developers on the App itself — real tenant site owners won't be able to connect until this is done. Meta may also require **Business Verification** for the ads/marketing-adjacent scopes.
101
+ 4. Set `META_APP_ID`/`META_APP_SECRET` from that App's Settings → Basic page and restart.
102
+
103
+ Site owners never see or enter these — the admin UI shows only a masked, read-only App ID (`GET /api/meta-oauth/app-info`) so they can confirm a platform App is configured before clicking Connect.
104
+
105
+ ### 3. Create a `Meta Config` in the Payload Admin
106
+
107
+ Go to **Integrations → Meta Config**:
108
+
109
+ - Select the site/tenant.
110
+ - **🔑 Connection tab**: either paste a long-lived Access Token manually, **or** click **Connect to Meta Business** and log in — see [Connecting Facebook, Instagram, and Threads](#connecting-facebook-instagram-and-threads) for the full walkthrough. Either way, save — the plugin verifies the token against the Graph API a couple of seconds later and updates **Connection Status**.
111
+ - Enable and configure only the channel tabs this site needs:
112
+ - **📊 Pixel & Conversions API** — Pixel ID (paste one, or use **Select / Create Pixel**).
113
+ - **🛍️ Commerce Catalog** — Catalog ID, the Payload collection slug to feed (e.g. `catalogue-items`), and an item URL template.
114
+ - **💬 WhatsApp Business** — phone number ID + Business Account ID (outbound sending is already live via the host CMS's notification system once these are set — see [Why Not Rebuild WhatsApp?](#why-not-rebuild-whatsapp)).
115
+ - **🧵 Threads** — click **Connect Threads** (its own, separate OAuth flow).
116
+ - Mark **Active** and save.
117
+
118
+ ### 4. Wire a Conversions API event into a Workflow
119
+
120
+ Go to **Automation → Workflows**:
121
+
122
+ - Create or edit a workflow (e.g. triggered on order creation).
123
+ - In **Steps**, add a **Trigger Meta Conversion Event** block.
124
+ - Pick the event name (`Purchase`, `Lead`, `AddToCart`, etc.) and map `value`/`currency`/`content_name`/`email`/`phone` using `{{var}}` references into the workflow context — same templating syntax as the ERPNext plugin's `trigger_erp` step. `email`/`phone` are optional but recommended: they're SHA-256 hashed before ever leaving the server and significantly improve Meta's event match quality.
125
+ - Trigger collection is just as generic as any other Workflow — e.g. watch `form-submissions` (`collection_change` / `afterCreate`) to fire `Lead` on every contact-form or job-application submission, no plugin-specific wiring required.
126
+
127
+ ---
128
+
129
+ ## Connecting Facebook, Instagram, and Threads
130
+
131
+ Two ways to connect, fully interchangeable — pick whichever suits a given site. Both populate the exact same `accessToken`/`pixelId` fields, so nothing downstream (Conversions API, Catalog feed) needs to know which path was used.
132
+
133
+ ### Option A — Manual
134
+
135
+ Paste a long-lived Page or System User access token directly into `accessToken` on the **🔑 Connection** tab. Useful if a site owner already has a token from elsewhere, or wants to skip the OAuth consent screen. Fully supported indefinitely — not a legacy fallback.
136
+
137
+ ### Option B — Connect to Meta Business (OAuth)
138
+
139
+ Uses the one platform-level Meta App set up via `META_APP_ID`/`META_APP_SECRET` (see [Set the encryption key and the platform Meta App](#2-set-the-encryption-key-and-the-platform-meta-app) — that's a one-time deployment setup step, not something each site does). Once that's configured:
140
+
141
+ 1. On the `meta-config` document's 🔑 Connection tab, the panel shows a masked, read-only **Platform Meta App** ID confirming it's configured.
142
+ 2. Click **Connect to Meta Business** — you'll be redirected to Meta's OAuth consent screen requesting `business_management`, `pages_show_list`, `pages_read_engagement`, `pages_manage_metadata`, `instagram_basic`, `ads_management`, `catalog_management`, and `whatsapp_business_management` (trim the scope list in `metaOAuth.ts` if your App's review doesn't cover all of them — Meta simply omits ungranted permissions from the resulting token rather than failing the whole flow).
143
+ 3. After consenting, you land back on the `meta-config` edit page. Click **Load My Pages**, pick the Facebook Page this site should use, then **Use This Page** — the linked Instagram Business account (if any) is detected automatically. The panel then shows a summary of what's connected: Business Manager ID, Facebook Page (name + ID), and Instagram handle.
144
+ 4. On the **📊 Pixel & Conversions API** tab, enter a **Business Manager ID** (found in Meta Business Settings) on the Connection tab first, then use **Load Existing Pixels** to pick one, or **Create New Pixel** to make a fresh one scoped to that Business Manager.
145
+
146
+ ### Connecting Threads
147
+
148
+ Threads is a **separate product/API** from Facebook and Instagram — its own OAuth host (`threads.net`, not `facebook.com`), its own token host (`graph.threads.net`, not `graph.facebook.com`), and its own token/profile shape — even though it's added as a product on the *same* Meta App and reuses the same platform-level `META_APP_ID`/`META_APP_SECRET`.
149
+
150
+ 1. Add the **Threads API** product to the same Meta App (see setup step above), and register `{PAYLOAD_PUBLIC_SERVER_URL}/api/threads-oauth/callback` as its redirect URI.
151
+ 2. On the **🧵 Threads** tab, click **Connect Threads** — separate consent screen (`threads_basic`, `threads_content_publish`), separate callback, separate stored token (`threadsAccessToken`). Connecting Threads does not affect or require the Facebook/Instagram connection above, or vice versa.
152
+
153
+ ### CSRF Protection Without a Session Store
154
+
155
+ Payload endpoints are stateless REST — there's no server-side session to carry a `configId` through the redirect to Meta's (or Threads') servers and back. Instead, `signOAuthState()`/`verifyOAuthState()` (`utils/metaCrypto.ts`) HMAC-sign `configId:timestamp` (10-minute TTL) into the `state` param, verified on callback with a constant-time comparison — tamper or replay it and the callback rejects with "Invalid or expired connect request."
156
+
157
+ ```typescript
158
+ export interface MetaPluginOptions {
159
+ /** CMS action registry — enables the `meta-conversion-event` workflow action. */
160
+ registry?: ActionRegistryRef
161
+ /** Reserved for future host bindings. Unused today. */
162
+ host?: Record<string, unknown>
163
+ }
164
+ ```
165
+
166
+ ### Environment Variables
167
+
168
+ | Variable | Required | Description |
169
+ |---|---|---|
170
+ | `META_APP_ID` / `META_APP_SECRET` | For OAuth Connect | The one Meta App for the whole deployment (developers.facebook.com) — every tenant site's Connect button uses this. Not required if every site only ever uses manual Access Token entry. Never entered by a site owner; see [Set the encryption key and the platform Meta App](#2-set-the-encryption-key-and-the-platform-meta-app). |
171
+ | `META_ENCRYPTION_KEY` | Production: yes | 32-byte hex key (`openssl rand -hex 32`) for AES-256-GCM credential encryption. Separate from `opscms-erpnext-plugin`'s `ERPNEXT_ENCRYPTION_KEY` — rotating one doesn't affect the other. |
172
+ | `ALLOW_PLAINTEXT_META_CREDS` | No | Set to `true` to explicitly allow plain-text credential storage in production. Do not set this unless you understand the risk (a DB dump/backup leaks every tenant's Meta access token). |
173
+ | `PAYLOAD_PUBLIC_SERVER_URL` | For Catalog feed + OAuth | Used to build absolute image URLs in the Commerce Catalog feed, and the OAuth callback redirect URIs (`/api/meta-oauth/callback`, `/api/threads-oauth/callback`). Already set for the host CMS's other public-facing needs. |
174
+ | `META_OAUTH_STATE_SECRET` | No | HMAC key for signing the OAuth `state` param. Falls back to `META_ENCRYPTION_KEY` if unset — only set this separately if you want state-signing and credential-encryption keys to rotate independently. |
175
+
176
+ ---
177
+
178
+ ## The `meta-config` Collection
179
+
180
+ One document per site. `appId`/`appSecret` are **not** fields here — they're the one platform-level Meta App (`META_APP_ID`/`META_APP_SECRET`), never per-site. Every other credential field is directly editable (manual entry) — the Connect buttons are a convenience layer on top, not a replacement:
181
+
182
+ | Tab | Fields | Notes |
183
+ |---|---|---|
184
+ | 🔑 Connection | `accessToken` (encrypted, required), `businessManagerId`, `connectionStatus` (read-only), `authMethod` (read-only, informational), masked **Platform Meta App** readout, **Connect to Meta Business** button, `facebookPageId`/`facebookPageName`/`instagramBusinessAccountId`/`instagramUsername` (read-only, set by Connect, shown as a connected-account summary), `oauthUserAccessToken` (hidden, encrypted, internal) | `connectionStatus` updates ~2 seconds after save via a background Graph API `/me` check. See [Connecting Facebook, Instagram, and Threads](#connecting-facebook-instagram-and-threads). |
185
+ | 📊 Pixel & Conversions API | `pixelEnabled`, `pixelId`, **Select / Create Pixel** button | Enables `sendConversionEvent()` / the `meta-conversion-event` workflow action for this site. |
186
+ | 🛍️ Commerce Catalog | `catalogEnabled`, `catalogId`, `catalogSourceCollection`, `catalogItemUrlTemplate` | Enables `GET /api/meta-catalog/feed?site=<slug>`. |
187
+ | 💬 WhatsApp Business | `whatsappEnabled`, `whatsappPhoneNumberId`, `whatsappBusinessAccountId` | Populates the host CMS's existing `lib/whatsapp.ts` `metaCloud` provider — no plugin code needed for outbound sending. |
188
+ | 🧵 Threads | `threadsEnabled`, **Connect Threads** button, `threadsUserId`/`threadsUsername` (read-only, set by Connect), `threadsAccessToken` (hidden, encrypted) | Independent OAuth flow — see [Connecting Facebook, Instagram, and Threads](#connecting-facebook-instagram-and-threads). |
189
+
190
+ Credentials (`accessToken`, `oauthUserAccessToken`, `threadsAccessToken`) are AES-256-GCM encrypted at rest and masked in the admin UI (`••••1234`) for any authenticated non-internal request — the same pattern `ErpnextConfig` uses for `apiKey`/`apiSecret`. `META_APP_SECRET` never touches the database at all — it's read from the environment on each OAuth request.
191
+
192
+ ---
193
+
194
+ ## Conversions API / Workflow Steps
195
+
196
+ `sendConversionEvent(creds, input, log?)` posts a single event to `graph.facebook.com/v21.0/{pixel_id}/events`. Exported directly for host-app code that wants to call it outside the workflow engine:
197
+
198
+ ```typescript
199
+ import { getMetaCredentials, sendConversionEvent } from 'opscms-meta-plugin'
200
+
201
+ const creds = await getMetaCredentials(payload, 'thatofadagirl')
202
+ if (creds?.pixelId) {
203
+ await sendConversionEvent(creds, {
204
+ eventName: 'Purchase',
205
+ customData: { value: 12500, currency: 'NGN' },
206
+ })
207
+ }
208
+ ```
209
+
210
+ There is deliberately **no client-side event to deduplicate against** — this plugin doesn't fire `fbq()` calls, so the `eventId`/dedup dance Meta's docs describe for hybrid Pixel+CAPI setups doesn't apply here. If a site later adds its own client Pixel events independently, `eventId` is available on `ConversionEventInput` to dedupe against those.
211
+
212
+ `ConversionEventInput.userData` accepts pre-hashed `emailHash`/`phoneHash` (SHA-256, caller hashes before calling — never pass raw PII here) for better event match quality. The workflow step below does this hashing for you from plain `email`/`phone` step fields.
213
+
214
+ The **Trigger Meta Conversion Event** workflow step (`trigger_meta_conversion` block) is the no-code path — see [Quick Start](#quick-start) step 4. It reads `event_name`/`value`/`currency`/`content_name`/`event_source_url`/`email`/`phone` off the step, resolves `{{var}}` templates against the workflow context, hashes `email`/`phone` (SHA-256, trimmed + lowercased; phone digits-only) before they ever reach Meta, and calls `sendConversionEvent()` under the hood (`metaConversionEventHandler` in `actions/metaActions.ts`).
215
+
216
+ **Any collection can trigger it** — the Workflow engine's trigger isn't Meta-specific. Watching `form-submissions` on `afterCreate` is the common case: a contact form or job application becomes a `Lead` event with zero extra plugin code, using the site's connected Pixel from the Connect flow above.
217
+
218
+ ### Migrating from the old `analytics-integrations`/`meta-capi` path
219
+
220
+ Earlier, Meta Conversions API had a second, unrelated implementation: the host CMS's generic `send_analytics_event` workflow block (`analytics_provider: 'meta'`) reading credentials from an `analytics-integrations` collection row (`provider: 'meta-capi'`). That path is retired — `send_analytics_event` is GA4-only now. If you were using it, recreate the same event as a **Trigger Meta Conversion Event** step instead; the site's Pixel/token now come from `meta-config` (via Connect or manual entry above), not a second credential entry.
221
+
222
+ ---
223
+
224
+ ## Commerce Catalog Feed
225
+
226
+ `GET /api/meta-catalog/feed?site=<slug>` — public, unauthenticated (Meta's Commerce Manager crawler doesn't send custom auth headers), site-scoped.
227
+
228
+ Generic by design: reads whichever collection `catalogSourceCollection` designates, tolerating a few common field-name variations so it isn't hardcoded to any one site's schema:
229
+
230
+ | Feed column | Source field(s) tried, in order |
231
+ |---|---|
232
+ | `title` | `title`, `name`, `heading` |
233
+ | `description` | `description`, `excerpt`, `body` (HTML stripped) |
234
+ | `price` | `price`, `price_from`, `priceFrom` |
235
+ | `image_link` | `image`, `featuredImage`, `photo` (resolved to an absolute URL) |
236
+ | `link` | `catalogItemUrlTemplate` with `{slug}` substituted |
237
+
238
+ Items missing a `title` or `price` are skipped rather than emitted as invalid rows — Meta rejects the whole feed on malformed entries, so a few incomplete source documents shouldn't take down catalog sync for everything else.
239
+
240
+ ---
241
+
242
+ ## Endpoints
243
+
244
+ All `/meta-oauth/*` and `/threads-oauth/start` endpoints require an authenticated `admin`/`super-admin` session. The two `*-oauth/callback` endpoints are hit by Meta's/Threads' redirect (not called directly) and verify the signed `state` param instead.
245
+
246
+ | Method | Path | Description |
247
+ |--------|------|-------------|
248
+ | `GET` | `/api/meta-catalog/feed?site=<slug>` | Public, unauthenticated. Commerce Catalog CSV feed. |
249
+ | `GET` | `/api/meta-oauth/start?configId=<id>` | Redirects to Meta's OAuth2 authorize screen. |
250
+ | `GET` | `/api/meta-oauth/callback` | Facebook/Instagram OAuth2 callback — exchanges the code, stores the long-lived user token. |
251
+ | `GET` | `/api/meta-oauth/pages?configId=<id>` | Lists Facebook Pages reachable by the connected account. |
252
+ | `POST` | `/api/meta-oauth/select-page` | Body `{ configId, pageId }` — fetches that Page's token + linked Instagram account, stores both. |
253
+ | `GET` | `/api/meta-oauth/pixels?configId=<id>` | Lists Pixels owned by the configured Business Manager. |
254
+ | `POST` | `/api/meta-oauth/pixels` | Body `{ configId, name }` — creates a new Pixel scoped to the Business Manager. |
255
+ | `GET` | `/api/threads-oauth/start?configId=<id>` | Redirects to Threads' OAuth2 authorize screen. |
256
+ | `GET` | `/api/threads-oauth/callback` | Threads OAuth2 callback — exchanges the code, stores the long-lived Threads token + profile. |
257
+
258
+ ---
259
+
260
+ ## Why Not Rebuild WhatsApp?
261
+
262
+ The host CMS already has real, generic, multi-tenant WhatsApp infrastructure:
263
+
264
+ - **Outbound**: `payload-cms/src/lib/whatsapp.ts`'s `sendWhatsApp()` supports the official Meta Cloud API provider (`metaCloud: { phoneNumberId, accessToken }`) alongside OpenWA, resolved per-site via `notificationService.ts`. Filling in `whatsappPhoneNumberId`/`whatsappBusinessAccountId` on `meta-config` is enough — no plugin code needed.
265
+ - **Inbound**: `payload-cms/src/collections/Webhooks.ts` + `webhookReceiver.ts` (`POST /api/webhooks/:id`) is a fully generic, per-site, HMAC-verified webhook receiver with replay protection and job-queue dispatch — its own admin description cites "WhatsApp Bot" as an example use case.
266
+
267
+ The one real gap: Meta's WhatsApp Cloud API webhook subscription requires a `GET` `hub.challenge`/`hub.verify_token` handshake before it will start sending `POST`s, and the generic receiver only handles `POST`+HMAC today. That's a small, targeted extension to the *host CMS's* existing `Webhooks` collection/`webhookReceiver.ts` — not something this plugin should duplicate with its own parallel WhatsApp-specific route. (An earlier, unrelated attempt at a WhatsApp webhook route lived directly in one frontend site, hardcoded and non-functional; it's been deleted.)
268
+
269
+ ---
270
+
271
+ ## Security
272
+
273
+ - Credentials (`accessToken`) are AES-256-GCM encrypted at rest (`META_ENCRYPTION_KEY`), masked in the admin UI, and only decrypted server-side when actually needed (e.g. `getMetaCredentials()`, the connection-health check). `META_APP_SECRET` is never stored in the database at all — it's read from the environment only, on each OAuth request.
274
+ - `accessToken` is only writable by `admin`/`super-admin` roles (`adminOrAboveField` field-level access) — editors can see the masked config but can't rotate credentials or repoint a connection.
275
+ - `getMetaCredentials()` never falls back across sites — a lookup for one site's slug will never return another tenant's credentials, even on a partial/missing config.
276
+ - The Commerce Catalog feed is intentionally public (Meta's crawler needs unauthenticated access) but strictly site-scoped — it can never return another site's data, and only returns docs that already belong to the requested site.
277
+ - The OAuth `state` param is HMAC-signed with a 10-minute TTL and verified with a constant-time comparison (`signOAuthState`/`verifyOAuthState` in `utils/metaCrypto.ts`) — the callback endpoints reject a forged, tampered, or replayed-after-expiry state before doing anything else.
278
+ - `/meta-oauth/select-page` and the Pixel endpoints only ever accept a `configId` + an identifier (`pageId`, pixel `name`) from the browser — the actual page/pixel access token is always re-fetched fresh from Graph server-side, never trusted from the client.
279
+ - OAuth endpoints (`/meta-oauth/*`, `/threads-oauth/start`) require an authenticated `admin`/`super-admin` session — same role gate as manual credential entry.
280
+
281
+ ---
282
+
283
+ ## What's Not Built Yet
284
+
285
+ - **WhatsApp webhook verify-token handshake** — belongs on the host CMS's `Webhooks` collection/`webhookReceiver.ts`, not this plugin (see [Why Not Rebuild WhatsApp?](#why-not-rebuild-whatsapp)).
286
+ - **Not live in production** — see the warning at the top of this README. A real Meta App exists and is being tested end-to-end in dev, but it's still in Development mode pending App Review/Live mode, so it's held out of production deploys until that clears (real customers can't complete OAuth against a Development-mode App regardless of what's deployed).
287
+
288
+ See `payload-cms/docs/future-features.md` in the host monorepo for the full, up-to-date plan and status.
289
+
290
+ ---
291
+
292
+ ## License
293
+
294
+ MIT
295
+
296
+
297
+ ## Webhook (template approvals and account events)
298
+
299
+ Meta reports what happens on its side to one callback address per app. Register
300
+ `https://<your CMS>/api/meta-webhook` as the callback of the platform's Meta app, for the
301
+ **WhatsApp Business Account** topic, with the verify token from `META_WEBHOOK_VERIFY_TOKEN`.
302
+ The app secret (`META_APP_SECRET`) must also be set: every delivery is signed with it, and a
303
+ delivery with a missing or wrong signature is refused with 401.
304
+
305
+ Each site's business account is subscribed to the app when the site chooses its WhatsApp
306
+ number (and unsubscribed when it disconnects), so its events arrive at the callback. Template
307
+ changes are handed to the host as events; see the changelog for their names. The host is
308
+ passed as `metaPlugin({ host: { emitSystemEvent } })`. Without it the webhook still answers
309
+ and checks deliveries but has nobody to tell.
310
+
311
+
312
+ ## WhatsApp templates and approval
313
+
314
+ Meta must approve the exact wording of a WhatsApp message before it can be sent. The plugin does this for the
315
+ notification templates a site actually sends by WhatsApp, with no extra setup:
316
+
317
+ 1. A workflow with a *send notification* step that includes WhatsApp is saved (or such a template's text is edited), and the
318
+ site has connected its WhatsApp number through Meta.
319
+ 2. The plugin submits the template's message text to the site's WhatsApp business account.
320
+ 3. Meta approves it (the webhook or the five-minute check finds out), and from then on the message is sent by template name.
321
+ If Meta does not approve it, the owner is told through the host's automation and the message is not sent by WhatsApp.
322
+
323
+ The host needs the `meta-approvals` collection's migration, and `metaPlugin({ host })` with `emitSystemEvent` and
324
+ `ensureEventHandler`. A site whose WhatsApp goes through another service (OpenWA) is not touched.
325
+
326
+ ## Signing in to the platform with Facebook
327
+
328
+ The plugin adds "Continue with Facebook" to the platform's login page, using the same Meta app customers connect through.
329
+
330
+ - **Who gets in:** someone who already has a platform account. Their Facebook email must be the same as their platform email to join the
331
+ two; after that they sign in by Facebook id. Signing in never creates an account, and an account is never matched on a different email.
332
+ - **Setup:** `META_APP_ID` and `META_APP_SECRET` on the server, the Facebook Login product on the Meta app, and
333
+ `<PAYLOAD_PUBLIC_SERVER_URL>/api/meta-login/callback` listed as a valid OAuth redirect URI. Only `email` and `public_profile` are
334
+ requested, which need no App Review.
335
+ - **Database:** the plugin adds a unique `facebookId` field to the users collection; the platform needs a migration for the column.
336
+ - **Admin screen:** the button is a component of the plugin (`opscms-meta-plugin/components/MetaLoginButton`); the platform's import map
337
+ has to be regenerated (`payload generate:importmap`) after the plugin is updated.
338
+ - **Endpoints:** `GET /api/meta-login/status`, `/start`, `/callback`; `POST /api/meta-login/unlink` (a signed-in person disconnects their own
339
+ Facebook account).