NW Pre Customer + ApiConnectBC — Manual

NW Pre Customer + ApiConnectBC

Portal de autoservicio para Microsoft Dynamics 365 Business Central — niccoweb.com

BC 26.0 + Node.js
📋 Información general
Publicadorniccoweb.com
Extensión BCPre Customer v26.0.0.0
Rango de ID50140–50145
Runtime AL14.0
Backend webNode.js + Express
AutenticaciónOAuth2 (Azure AD)
ℹ️ ¿Qué hacen estos dos proyectos?
NW Pre Customer (extensión AL) y ApiConnectBC (app web Node.js) forman, juntos, un portal de autoservicio: un cliente potencial puede actualizar sus propios datos directamente en una tabla de Business Central a través de un formulario web público, sin tener usuario ni licencia de BC y sin que nadie tenga que entrar al sistema. Business Central guarda la prospección en una tabla intermedia (Pre Customer), envía un correo con un enlace seguro de un solo uso, y la app web hace de puente seguro hacia la API estándar de BC.

🧑‍💼 Usuario BCCrea el Pre Customer
📧 Email seguroCodeunit 50140
🌐 ApiConnectBCFormulario Node.js
🔑 OAuth2Azure AD
🧩 API Pre CustomerPágina 50142
🗄️ Tabla Pre CustomerBase de datos BC

✉️ Invitación por correo
Actualizar mis datos →
📝 Formulario web (sin login BC)
NameJane Doe
E-mail🔒 jane@…
AddressCalle 123
CityMadrid
💡 El correo y el formulario muestran solo un ejemplo ilustrativo del flujo real del proyecto.
Funciones principales
🚪

Sin entrar a BC

El cliente potencial nunca necesita usuario, licencia ni sesión de Business Central.

🔑

Token de un solo uso

Cada invitación incluye un Guid Token que se invalida automáticamente tras la primera actualización correcta.

Caducidad configurable

El campo Token Time define cuánto tiempo sigue siendo válido el enlace enviado.

🛡️

Validación en la propia API

El trigger OnModifyRecord rechaza cualquier PATCH con token incorrecto o caducado.

🤖

Autenticación app-only

ApiConnectBC se autentica con OAuth2 client credentials: no usa ni expone credenciales del prospecto.

👀

Vista previa del correo

La acción Send Email (Preview Mode) abre el email en el editor de BC antes de enviarlo.

📎

Adjuntos documentales

Cada Pre Customer admite archivos adjuntos (DNI, justificante, etc.) desde la ficha de BC.

🔌

API estándar reutilizable

La página API (OData v4) puede integrarse con cualquier sistema externo, no solo con ApiConnectBC.

⚙️ Configuración inicial
  • 1
    Registra una aplicación Azure AD (client credentials) con permiso sobre la API de Business Central; guarda el Tenant ID, Client ID y genera un Client Secret.
  • 2
    Da de alta esa aplicación en BC (Microsoft Entra Applications) con permiso sobre los objetos de Pre Customer.
  • 3
    Configura el .env de ApiConnectBC: TENANT_ID, CLIENT_ID, CLIENT_SECRET, BASE_URL, ENVIRONMENT, API_VERSION, COMPANY_ID, RESOURCE_TYPE, PORT.
  • 4
    Despliega/arranca el servicio: npm install && npm start, y anota su URL pública.
  • 5
    En BC, abre Pre Customer Setup e indica esa Url, el Subject, el Body Text del correo y el Token Time de validez.
🚀 Flujo de uso completo
  • 1
    El usuario de BC crea un registro Pre Customer con Name, E-mail, Address, City, County y Post Code.
  • 2
    Pulsa Send Email (o la versión en modo vista previa).
  • 3
    El codeunit genera un nuevo Guid Token, calcula su caducidad y envía un correo HTML con un botón hacia {Url}/{Id}/{GuidToken}.
  • 4
    ApiConnectBC obtiene un token OAuth2 y hace GET a la API de BC para traer los datos actuales del prospecto.
  • 5
    El prospecto ve el formulario pre-rellenado (E-mail de solo lectura) y corrige Name/Address/City/County/Post Code.
  • 6
    Al enviar, ApiConnectBC hace PATCH a la API incluyendo el guidToken recibido en el enlace.
  • 7
    La página API valida el token: si es correcto y no ha caducado, aplica los cambios y lo borra (un solo uso); si no, devuelve error.
  • 8
    El prospecto ve la pantalla de confirmación, sin haber accedido nunca a Business Central.
