← Guides
Sincronizar Contatos com ERP
Mantenha os contatos do CRM sincronizados com seu sistema ERP usando paginação e sync incremental.
Pré-requisitos
- Um Service Account (Client ID + Client Secret)
- Sistema ERP com API ou banco de dados de contatos
- Um job agendado ou cron para executar o sync periodicamente
Passo 1: Autenticar
Obtenha um token de acesso usando as credenciais do cliente:
cURL
curl -X POST https://magnetcustomer.net/realms/platform/protocol/openid-connect/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials&client_id=YOUR_ID&client_secret=YOUR_SECRET"Passo 2: Buscar contatos com paginação
Use os parâmetros page e limit para percorrer todos os contatos:
cURL
curl "https://minha-empresa.platform-api.magnetcustomer.com/api/contacts?page=1&limit=100" \
-H "Authorization: Bearer YOUR_TOKEN"Response 200
{
"docs": [
{
"_id": "507f1f77bcf86cd799439011",
"lifeCycle": "customer",
"fullname": "Joao Silva",
"email": "joao@empresa.com.br",
"phones": [{ "number": "11988880000", "typePhone": "cellphone", "ddi": "+55" }],
"updatedAt": "2026-01-15T14:30:00Z"
}
],
"total": 1147,
"pages": 12,
"page": 1,
"limit": 100
}Passo 3: Mapear campos para o formato ERP
Transforme a estrutura de contato do CRM para corresponder ao schema do seu ERP:
Node.js
function mapCrmToErp(contact: CrmContact): ErpContact {
return {
erpId: contact._id,
name: contact.fullname,
email: contact.email,
phone: contact.phones?.[0]?.number ?? null,
// Map custom fields
taxId: contact.customFields?.find(f => f.k === 'cpf')?.v ?? null,
updatedAt: contact.updatedAt,
};
}Passo 4: Sync incremental usando updatedAt
A listagem de contatos não tem filtro por data. Ordene pela alteração mais recente e pare ao chegar num contato anterior ao último sync:
cURL
# Most recently changed first: stop when you reach a contact older than the last sync
curl "https://minha-empresa.platform-api.magnetcustomer.com/api/contacts?page=1&limit=100&sortBy=updatedAt&sortType=desc" \
-H "Authorization: Bearer YOUR_TOKEN"Loop de sync completo (Node.js)
Node.js
import { MagnetCustomer } from '@magnetcustomer/sdk';
const crm = new MagnetCustomer({
account: 'minha-empresa',
clientId: process.env.MAGNET_CLIENT_ID,
clientSecret: process.env.MAGNET_CLIENT_SECRET,
});
async function syncContactsToErp(lastSyncAt?: string) {
const startedAt = new Date().toISOString();
for (let page = 1; ; page++) {
const { data } = await crm.contacts.listContacts({
page,
limit: 100,
sortBy: 'updatedAt',
sortType: 'desc',
});
for (const contact of data.docs ?? []) {
// Sorted by most recent change: everything from here on was already synced
if (lastSyncAt && contact.updatedAt <= lastSyncAt) return finish(startedAt);
await erp.contacts.upsert(mapCrmToErp(contact));
}
if (page >= (data.pages ?? 0)) return finish(startedAt);
}
}
// Persist sync timestamp for next run
async function finish(startedAt: string) {
await db.set('lastContactSync', startedAt);
}Próximo: Aprenda a configurar webhooks para receber as atualizações de contatos em tempo real, em vez de consultar de tempos em tempos.