> ## Documentation Index
> Fetch the complete documentation index at: https://docs.payana.la/llms.txt
> Use this file to discover all available pages before exploring further.

# Oracle Fusion

> Guía de configuración para administradores de Oracle Fusion Cloud ERP — integración Payana

<Tabs>
  <Tab title="Español">
    Guía paso a paso para que los administradores de Oracle Fusion Cloud ERP configuren y obtengan todas las credenciales y permisos necesarios para la integración con Payana.

    La integración usa las **REST APIs de Fusion** (`fscmRestApi`) autenticadas con **OAuth 2.0** contra el identity domain de OCI IAM asociado a tu instancia.

    <Note>
      Oracle Fusion no expone una API única e idéntica para todos los clientes: las unidades de negocio, los libros contables, los roles y los campos de localización dependen de cómo esté implementada **tu** instancia. Por eso esta guía incluye un paso de descubrimiento (sección 1) antes de la configuración técnica.
    </Note>

    ***

    ## 1. Obtener los datos del entorno

    1. Identifica la URL de tu instancia (**pod**). Tiene la forma `https://<pod>.fa.<región>.oraclecloud.com`.
    2. Anota si es **producción** o **test/sandbox**. Si tienes ambos, comparte los dos: la integración se configura y valida primero en test.
    3. Identifica el **release** en el que está la instancia (26A, 26B, 26C…). Lo encuentras en **Ayuda > Acerca de esta aplicación**.
    4. Identifica la URL del **identity domain** de OCI IAM asociado a la instancia. Tiene la forma `https://<idcs-id>.identity.oraclecloud.com`.

    <Tip>
      Puedes confirmar los endpoints exactos del identity domain consultando `https://idcs-<idcs-id>.identity.oraclecloud.com/.well-known/idcs-configuration` desde el navegador.
    </Tip>

    ### 1.1 Alcance funcional

    Además de los datos técnicos, define con tu equipo de finanzas:

    | Dato | Por qué se necesita |
    | - | - |
    | **Business Units (BU)** | Determina qué facturas y pagos ve la integración. Sin acceso a la BU, la API responde vacío. |
    | **Ledgers y monedas** | Define el contexto contable de las facturas que se crean o leen. |
    | **Invoice Source** | Identifica en Fusion las facturas originadas en Payana. Debe existir antes de empezar. |
    | **Métodos y términos de pago** | Se usan al registrar los pagos. |
    | **Cuentas bancarias propias** | Las cuentas de la empresa habilitadas en Payables desde las que se pagan las facturas. |

    ***

    ## 2. Crear el usuario de integración

    1. Ve a **Herramientas > Security Console > Usuarios > Agregar usuario**.
    2. Crea un usuario dedicado, por ejemplo `PAYANA_INTEGRATION`.
    3. Asocia una dirección de correo controlada por tu equipo de TI.
    4. Haz clic en **Guardar**.

    <Tip>
      Usa siempre un usuario dedicado y no la cuenta personal de un empleado: si esa persona deja la empresa o cambia de rol, la integración se cae. Verifica también que la política de expiración de contraseña no aplique a esta cuenta, o programa su rotación.
    </Tip>

    ***

    ## 3. Crear el rol de integración

    ### 3.1 Crear el rol

    1. Ve a **Herramientas > Security Console > Roles > Crear rol**.
    2. Configura:
       * **Nombre del rol:** `Conexión Payana`.
       * **Código del rol:** `PAYANA_INTEGRATION_JOB`.
       * **Categoría del rol:** **Common — Job Roles**.
    3. Avanza por el asistente y guarda.

    <Note>
      **¿Por qué un rol propio y no uno predefinido?**\
      Los roles predefinidos de Oracle (por ejemplo *Accounts Payable Manager*) traen cientos de privilegios que la integración no necesita, y suelen ser lo primero que una auditoría interna retira. Un rol propio, construido a partir de los roles de referencia de la sección 3.2, sobrevive a la auditoría y deja explícito qué hace la integración.
    </Note>

    ### 3.2 Roles de referencia por área funcional

    En la pestaña **Jerarquía de roles** del rol `Conexión Payana`, agrega los roles de referencia correspondientes al alcance acordado. Cada uno aporta los privilegios de su área.

    | Área funcional | Rol de referencia de Oracle | Motivo |
    | - | - | - |
    | Facturas de proveedor (AP) | Accounts Payable Specialist | Leer y crear facturas de proveedor, sus líneas, distribuciones y cuotas. |
    | Pagos | Accounts Payable Manager | Registrar pagos manuales y consultarlos. Incluye *Payables Payment Processing*. |
    | Proveedores (lectura) | Supplier Manager | Leer el maestro de proveedores, sus sitios, direcciones y contactos. |
    | Datos bancarios de proveedores | Accounts Payable Manager | Aporta *Payee Bank Account Management*, necesario para leer o crear cuentas bancarias. |
    | Órdenes de compra (si aplica) | Procurement Integration Specialist | Leer órdenes de compra para vincularlas a las facturas. |
    | Datos contables (cuentas, libros) | General Accountant | Leer el plan de cuentas, combinaciones contables y libros. |
    | Carga masiva (`erpintegrations`) | Financial Integration Specialist | Solo si se usará carga masiva FBDI para la migración inicial. |

    <Warning>
      Los nombres de los roles predefinidos son los de la *Security Reference for Financials* y *for Procurement* de Oracle, pero **el conjunto exacto de privilegios que necesita tu instancia debe validarlo tu equipo de seguridad**. La recomendación práctica es partir de estos roles, probar la integración en el entorno de test, y retirar después lo que no se use.
    </Warning>

    ### 3.3 Recursos REST que usa la integración

    Esta es la lista de recursos REST a los que accede la integración. Sirve para que tu equipo de seguridad verifique que el rol los cubre.

    | Recurso REST | Uso en la integración Payana |
    | - | - |
    | `suppliers` (+ `sites`, `addresses`, `contacts`) | Sincronización del maestro de proveedores y sus sitios por unidad de negocio. |
    | `externalBankAccounts`, `paymentsExternalPayees`, `instrumentAssignments` | Datos bancarios del proveedor. Son tres recursos encadenados. |
    | `invoices` (+ `invoiceLines`, `invoiceDistributions`, `invoiceInstallments`, `attachments`) | Lectura de cuentas por pagar y creación de facturas desde Payana. |
    | `payablesPayments` (+ `relatedInvoices`) | Registro del pago en Fusion y su asociación a las facturas saldadas. |
    | `purchaseOrders` | Lectura de órdenes de compra para vincularlas a las facturas. |
    | `accountCombinationsLOV` | Combinaciones contables y segmentos del plan de cuentas. |
    | `dataAccessSetLedgersLOV` | Libros contables accesibles por el usuario de integración. |
    | `payablesAndProcurementOptions` | Opciones de Payables por unidad de negocio. |
    | `erpintegrations` | Carga masiva FBDI. Solo si se usa para la migración inicial. |

    <Note>
      Los recursos para **impuestos, retenciones, centros de costo, bodegas y proyectos** dependen de cómo esté configurada la contabilidad analítica en tu instancia: en Fusion esos conceptos suelen vivir como **segmentos del plan de cuentas** o como **flexfields**, no como recursos REST independientes. Se confirman en la sesión de descubrimiento (sección 1.1).
    </Note>

    ### 3.4 Acceso a datos (data security)

    Este paso es tan importante como los permisos funcionales y es el que más se olvida.

    1. Ve a **Herramientas > Security Console** o al área de configuración **Gestionar acceso a datos para usuarios**.
    2. Busca el usuario `PAYANA_INTEGRATION`.
    3. Asigna el acceso a datos para el rol `Conexión Payana`:
       * **Business Unit:** las BU acordadas en la sección 1.1.
       * **Ledger / Data Access Set:** los libros correspondientes.
    4. Guarda.

    <Warning>
      **El error más difícil de diagnosticar.** Si faltan las políticas de acceso a datos, la API **no devuelve 403**: devuelve `200 OK` con `count: 0`. Una integración que "conecta bien" pero no trae ningún registro casi siempre es esto, no un problema de filtros ni de credenciales.
    </Warning>

    ### 3.5 Asignar el rol al usuario

    1. Ve a **Herramientas > Security Console > Usuarios**.
    2. Busca `PAYANA_INTEGRATION` y edítalo.
    3. En **Roles**, agrega `Conexión Payana`.
    4. Guarda.

    ***

    ## 4. Registrar la aplicación OAuth en OCI IAM

    1. Ingresa a la consola del **identity domain** de OCI IAM asociado a la instancia, como administrador.
    2. Ve a **Integrated applications > Add application**.
    3. Selecciona **Confidential Application** y haz clic en **Launch workflow**.
    4. Nombra la aplicación, por ejemplo `Payana Integration`.
    5. En la sección de configuración, marca **Configure this application as a client now**.
    6. En **Authorization**, marca el grant type **Client credentials**.
    7. En **Token issuance policy**, establece **Authorized resources** en **Specific**, y agrega el recurso de Fusion con su scope.
    8. Haz clic en **Finish** y luego en **Activate**.
    9. **Copia y guarda** el **Client ID** y el **Client Secret**.

    <Warning>
      El **Client Secret** solo se muestra una vez. Si se pierde, debes generar uno nuevo desde la aplicación.
    </Warning>

    ### 4.1 Obtener el scope

    El scope de OAuth **no es genérico**: es propio de tu instancia. Tiene la forma:

    ```text theme={null}
    urn:opc:resource:fa:<instanceid>=<podname> urn:opc:resource:consumer::all
    ```

    Para obtenerlo, en la consola de IAM abre el servicio **Oracle Applications Cloud (Fusion)** y localiza la propiedad **`IDCS_CONNECTOR_CLIENT_SCOPE`**. Copia el valor completo.

    ***

    ## 5. Vincular el Client ID con Fusion

    Este paso es obligatorio y es la causa más común de que la primera prueba falle.

    1. Copia el **Client ID** generado en el paso 4.
    2. Ve a **Herramientas > Security Console > Usuarios**.
    3. Crea un usuario cuyo **nombre de usuario sea exactamente el Client ID**.
    4. Asígnale el rol `Conexión Payana` y el mismo acceso a datos configurado en la sección 3.4.
    5. Guarda.

    <Warning>
      Con el grant `client_credentials`, Fusion resuelve la identidad de la llamada a partir del Client ID. Si ese Client ID no existe como usuario dentro de Fusion, el identity domain emite el token correctamente **pero la API responde 401 o devuelve `count: 0`**. Es un fallo silencioso: el token es válido, el usuario no existe.
    </Warning>

    ***

    ## 6. Resumen de valores para compartir con Payana

    | Campo | Dónde obtenerlo |
    | - | - |
    | URL del pod | URL de la instancia (`https://<pod>.fa.<región>.oraclecloud.com`) |
    | Tipo de entorno | Producción / Test |
    | Release | Ayuda > Acerca de esta aplicación (26A, 26B, 26C…) |
    | URL del identity domain | `https://<idcs-id>.identity.oraclecloud.com` |
    | Client ID | Aplicación confidencial en OCI IAM (paso 4) |
    | Client Secret | Se muestra una vez al crear la aplicación |
    | Scope de OAuth | Propiedad `IDCS_CONNECTOR_CLIENT_SCOPE` en IAM (sección 4.1) |
    | Business Units en alcance | Definidas en la sección 1.1 |
    | Invoice Source | Definido en la sección 1.1 |

    Comparte estos valores por un **canal seguro**. El Client Secret nunca debe enviarse por correo ni por chat sin cifrar.

    ***

    <div>
      ## 7. Lista de verificación

      * [ ] Tienes la URL del pod de test y, si aplica, la de producción.
      * [ ] Tienes la URL del identity domain de OCI IAM.
      * [ ] Existe el usuario de integración dedicado (`PAYANA_INTEGRATION`).
      * [ ] Existe el rol `Conexión Payana` con categoría **Common — Job Roles**.
      * [ ] El rol incluye los roles de referencia del alcance acordado (sección 3.2).
      * [ ] El usuario tiene configurado el **acceso a datos** por Business Unit y Ledger (sección 3.4).
      * [ ] El rol `Conexión Payana` está asignado al usuario de integración.
      * [ ] La aplicación confidencial en OCI IAM está creada y **activada**.
      * [ ] El grant **Client credentials** está habilitado y los **Authorized resources** están en **Specific**.
      * [ ] Tienes el Client ID, el Client Secret y el scope completo.
      * [ ] **Existe un usuario en Fusion cuyo nombre es exactamente el Client ID**, con el rol y el acceso a datos asignados (sección 5).
      * [ ] Las Business Units, los ledgers y el Invoice Source están definidos y comunicados.
      * [ ] Los valores se compartieron con Payana de forma segura.
      * [ ] Se verificó el acceso con una solicitud de prueba (sección 8).
    </div>

    ***

    ## 8. Validar la conexión (Opcional)

    Una vez configuradas las credenciales, verifica que la integración tiene acceso correcto a Fusion. Son dos llamadas: obtener el token y usarlo.

    <Steps>
      <Step title="Obtener un access token">
        Reemplaza los valores y ejecuta en una terminal:

        ```bash theme={null}
        CLIENT_ID="tu_client_id"
        CLIENT_SECRET="tu_client_secret"
        DOMAIN="https://idcs-xxxxx.identity.oraclecloud.com"
        SCOPE="urn:opc:resource:fa:instanceid=xxxxx urn:opc:resource:consumer::all"

        curl -s -u "${CLIENT_ID}:${CLIENT_SECRET}" --basic \
          -H "Content-Type: application/x-www-form-urlencoded;charset=UTF-8" \
          -X POST "${DOMAIN}/oauth2/v1/token" \
          --data-urlencode "grant_type=client_credentials" \
          --data-urlencode "scope=${SCOPE}"
        ```

        La respuesta contiene el `access_token`, con una validez de 3600 segundos.
      </Step>

      <Step title="Consultar proveedores">
        Usa el token obtenido:

        ```bash theme={null}
        TOKEN="pega_aqui_el_access_token"
        POD="https://tupod.fa.us2.oraclecloud.com"

        curl -s -H "Authorization: Bearer ${TOKEN}" \
          -H "Content-Type: application/json" \
          "${POD}/fscmRestApi/resources/11.13.18.05/suppliers?limit=1&onlyData=true"
        ```
      </Step>

      <Step title="Consultar facturas">
        Confirma también el acceso a Payables:

        ```bash theme={null}
        curl -s -H "Authorization: Bearer ${TOKEN}" \
          -H "Content-Type: application/json" \
          "${POD}/fscmRestApi/resources/11.13.18.05/invoices?limit=1&onlyData=true"
        ```
      </Step>
    </Steps>

    ### Respuesta esperada

    Una respuesta **200 OK** con `count` mayor que cero confirma que las credenciales, los permisos y el acceso a datos están correctos:

    ```json theme={null}
    {
      "items": [
        {
          "SupplierId": 300000012345678,
          "SupplierNumber": "1001",
          "Supplier": "Proveedor Ejemplo S.A.S."
        }
      ],
      "count": 1,
      "hasMore": true,
      "limit": 1,
      "offset": 0
    }
    ```

    ### Errores comunes

    | Código | Significado | Qué revisar |
    | - | - | - |
    | `400` | Scope inválido | El scope debe copiarse completo, incluyendo `urn:opc:resource:consumer::all`. Revisa la sección 4.1. |
    | `401` | Credenciales inválidas | Verifica Client ID y Secret, que la aplicación esté **activada**, y que exista el usuario en Fusion con el nombre del Client ID (sección 5). |
    | `403` | Permisos insuficientes | El rol no tiene los privilegios necesarios. Revisa la sección 3.2. |
    | `404` | URL incorrecta | Confirma el pod y que la ruta incluya `/fscmRestApi/resources/11.13.18.05/`. |
    | `429` | Throttling | Oracle aplica límites de uso justo, no publicados. La integración reintenta con espera progresiva; si es persistente, revisa la ventana de sync. |

    <AccordionGroup>
      <Accordion title="200 OK pero count: 0">
        Este es el caso más frecuente y **no es un error de credenciales**. Si el token se emite y la API responde `200` con `"count": 0`, casi siempre falta el **acceso a datos** del usuario de integración.

        Revisa, en este orden:

        1. Que el usuario tenga asignado el acceso a datos por **Business Unit** (sección 3.4).
        2. Que tenga asignado el **Data Access Set** del ledger correspondiente.
        3. Que el usuario creado con el nombre del **Client ID** tenga el mismo rol y el mismo acceso a datos (sección 5). Es habitual configurarlos solo en `PAYANA_INTEGRATION` y olvidarlos en el usuario del Client ID.
        4. Que realmente existan registros en esa BU.
      </Accordion>

      <Accordion title="Consultas de validación adicionales">
        Una vez que la consulta básica funcione, verifica el acceso a los demás recursos que usa la integración:

        ```bash theme={null}
        # Libros contables accesibles
        curl -s -H "Authorization: Bearer ${TOKEN}" \
          "${POD}/fscmRestApi/resources/11.13.18.05/dataAccessSetLedgersLOV?limit=5&onlyData=true"

        # Órdenes de compra
        curl -s -H "Authorization: Bearer ${TOKEN}" \
          "${POD}/fscmRestApi/resources/11.13.18.05/purchaseOrders?limit=1&onlyData=true"

        # Pagos registrados
        curl -s -H "Authorization: Bearer ${TOKEN}" \
          "${POD}/fscmRestApi/resources/11.13.18.05/payablesPayments?limit=1&onlyData=true"

        # Combinaciones contables
        curl -s -H "Authorization: Bearer ${TOKEN}" \
          "${POD}/fscmRestApi/resources/11.13.18.05/accountCombinationsLOV?limit=1&onlyData=true"
        ```

        Si todas responden `200` (aunque `items` venga vacío por no haber registros en esa BU), las credenciales y permisos están correctamente configurados.
      </Accordion>

      <Accordion title="Filtrar por fecha de actualización">
        La integración lee de forma incremental usando `LastUpdateDate`. Puedes probar el mismo filtro:

        ```bash theme={null}
        curl -s -G -H "Authorization: Bearer ${TOKEN}" \
          "${POD}/fscmRestApi/resources/11.13.18.05/invoices" \
          --data-urlencode 'q=LastUpdateDate >= "2026-01-01T00:00:00+00:00"' \
          --data-urlencode 'fields=InvoiceId,InvoiceNumber,SupplierNumber,InvoiceAmount,UnpaidAmount' \
          --data-urlencode 'limit=5' \
          --data-urlencode 'onlyData=true'
        ```
      </Accordion>
    </AccordionGroup>

    ***

    ## 9. Consideraciones de mantenimiento

    | Tema | Qué implica |
    | - | - |
    | **Actualizaciones trimestrales** | Oracle actualiza Fusion cada trimestre (26A, 26B, 26C…) y el entorno de test se actualiza antes que producción. Avísanos con anticipación para validar la integración. |
    | **Rotación del secreto** | Si rotas el Client Secret, la integración deja de funcionar hasta que compartas el nuevo valor. Coordina la rotación con el equipo de Payana. |
    | **Localización LATAM** | En Colombia (DIAN/CUFE) y México (CFDI) los identificadores fiscales y los datos del documento electrónico viven en **flexfields globales (GDF)**, con nombres propios de cada instancia. Se mapean en la sesión de descubrimiento. |
    | **Límites de uso** | Oracle no publica límites de tasa; aplica throttling de uso justo y responde `429`. La integración lo maneja con reintentos progresivos y ventanas de sincronización acotadas. |
  </Tab>

  <Tab title="English">
    Step-by-step guide for Oracle Fusion Cloud ERP administrators to configure and obtain all the credentials and permissions required by the Payana integration.

    The integration uses the **Fusion REST APIs** (`fscmRestApi`) authenticated with **OAuth 2.0** against the OCI IAM identity domain associated with your instance.

    <Note>
      Oracle Fusion does not expose a single identical API for every customer: business units, ledgers, roles and localization fields depend on how **your** instance was implemented. That is why this guide includes a discovery step (section 1) before the technical configuration.
    </Note>

    ***

    ## 1. Gather environment details

    1. Identify your instance (**pod**) URL. It looks like `https://<pod>.fa.<region>.oraclecloud.com`.
    2. Note whether it is **production** or **test/sandbox**. If you have both, share both: the integration is configured and validated in test first.
    3. Identify the **release** your instance is on (26A, 26B, 26C…). You'll find it under **Help > About This Application**.
    4. Identify the **OCI IAM identity domain** URL associated with the instance. It looks like `https://<idcs-id>.identity.oraclecloud.com`.

    <Tip>
      You can confirm the exact identity domain endpoints by opening `https://idcs-<idcs-id>.identity.oraclecloud.com/.well-known/idcs-configuration` in a browser.
    </Tip>

    ### 1.1 Functional scope

    Beyond the technical details, define the following with your finance team:

    | Detail | Why it's needed |
    | - | - |
    | **Business Units (BU)** | Determines which invoices and payments the integration can see. Without BU access the API returns empty. |
    | **Ledgers and currencies** | Defines the accounting context of the invoices created or read. |
    | **Invoice Source** | Identifies Payana-originated invoices inside Fusion. It must exist before starting. |
    | **Payment methods and terms** | Used when registering payments. |
    | **Internal bank accounts** | Your company's accounts enabled in Payables, used to pay the invoices. |

    ***

    ## 2. Create the integration user

    1. Go to **Tools > Security Console > Users > Add User Account**.
    2. Create a dedicated user, for example `PAYANA_INTEGRATION`.
    3. Associate an email address controlled by your IT team.
    4. Click **Save**.

    <Tip>
      Always use a dedicated user rather than an employee's personal account: if that person leaves or changes roles, the integration breaks. Also confirm the password expiration policy does not apply to this account, or schedule its rotation.
    </Tip>

    ***

    ## 3. Create the integration role

    ### 3.1 Create the role

    1. Go to **Tools > Security Console > Roles > Create Role**.
    2. Configure:
       * **Role Name:** `Payana Connection`.
       * **Role Code:** `PAYANA_INTEGRATION_JOB`.
       * **Role Category:** **Common — Job Roles**.
    3. Step through the wizard and save.

    <Note>
      **Why a custom role instead of a predefined one?**\
      Oracle's predefined roles (for example *Accounts Payable Manager*) carry hundreds of privileges the integration does not need, and they are usually the first thing an internal audit strips away. A custom role built from the reference roles in section 3.2 survives the audit and makes the integration's footprint explicit.
    </Note>

    ### 3.2 Reference roles by functional area

    On the **Role Hierarchy** tab of the `Payana Connection` role, add the reference roles matching the agreed scope. Each contributes the privileges of its area.

    | Functional area | Oracle reference role | Reason |
    | - | - | - |
    | Supplier invoices (AP) | Accounts Payable Specialist | Read and create supplier invoices, their lines, distributions and installments. |
    | Payments | Accounts Payable Manager | Create and query manual payments. Includes *Payables Payment Processing*. |
    | Suppliers (read) | Supplier Manager | Read the supplier master, its sites, addresses and contacts. |
    | Supplier bank accounts | Accounts Payable Manager | Provides *Payee Bank Account Management*, required to read or create bank accounts. |
    | Purchase orders (if applicable) | Procurement Integration Specialist | Read purchase orders to link them to invoices. |
    | Accounting data (accounts, ledgers) | General Accountant | Read the chart of accounts, account combinations and ledgers. |
    | Bulk load (`erpintegrations`) | Financial Integration Specialist | Only if FBDI bulk load will be used for the initial migration. |

    <Warning>
      These predefined role names come from Oracle's *Security Reference for Financials* and *for Procurement*, but **the exact set of privileges your instance needs must be validated by your security team**. The practical recommendation is to start from these roles, test the integration in the test environment, and then strip what isn't used.
    </Warning>

    ### 3.3 REST resources used by the integration

    This is the list of REST resources the integration accesses. Use it so your security team can verify the role covers them.

    | REST resource | Use in the Payana integration |
    | - | - |
    | `suppliers` (+ `sites`, `addresses`, `contacts`) | Supplier master sync and its sites per business unit. |
    | `externalBankAccounts`, `paymentsExternalPayees`, `instrumentAssignments` | Supplier bank details. These are three chained resources. |
    | `invoices` (+ `invoiceLines`, `invoiceDistributions`, `invoiceInstallments`, `attachments`) | Reading payables and creating invoices from Payana. |
    | `payablesPayments` (+ `relatedInvoices`) | Registering the payment in Fusion and linking it to the settled invoices. |
    | `purchaseOrders` | Reading purchase orders to link them to invoices. |
    | `accountCombinationsLOV` | Account combinations and chart of accounts segments. |
    | `dataAccessSetLedgersLOV` | Ledgers accessible to the integration user. |
    | `payablesAndProcurementOptions` | Payables options per business unit. |
    | `erpintegrations` | FBDI bulk load. Only if used for the initial migration. |

    <Note>
      Resources for **taxes, withholdings, cost centers, warehouses and projects** depend on how analytical accounting is configured in your instance: in Fusion those concepts usually live as **chart of accounts segments** or **flexfields**, not as standalone REST resources. They are confirmed during the discovery session (section 1.1).
    </Note>

    ### 3.4 Data access (data security)

    This step matters as much as the functional privileges, and it is the one most often forgotten.

    1. Go to **Tools > Security Console** or to the **Manage Data Access for Users** setup task.
    2. Look up the `PAYANA_INTEGRATION` user.
    3. Assign data access for the `Payana Connection` role:
       * **Business Unit:** the BUs agreed in section 1.1.
       * **Ledger / Data Access Set:** the corresponding ledgers.
    4. Save.

    <Warning>
      **The hardest error to diagnose.** If data access policies are missing, the API **does not return 403**: it returns `200 OK` with `count: 0`. An integration that "connects fine" but returns no records is almost always this, not a filter or credentials problem.
    </Warning>

    ### 3.5 Assign the role to the user

    1. Go to **Tools > Security Console > Users**.
    2. Look up `PAYANA_INTEGRATION` and edit it.
    3. Under **Roles**, add `Payana Connection`.
    4. Save.

    ***

    ## 4. Register the OAuth application in OCI IAM

    1. Sign in to the **OCI IAM identity domain** console associated with the instance, as an administrator.
    2. Go to **Integrated applications > Add application**.
    3. Select **Confidential Application** and click **Launch workflow**.
    4. Name the application, for example `Payana Integration`.
    5. In the configuration section, select **Configure this application as a client now**.
    6. Under **Authorization**, select the **Client credentials** grant type.
    7. Under **Token issuance policy**, set **Authorized resources** to **Specific**, and add the Fusion resource with its scope.
    8. Click **Finish** and then **Activate**.
    9. **Copy and store** the **Client ID** and **Client Secret**.

    <Warning>
      The **Client Secret** is shown only once. If it's lost, you must generate a new one from the application.
    </Warning>

    ### 4.1 Getting the scope

    The OAuth scope is **not generic**: it is specific to your instance. It looks like:

    ```text theme={null}
    urn:opc:resource:fa:<instanceid>=<podname> urn:opc:resource:consumer::all
    ```

    To obtain it, open the **Oracle Applications Cloud (Fusion)** service in the IAM console and locate the **`IDCS_CONNECTOR_CLIENT_SCOPE`** property. Copy the full value.

    ***

    ## 5. Link the Client ID to Fusion

    This step is mandatory and is the most common reason a first test fails.

    1. Copy the **Client ID** generated in step 4.
    2. Go to **Tools > Security Console > Users**.
    3. Create a user whose **username is exactly the Client ID**.
    4. Assign it the `Payana Connection` role and the same data access configured in section 3.4.
    5. Save.

    <Warning>
      With the `client_credentials` grant, Fusion resolves the caller's identity from the Client ID. If that Client ID does not exist as a user inside Fusion, the identity domain issues the token correctly **but the API returns 401 or `count: 0`**. It's a silent failure: the token is valid, the user is not there.
    </Warning>

    ***

    ## 6. Summary of values to share with Payana

    | Field | Where to get it |
    | - | - |
    | Pod URL | Instance URL (`https://<pod>.fa.<region>.oraclecloud.com`) |
    | Environment type | Production / Test |
    | Release | Help > About This Application (26A, 26B, 26C…) |
    | Identity domain URL | `https://<idcs-id>.identity.oraclecloud.com` |
    | Client ID | Confidential application in OCI IAM (step 4) |
    | Client Secret | Shown once when the application is created |
    | OAuth scope | `IDCS_CONNECTOR_CLIENT_SCOPE` property in IAM (section 4.1) |
    | Business Units in scope | Defined in section 1.1 |
    | Invoice Source | Defined in section 1.1 |

    Share these values through a **secure channel**. The Client Secret must never be sent by email or unencrypted chat.

    ***

    <div>
      ## 7. Checklist

      * [ ] You have the test pod URL and, if applicable, the production one.
      * [ ] You have the OCI IAM identity domain URL.
      * [ ] The dedicated integration user exists (`PAYANA_INTEGRATION`).
      * [ ] The `Payana Connection` role exists with category **Common — Job Roles**.
      * [ ] The role includes the reference roles for the agreed scope (section 3.2).
      * [ ] The user has **data access** configured per Business Unit and Ledger (section 3.4).
      * [ ] The `Payana Connection` role is assigned to the integration user.
      * [ ] The confidential application in OCI IAM is created and **activated**.
      * [ ] The **Client credentials** grant is enabled and **Authorized resources** is set to **Specific**.
      * [ ] You have the Client ID, the Client Secret and the full scope.
      * [ ] **A Fusion user exists whose username is exactly the Client ID**, with the role and data access assigned (section 5).
      * [ ] Business Units, ledgers and Invoice Source are defined and communicated.
      * [ ] The values were shared with Payana securely.
      * [ ] Access was verified with a test request (section 8).
    </div>

    ***

    ## 8. Validate the connection (Optional)

    Once the credentials are configured, verify the integration has proper access to Fusion. It's two calls: get the token, then use it.

    <Steps>
      <Step title="Get an access token">
        Replace the values and run in a terminal:

        ```bash theme={null}
        CLIENT_ID="your_client_id"
        CLIENT_SECRET="your_client_secret"
        DOMAIN="https://idcs-xxxxx.identity.oraclecloud.com"
        SCOPE="urn:opc:resource:fa:instanceid=xxxxx urn:opc:resource:consumer::all"

        curl -s -u "${CLIENT_ID}:${CLIENT_SECRET}" --basic \
          -H "Content-Type: application/x-www-form-urlencoded;charset=UTF-8" \
          -X POST "${DOMAIN}/oauth2/v1/token" \
          --data-urlencode "grant_type=client_credentials" \
          --data-urlencode "scope=${SCOPE}"
        ```

        The response contains the `access_token`, valid for 3600 seconds.
      </Step>

      <Step title="Query suppliers">
        Use the token you obtained:

        ```bash theme={null}
        TOKEN="paste_the_access_token_here"
        POD="https://yourpod.fa.us2.oraclecloud.com"

        curl -s -H "Authorization: Bearer ${TOKEN}" \
          -H "Content-Type: application/json" \
          "${POD}/fscmRestApi/resources/11.13.18.05/suppliers?limit=1&onlyData=true"
        ```
      </Step>

      <Step title="Query invoices">
        Confirm Payables access as well:

        ```bash theme={null}
        curl -s -H "Authorization: Bearer ${TOKEN}" \
          -H "Content-Type: application/json" \
          "${POD}/fscmRestApi/resources/11.13.18.05/invoices?limit=1&onlyData=true"
        ```
      </Step>
    </Steps>

    ### Expected response

    A **200 OK** response with `count` greater than zero confirms credentials, privileges and data access are all correct:

    ```json theme={null}
    {
      "items": [
        {
          "SupplierId": 300000012345678,
          "SupplierNumber": "1001",
          "Supplier": "Example Supplier Inc."
        }
      ],
      "count": 1,
      "hasMore": true,
      "limit": 1,
      "offset": 0
    }
    ```

    ### Common errors

    | Code | Meaning | What to check |
    | - | - | - |
    | `400` | Invalid scope | The scope must be copied in full, including `urn:opc:resource:consumer::all`. See section 4.1. |
    | `401` | Invalid credentials | Check the Client ID and Secret, that the application is **activated**, and that a Fusion user named after the Client ID exists (section 5). |
    | `403` | Insufficient privileges | The role lacks the required privileges. See section 3.2. |
    | `404` | Wrong URL | Confirm the pod and that the path includes `/fscmRestApi/resources/11.13.18.05/`. |
    | `429` | Throttling | Oracle applies unpublished fair-use limits. The integration retries with progressive backoff; if persistent, review the sync window. |

    <AccordionGroup>
      <Accordion title="200 OK but count: 0">
        This is the most frequent case and it is **not a credentials error**. If the token is issued and the API returns `200` with `"count": 0`, the integration user is almost always missing **data access**.

        Check, in this order:

        1. That the user has data access assigned per **Business Unit** (section 3.4).
        2. That it has the ledger's **Data Access Set** assigned.
        3. That the user created with the **Client ID** as its username has the same role and the same data access (section 5). It's common to configure them only on `PAYANA_INTEGRATION` and forget the Client ID user.
        4. That records actually exist in that BU.
      </Accordion>

      <Accordion title="Additional validation queries">
        Once the basic query works, verify access to the remaining resources the integration uses:

        ```bash theme={null}
        # Accessible ledgers
        curl -s -H "Authorization: Bearer ${TOKEN}" \
          "${POD}/fscmRestApi/resources/11.13.18.05/dataAccessSetLedgersLOV?limit=5&onlyData=true"

        # Purchase orders
        curl -s -H "Authorization: Bearer ${TOKEN}" \
          "${POD}/fscmRestApi/resources/11.13.18.05/purchaseOrders?limit=1&onlyData=true"

        # Registered payments
        curl -s -H "Authorization: Bearer ${TOKEN}" \
          "${POD}/fscmRestApi/resources/11.13.18.05/payablesPayments?limit=1&onlyData=true"

        # Account combinations
        curl -s -H "Authorization: Bearer ${TOKEN}" \
          "${POD}/fscmRestApi/resources/11.13.18.05/accountCombinationsLOV?limit=1&onlyData=true"
        ```

        If they all return `200` (even with an empty `items` array because there are no records in that BU), credentials and privileges are correctly configured.
      </Accordion>

      <Accordion title="Filtering by last update date">
        The integration reads incrementally using `LastUpdateDate`. You can test the same filter:

        ```bash theme={null}
        curl -s -G -H "Authorization: Bearer ${TOKEN}" \
          "${POD}/fscmRestApi/resources/11.13.18.05/invoices" \
          --data-urlencode 'q=LastUpdateDate >= "2026-01-01T00:00:00+00:00"' \
          --data-urlencode 'fields=InvoiceId,InvoiceNumber,SupplierNumber,InvoiceAmount,UnpaidAmount' \
          --data-urlencode 'limit=5' \
          --data-urlencode 'onlyData=true'
        ```
      </Accordion>
    </AccordionGroup>

    ***

    ## 9. Maintenance considerations

    | Topic | What it means |
    | - | - |
    | **Quarterly updates** | Oracle updates Fusion every quarter (26A, 26B, 26C…) and the test environment is updated before production. Let us know in advance so we can validate the integration. |
    | **Secret rotation** | If you rotate the Client Secret, the integration stops working until you share the new value. Coordinate rotation with the Payana team. |
    | **LATAM localization** | In Colombia (DIAN/CUFE) and Mexico (CFDI), tax identifiers and electronic document data live in **global flexfields (GDF)**, with names specific to each instance. These are mapped during the discovery session. |
    | **Usage limits** | Oracle does not publish rate limits; it applies fair-use throttling and returns `429`. The integration handles this with progressive retries and bounded sync windows. |
  </Tab>
</Tabs>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.