📦 Objetos AL — Pre Customer
TipoIDNombreDescripción
Tabla50140Pre CustomerTabla intermedia con los datos del prospecto y su token de seguridad
Tabla50141Pre Customer SetupConfiguración singleton: URL del formulario, asunto, cuerpo del correo y caducidad del token
Página50140Pre CustomerLista para gestionar prospectos y disparar el envío de invitaciones
Página50141Pre Customer SetupFicha de configuración (singleton, sin alta ni baja)
Página API50142API Pre CustomerEndpoint OData consumido por ApiConnectBC (y cualquier otro sistema externo)
Codeunit50140Pre Customer Mgt.Generación del token, envío del correo e integración con adjuntos documentales
EnumExt50140NW Attachment Document TypeAñade "Pre Customer" como tipo de documento adjunto
⚠️ Esta extensión no incluye un conjunto de permisos propio: concede acceso mediante SUPER o un permission set personalizado que cubra las tablas, páginas y el codeunit anteriores.
🗂️ Modelo de datos
Tabla — Pre Customer (50140)
CampoTipoDescripción
No. (1)Code[20]Clave primaria, expuesta como id en la API
E-mail (2)Text[80]Correo del prospecto; solo lectura en el formulario web
Name (3)Text[100]Nombre del prospecto
Address (4)Text[100]Dirección
City (5)Text[30]Ciudad
County (6)Text[30]Provincia / condado
Post Code (7)Code[20]Código postal
Guid Token (50000)GuidToken de un solo uso para autorizar la actualización
Guid Token Expires At (50001)DateTimeCaducidad del token
Tabla — Pre Customer Setup (50141)
CampoTipoDescripción
UrlText[150]URL base del formulario (servidor ApiConnectBC)
SubjectText[80]Asunto del correo de invitación
Body TextText[500]Cuerpo del correo, insertado en la plantilla HTML
Token TimeDurationTiempo de validez del enlace enviado
🧩 API Pre Customer (página 50142)
Endpoint OData v4 personalizado, publicado bajo APIPublisher=nw, APIGroup=precustomer, APIVersion=v2.0, con EntityName=precustomer / EntitySetName=precustomers sobre la tabla Pre Customer. Usa ODataKeyFields=SystemId (el GUID interno de BC, no el campo "No.") y DelayedInsert=true.

Campo APICampo BCAcceso
systemIdSystemIdClave OData (lectura)
idNo.Lectura
eMailE-mailLectura/escritura
nameNameLectura/escritura
addressAddressLectura/escritura
cityCityLectura/escritura
countyCountyLectura/escritura
postCodePost CodeLectura/escritura
guidTokenGuid TokenEscritura (token de la invitación)
📎 Incluye además la parte incrustada documentAttachments (basada en la página estándar "APIV2 - Document Attachments" de BC), enlazada por Document Id = SystemId.
🔐 Seguridad del token (trigger OnModifyRecord): antes de aplicar cualquier modificación, compara el Guid Token recibido con el que ya tenía el registro y comprueba que no haya superado su fecha de caducidad. Si algo no coincide, rechaza la petición con error; si todo es correcto, aplica los cambios y borra ambos campos de token, de modo que el enlace deja de funcionar tras el primer uso.
🌐 Arquitectura de ApiConnectBC
Aplicación Node.js / Express sin frontend de cliente pesado: usa plantillas EJS renderizadas en servidor y Axios para hablar con la API de BC. No guarda datos propios: actúa como puente seguro entre el navegador del prospecto y Business Central.

MétodoRutaDescripción
GET/Sirve form.html: formulario para introducir manualmente Id y token
GET/api/update-precustomer/:id/:guidObtiene token OAuth2, hace GET a la API de BC y renderiza el formulario pre-rellenado
POST/api/update-precustomer/:id/:guidHace PATCH a la API de BC con los campos editados y el guidToken; renderiza éxito o error
📁 Estructura: server.js (arranque Express) · auth/oauth.js (token client-credentials) · routes/bc.js (rutas GET/POST) · views/update-precustomer.ejs + views/success.ejs · public/form.html + public/css/style.css 📦 Dependencias: express, ejs, axios, dotenv, express-session.
🛡️ Seguridad
  • OAuth2 client credentials: ApiConnectBC se autentica como aplicación (app-only) contra login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token con el scope https://api.businesscentral.dynamics.com/.default; el prospecto nunca ve ni necesita credenciales de BC.
  • El Client Secret vive solo en el .env del servidor, nunca llega al navegador del prospecto.
  • El Guid Token es de un solo uso y caduca según Token Time; tras una actualización válida se borra y el enlace deja de servir.
  • El campo E-mail es de solo lectura en el formulario, para evitar que alguien redirija la prospección a otra bandeja de entrada.
