Skip to content

Integracion con Microsoft Dynamics 365

Por que Dynamics 365

Microsoft Dynamics 365 Business Central (antes NAV) es el ERP de referencia para empresas del ecosistema Microsoft. Su integracion nativa con Power Platform, Office 365 y Azure lo hace ideal para empresas que ya usan tecnologias Microsoft.

Lo que puedes integrar

ProcesoComo se conecta
Facturas ventaWebhook Cargoffer -> Power Automate -> Dynamics
ClientesAPI Cargoffer -> API Dynamics
ProveedoresSincronizacion batch
PagosConciliacion automatica

Opcion 1: Power Automate (sin codigo)

Recomendada para equipos sin desarrollo. Crea un flujo que:

  1. Trigger: HTTP request (recibe webhook de Cargoffer)
  2. Accion: Buscar cliente en Dynamics por CIF
  3. Condicion: Si existe -> crear factura. Si no -> crear cliente + factura
  4. Accion: Crear factura venta en Dynamics 365

Plantilla Power Automate

Para importar esta plantilla en Power Automate:

  1. Ve a https://make.powerautomate.com
  2. Importa -> Carga el archivo
  3. Configura las conexiones a Cargoffer y Dynamics
json
{
  "definition": {
    "triggers": {
      "when_a_http_request_is_received": {
        "type": "OpenApiConnection",
        "inputs": {
          "host": {
            "connectionName": "shared_webhooks",
            "operationId": "WhenAHttpRequestIsReceived"
          },
          "parameters": {
            "schema": "{\"type\":\"object\",\"properties\":{\"event\":{\"type\":\"string\"},\"data\":{\"type\":\"object\"}}}"
          }
        }
      }
    },
    "actions": {
      "Create_invoice": {
        "type": "OpenApiConnection",
        "inputs": {
          "host": {
            "connectionName": "shared_dynamicssmbsaas",
            "operationId": "CreateEntity",
            "parameters": {
              "entityName": "salesInvoices",
              "body": {
                "customerId": "@{outputs('Get_customer')['value'][0]['customerId']}",
                "postingDate": "@{triggerBody()?['data']?['date']}",
                "salesInvoiceLines": [{
                  "description": "@{concat('Transporte ', triggerBody()?['data']?['serviceCode'])}",
                  "quantity": 1,
                  "unitPrice": "@{triggerBody()?['data']?['amount']}"
                }]
              }
            }
          }
        }
      }
    }
  }
}

Opcion 2: API Directa (recomendada para volumen)

bash
# Autenticar en Dynamics
curl -X POST "https://login.microsoftonline.com/tu-tenant/oauth2/v2.0/token" \
  -d "client_id=tu_client_id" \
  -d "client_secret=tu_secret" \
  -d "scope=https://api.businesscentral.dynamics.com/.default" \
  -d "grant_type=client_credentials"

# Crear factura
curl -X POST "https://api.businesscentral.dynamics.com/v2.0/tu-tenant/api/v2.0/companies(tu_company_id)/salesInvoices" \
  -H "Authorization: Bearer *** \
  -H "Content-Type: application/json" \
  -d '{
    "customerId": "A12345678",
    "postingDate": "2026-06-17",
    "salesInvoiceLines": [{
      "description": "Transporte SRV-2026-001",
      "quantity": 1,
      "unitPrice": 1250.00
    }]
  }'

Guia paso a paso

Paso 1: Registrar aplicacion en Azure AD

Necesitas una aplicacion registrada en Azure Active Directory con permisos para:

  • Financials.ReadWrite.All
  • Automation.ReadWrite.All

Paso 2: Configurar webhook en Cargoffer

bash
curl -X POST "https://api.pro.cargoffer.com/api/webhook" \
  -H "Authorization: Bearer *** \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://tu-api-azure.azurewebsites.net/cargoffer-webhook",
    "events": ["contract.signed"]
  }'

Paso 3: Procesar con Azure Functions

python
import azure.functions as func
import requests, os

def main(req: func.HttpRequest) -> func.HttpResponse:
    evento = req.get_json()
    
    if evento["event"] == "contract.signed":
        contrato = evento["data"]
        
        # Obtener token Dynamics
        token = obtener_token_dynamics()
        
        # Crear factura
        headers = {
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json"
        }
        
        factura = {
            "customerId": contrato["client"]["cif"],
            "postingDate": contrato["date"],
            "salesInvoiceLines": [{
                "description": f"Transporte {contrato['serviceCode']}",
                "quantity": 1,
                "unitPrice": contrato["amount"]
            }]
        }
        
        r = requests.post(
            f"{DYNAMICS_URL}/salesInvoices",
            headers=headers, json=factura
        )
        
        return func.HttpResponse(f"Factura creada: {r.status_code}")

Documentacion relacionada

Documentación de Cargoffer