---
url: /technical/process-sage-micropay-example.md
---

# Sage MicrOpay Example

The code below is a simple example of a process connecting to Sage MicrOpay (Micropay Cloud API). It authenticates with Basic Auth plus a separate API key header rather than MODLR's built-in OAuth 2.0 flow, so this is an [Advanced Integration](/technical/integrations.html#advanced-integrations).

::: info
This process requires Sage MicrOpay credentials (user, password and API token) per instance/region, stored as [Secrets](/process-functions/security-getsecret.html) rather than hardcoded in the process.
:::

## Library Code

A small helper for querying the Micropay Cloud API. Save this as a [Process Library](/technical/process-libraries.html) (e.g. `libraries/micropay.js`) and load it with [`script.library`](/process-functions/script-library.html).

```js
const MICROPAY_URL = "https://api.cloud.micropay.com.au/api/";

function micropayQuery(instance, path) {
    const credentials = {
        user: security.getSecret(`MICROPAY_${instance.toUpperCase()}_USER`),
        password: security.getSecret(`MICROPAY_${instance.toUpperCase()}_PASSWORD`),
        token: security.getSecret(`MICROPAY_${instance.toUpperCase()}_TOKEN`)
    };

    const response = web.get(MICROPAY_URL + path, {
        "Authorization": "Basic " + script.base64(`${credentials.user}:${credentials.password}`, "utf8"),
        "Api-Key": script.base64(credentials.token, "utf8"),
        "Accept": "application/json"
    });

    if (response.status >= 200 && response.status < 300) {
        return JSON.parse(response.body);
    } else {
        console.log(`Request failed. Status ${response.status}. Body:`, response.body);
        return null;
    }
}
```

## Process Code

```js
script.library("libraries/micropay.js");

function pre() {
    // This function is called once before the process is executed.
    // Use this to setup prompts.
    script.log('process pre-execution parameters parsed.');
}

function begin() {
    // This function is called once at the start of the process
    script.log('process execution started.');

    const result = micropayQuery("au", "PublicHolidays");
    console.log(result);
}

function data(record) {
    // This function is called once for each line of data on the second cycle
    // Use this to build dimensions and push data into cubes
}

function end() {
    // This function is called once at the end of the process
    script.log('process execution finished.');
}
```