📝 Requisitos previos
  • Business Central con la extensión Pre Customer instalada y publicada (probado en v26.0).
  • Una app registration de Azure AD con permiso de API sobre Business Central y un Client Secret vigente.
  • Un entorno Node.js donde alojar ApiConnectBC, idealmente detrás de HTTPS para los enlaces enviados por correo.
  • El conector de correo saliente de Business Central configurado (Email Setup) para que el codeunit pueda enviar las invitaciones.

NW Pre Customer + ApiConnectBC

Self-service portal for Microsoft Dynamics 365 Business Central — niccoweb.com

BC 26.0 + Node.js
📋 General Information
Publisherniccoweb.com
BC ExtensionPre Customer v26.0.0.0
ID Range50140–50145
AL Runtime14.0
Web BackendNode.js + Express
AuthenticationOAuth2 (Azure AD)
ℹ️ What do these two projects do?
NW Pre Customer (AL extension) and ApiConnectBC (Node.js web app) work together as a self-service portal: a prospect can update their own data directly in a Business Central table through a public web form, without a BC user, a license, or anyone having to log into the system. Business Central keeps the prospect in a staging table (Pre Customer), emails a secure one-time link, and the web app acts as a secure bridge to BC's standard API.

🧑‍💼 BC UserCreates the Pre Customer
📧 Secure EmailCodeunit 50140
🌐 ApiConnectBCNode.js form
🔑 OAuth2Azure AD
🧩 API Pre CustomerPage 50142
🗄️ Pre Customer TableBC Database

✉️ Email invitation
Update my data →
📝 Web form (no BC login)
NameJane Doe
E-mail🔒 jane@…
Address123 Main St
CityMadrid
💡 The email and form are an illustrative mock-up of the real project flow.
Key Features
🚪

No BC login required

The prospect never needs a Business Central user, license, or session.

🔑

Single-use token

Every invitation carries a Guid Token that is automatically invalidated after the first successful update.

Configurable expiry

The Token Time field controls how long the emailed link stays valid.

🛡️

Validated at the API itself

The OnModifyRecord trigger rejects any PATCH with a wrong or expired token.

🤖

App-only authentication

ApiConnectBC authenticates with OAuth2 client credentials — no prospect credentials are ever used or exposed.

👀

Email preview mode

The Send Email (Preview Mode) action opens the email in BC's editor before sending.

📎

Document attachments

Each Pre Customer supports file attachments (ID, proof of address, etc.) from the BC card.

🔌

Reusable standard API

The OData v4 API page can be integrated with any external system, not just ApiConnectBC.

⚙️ Initial Setup
  • 1
    Register an Azure AD application (client credentials) with permission to call the Business Central API; note the Tenant ID, Client ID and generate a Client Secret.
  • 2
    Register that application in BC (Microsoft Entra Applications) with permission over the Pre Customer objects.
  • 3
    Fill in ApiConnectBC's .env: TENANT_ID, CLIENT_ID, CLIENT_SECRET, BASE_URL, ENVIRONMENT, API_VERSION, COMPANY_ID, RESOURCE_TYPE, PORT.
  • 4
    Deploy/run the service: npm install && npm start, and note its public URL.
  • 5
    In BC, open Pre Customer Setup and enter that Url, the Subject, the email Body Text, and the Token Time validity window.
🚀 Full Usage Flow
  • 1
    The BC user creates a Pre Customer record with Name, E-mail, Address, City, County and Post Code.
  • 2
    They click Send Email (or the preview-mode variant).
  • 3
    The codeunit generates a new Guid Token, computes its expiry, and sends an HTML email with a button linking to {Url}/{Id}/{GuidToken}.
  • 4
    ApiConnectBC obtains an OAuth2 token and issues a GET to the BC API to fetch the prospect's current data.
  • 5
    The prospect sees a pre-filled form (E-mail read-only) and corrects Name/Address/City/County/Post Code.
  • 6
    On submit, ApiConnectBC issues a PATCH to the API including the guidToken received in the link.
  • 7
    The API page validates the token: if correct and not expired, it applies the changes and clears it (single use); otherwise it returns an error.
  • 8
    The prospect sees a confirmation screen — having never accessed Business Central.
