opscms-erpnext-plugin
A self-contained Payload CMS 3.x plugin for secure, multi-tenant ERPNext integrations.
It provides:
- ERPNext Connection Configuration per site (multi-tenant) with encrypted credentials.
- Generic ERP Action Handlers (
erp-get, erp-post, erp-patch, erp-delete) registered directly into the CMS workflow engine's action registry.
- Workflow Step Integration — injects a
trigger_erp (Trigger ERP Action) block into the CMS workflows collection steps, with custom field components for live DocType and target field selection.
- Dead-Letter Queue (
erpnext-dead-letters collection) for permanently failed ERPNext requests.
- Anonymous File Upload endpoint for form attachments (e.g., resumes) with file-type and origin validation.
- Secure ERPNext Proxy Endpoints (
/api/erpnext-proxy/...) with rate-limiting, origin validation, and cross-tenant data isolation.
- Inbound Sync Rules (
erpnext-sync-rules collection) to map ERPNext DocTypes into Payload collections.
- Inbound Webhook Receiver (
/api/erpnext-sync) with HMAC-SHA256 signature verification for ERPNext → Payload sync.
- Webhook Signature Verification helper for validating incoming ERPNext/Frappe notifications.
[!NOTE]
Form-submission-to-ERPNext forwarding is handled by the host application's general Workflows collection (e.g., triggered on collection_change for form-submissions) rather than a dedicated parallel engine.
Table of Contents
- Installation
- Quick Start
- ERPNext OAuth2 Connect
- Configuration
- ERPNext Workflow Steps
- Inbound Sync Rules
- Security & Access Control
- Dead-Letter Queue
- Endpoints
- Architecture
- License
Installation
npm install opscms-erpnext-plugin
# or
pnpm add opscms-erpnext-plugin
Quick Start
1. Add the plugin to payload.config.ts
Import and register erpnextPlugin, passing the host application's action registry to enable workflow execution:
import { buildConfig } from 'payload'
import { erpnextPlugin } from 'opscms-erpnext-plugin'
import { actionRegistry } from './lib/actionRegistry' // your host application's registry
export default buildConfig({
// ... your config
plugins: [
erpnextPlugin({
registry: actionRegistry,
}),
],
})
2. Create an ERPNext Config in the Payload Admin
Go to Integrations → ERPNext Config:
- Select the site/tenant.
- Enter the ERPNext URL (HTTPS only).
- Either enter API Key and Secret manually, or enter the ERPNext username/password of an account with permission to create OAuth Clients and click Connect — see ERPNext OAuth2 Connect below. Both populate the same underlying credentials; pick whichever suits a given site.
- Companies are fetched automatically once credentials are in place (manual or OAuth) — no separate "fetch companies" step.
- Mark as Active and Save.
3. Build a Workflow Step
Go to Settings → Workflows:
- Create or edit a workflow.
- In Steps, add a Trigger ERP Action (
trigger_erp) block.
- Select the DocType and Action (e.g.,
POST to create, GET to search).
- Map fields from the CMS document context using
{{doc.fieldName}} variables.
ERPNext OAuth2 Connect
Two ways to authenticate an ERPNext Config, fully interchangeable — pick whichever suits a given site. Both populate the credentials getCredentials()/authHeaders() use, so nothing downstream (the proxy endpoints, workflow ERP actions) needs to know which was used.
Option A — Manual API Key/Secret
Create an API Key/Secret pair in ERPNext under User → API Access, paste them in. Fully supported indefinitely — not a legacy fallback.
Option B — Connect (login-based auto-connect)
There is no manual OAuth Client setup step — no going into ERPNext's admin to register a Client ID/Secret or a redirect URI by hand. Enter the ERPNext username/password of an account with permission to create OAuth Clients (typically an Administrator or System Manager) directly on the erpnext-config document and click Connect:
- The plugin logs in to ERPNext via
POST /api/method/login using the entered credentials (this call is never stored — only the resulting session is used, transiently, for the next steps).
- It looks up an existing OAuth Client via
GET /api/resource/OAuth Client, keyed by a deterministic name (IVarse Integration (<site-slug>)) — reused if found, so reconnecting the same site never creates a duplicate Client. If none exists, it creates one via POST /api/resource/OAuth Client with skip_authorization: 1 set, so the end user is never shown a consent screen.
- It calls ERPNext's
/authorize endpoint server-side using that session. Because skip_authorization is set, ERPNext auto-approves and redirects in a single hop straight to the plugin's redirect_uri with ?code=&state= — there's no separate "approve" confirmation redirect to follow, and that URL is only ever read off the Location header, never actually fetched (it isn't a route the plugin serves). The code is then exchanged for tokens.
- The resulting Client ID and Client Secret (auto-populated, read-only, masked in the UI — the user never sees or types these) and the access/refresh token pair are stored (encrypted).
- Access tokens are refreshed automatically and transparently by
getCredentials() when expired, using the stored refresh token — no user interaction needed after the initial connect.
Manual API Key/Secret fields are not required (and are not cleared) once a config is OAuth-connected — switching back to manual entry is just a matter of leaving OAuth alone and filling those fields in; authMethod only reflects whichever path was used most recently.
The idempotency guarantee (point 2 above) is the reason this is safe to re-run: if an erpnext-config document is ever deleted and recreated for the same site, reconnecting finds and reuses the same OAuth Client by name instead of accumulating orphaned, unused Clients in ERPNext.
Why This Flow Doesn't Need OAuth state Param Signing
A state param exists to protect OAuth flows that redirect the browser out to a third-party authorization server and back — it's what lets the app verify, statelessly, that the request completing the round trip is the same one that started it. ERPNext's auto-connect has no such round trip to protect: it's a single same-origin POST /api/erpnext-oauth/auto-connect, and the browser never leaves the Payload admin. It's protected instead by: requiring an authenticated admin/super-admin Payload session (isAdminOrAbove), and a per-IP rate limit (5 attempts per 60 seconds) against credential-stuffing the ERPNext login step.
Configuration
Plugin Options
import { buildConfig } from 'payload'
import { erpnextPlugin } from 'opscms-erpnext-plugin'
import { actionRegistry, emitSystemEvent, systemEvents, isInternalAuth } from './lib/host' // your host app
export default buildConfig({
// ... your config
plugins: [
erpnextPlugin({
registry: actionRegistry, // required for workflow ERP actions
host: {
emitSystemEvent, // optional: enables ERPNext connection monitoring
systemEvents, // optional: { ERPNEXT_CONNECTION_FAILED, ERPNEXT_CONNECTION_RESTORED }
isInternalAuth, // optional: enables /api/erpnext/link-customer
siteCollectionsMap, // optional: enables global/local grouping in the Sync Rules collection picker
},
enableAnonymousUpload: true, // optional, defaults to true
}),
],
})
| Option |
Type |
Default |
Description |
registry |
ActionRegistryRef |
undefined |
Required for workflow actions. The action registry to register erp-get, erp-post, erp-patch, and erp-delete handlers. |
host |
ERPNextHostBindings |
undefined |
Host-injected automation primitives (emitSystemEvent, systemEvents, isInternalAuth, siteCollectionsMap). Keeps the plugin free of circular imports into the CMS — see Inbound Sync Rules for what siteCollectionsMap does. |
enableAnonymousUpload |
boolean |
true |
Registers /api/anonymous-upload for form file attachments. |
Environment Variables
| Variable |
Required |
Description |
ERPNEXT_ENCRYPTION_KEY |
Required |
32-byte hex AES-256-GCM key for encrypting credentials at rest. Generate with openssl rand -hex 32. |
INTERNAL_API_SECRET |
Recommended |
Shared secret for isInternalAuth checks (e.g. /api/erpnext/link-customer). Verified with constant-time comparison. |
ERPNEXT_PROXY_KEY |
Recommended |
Shared secret for server-to-server proxy access (x-internal-key header). Verified with constant-time comparison. |
ERPNEXT_PROXY_REQUIRE_CAPTCHA |
Optional |
Set to true to require a reCAPTCHA token on public write operations (/api/erpnext-proxy/submit). |
REDIS_URL |
Optional |
Enables Redis-backed rate limiting. Recommended for horizontal scaling. |
TRUSTED_ORIGINS |
Optional |
Comma-separated list of origins allowed for proxy and anonymous upload endpoints. |
CORS_ORIGINS |
Optional |
Fallback origin allow-list for proxy and anonymous upload endpoints. |
PAYLOAD_PUBLIC_SERVER_URL |
Recommended |
The CMS public URL; used as a trusted origin for anonymous uploads, and as the redirect_uri registered on each auto-created ERPNext OAuth Client. That URI is never actually hit by a browser (see ERPNext OAuth2 Connect — the whole exchange happens server-side), it just has to match what ERPNext's OAuth2 provider has on file for the request to be accepted. |
NEXT_PUBLIC_PAYLOAD_URL |
Optional |
Fallback public URL for anonymous upload origin checks. |
TRUSTED_PROXY_COUNT |
Optional |
Number of trusted proxies in front of the app, used for accurate IP extraction. |
ALLOW_PLAINTEXT_ERPNEXT_CREDS |
Optional |
Dangerous opt-out: allows storing ERPNext credentials without encryption when no ERPNEXT_ENCRYPTION_KEY is set. Not recommended for production. |
ERPNext Workflow Steps
The plugin automatically extends the host's workflows collection steps with the Trigger ERP Action (trigger_erp) block.
Step Fields