📦 AL Objects — Pre Customer
TypeIDNameDescription
Table50140Pre CustomerStaging table holding the prospect's data and security token
Table50141Pre Customer SetupSingleton config: form URL, email subject/body and token expiry
Page50140Pre CustomerList page to manage prospects and trigger invitation emails
Page50141Pre Customer SetupCard page for configuration (singleton, no insert/delete)
API Page50142API Pre CustomerOData endpoint consumed by ApiConnectBC (or any external system)
Codeunit50140Pre Customer Mgt.Token generation, email sending, document attachment integration
EnumExt50140NW Attachment Document TypeAdds "Pre Customer" as a valid attachment document type
⚠️ This extension ships without its own permission set: grant access via SUPER or a custom permission set covering the tables, pages and codeunit above.
🗂️ Data Model
Table — Pre Customer (50140)
FieldTypeDescription
No. (1)Code[20]Primary key, exposed as id in the API
E-mail (2)Text[80]Prospect's email; read-only in the web form
Name (3)Text[100]Prospect's name
Address (4)Text[100]Street address
City (5)Text[30]City
County (6)Text[30]County / state
Post Code (7)Code[20]Postal code
Guid Token (50000)GuidSingle-use token authorising the update
Guid Token Expires At (50001)DateTimeToken expiry timestamp
Table — Pre Customer Setup (50141)
FieldTypeDescription
UrlText[150]Base URL of the form (ApiConnectBC server)
SubjectText[80]Invitation email subject
Body TextText[500]Email body, inserted into the HTML template
Token TimeDurationValidity window of the emailed link
🧩 API Pre Customer (page 50142)
Custom OData v4 endpoint published under APIPublisher=nw, APIGroup=precustomer, APIVersion=v2.0, with EntityName=precustomer / EntitySetName=precustomers on the Pre Customer table. Uses ODataKeyFields=SystemId (BC's internal GUID, not the "No." field) and DelayedInsert=true.

API FieldBC FieldAccess
systemIdSystemIdOData key (read)
idNo.Read
eMailE-mailRead/write
nameNameRead/write
addressAddressRead/write
cityCityRead/write
countyCountyRead/write
postCodePost CodeRead/write
guidTokenGuid TokenWrite (invitation token)
📎 Also includes the embedded part documentAttachments (based on BC's standard "APIV2 - Document Attachments" page), linked via Document Id = SystemId.
🔐 Token security (OnModifyRecord trigger): before applying any change, it compares the incoming Guid Token against the one already stored on the record and checks that its expiry has not passed. If anything doesn't match, the request is rejected with an error; if it checks out, the change is applied and both token fields are cleared, so the link stops working after its first use.
🌐 ApiConnectBC Architecture
A Node.js / Express application with no heavy client-side framework: server-rendered EJS templates and Axios to talk to the BC API. It stores no data of its own — it acts purely as a secure bridge between the prospect's browser and Business Central.

MethodRouteDescription
GET/Serves form.html: manual entry form for Id and token
GET/api/update-precustomer/:id/:guidGets an OAuth2 token, issues a GET to the BC API and renders the pre-filled form
POST/api/update-precustomer/:id/:guidIssues a PATCH to the BC API with the edited fields and guidToken; renders success or error
📁 Layout: server.js (Express bootstrap) · auth/oauth.js (client-credentials token) · routes/bc.js (GET/POST routes) · views/update-precustomer.ejs + views/success.ejs · public/form.html + public/css/style.css 📦 Dependencies: express, ejs, axios, dotenv, express-session.
🛡️ Security
  • OAuth2 client credentials: ApiConnectBC authenticates app-only against login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token with scope https://api.businesscentral.dynamics.com/.default; the prospect never sees or needs BC credentials.
  • The Client Secret lives only in the server's .env file and never reaches the prospect's browser.
  • The Guid Token is single-use and expires per Token Time; after a valid update it is cleared and the link stops working.
  • The E-mail field is read-only in the form, preventing a prospect from redirecting their record to a different inbox.
📝 Prerequisites
  • Business Central with the Pre Customer extension installed and published (tested on v26.0).
  • An Azure AD app registration with API permission over Business Central and a valid Client Secret.
  • A Node.js environment to host ApiConnectBC, ideally behind HTTPS for the emailed links.
  • Business Central's outgoing email connector configured (Email Setup) so the codeunit can send invitations.

Comentarios