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

# Who hasn’t paid

> Every payment request that is not yet paid, by young person and by camp or trip, and every Direct Debit that failed. In a Google Sheet.

> [!NOTE]
>
> * **For:** treasurers, and leaders running a camp or trip
> * **You get:** a **Not paid** tab and a **Failed Direct Debits** tab, refreshed every morning
> * **Time:** about ten minutes
> * **Scopes:** `payments:read`, `payments.people:read`, `members:read` and `events:read`

Before a camp, someone has to chase the families who have not paid. This recipe lists every payment request that is not yet paid, with the young person, the parent to contact, what it is for and when it was due. A second tab lists the Direct Debits that failed, so you can ask the family to check their bank.

## 1. Try the requests

Paste these into a terminal to see the demo group's unpaid requests and failed payments:

```bash theme={null}
curl "https://api-demo.scoutworks.app/api/v1/payment-requests?status=failed&limit=200" \
  -H "Authorization: Bearer sw_test_473adcc6c7236916021f0f24559db36576a53bab071d0f0c08a025adb510b6ab"

curl "https://api-demo.scoutworks.app/api/v1/payments?status=failed&limit=200" \
  -H "Authorization: Bearer sw_test_473adcc6c7236916021f0f24559db36576a53bab071d0f0c08a025adb510b6ab"
```

## 2. Add the script

In your Google Sheet, choose **Extensions → Apps Script**. Delete what is there, paste the script below and choose **Save**.

```javascript Code.gs theme={null}
// Scoutworks → who hasn't paid. https://developers.scoutworks.app/recipes/who-hasnt-paid

const BASE = 'https://api-demo.scoutworks.app/api/v1';

// Payment request statuses that still need money, in plain words.
const OUTSTANDING = {
  pending: 'Not paid',
  failed: 'Payment failed',
  processing: 'Being collected',
  payment_created: 'Being collected',
};

// Direct Debit statuses that mean the money did not arrive.
const FAILED = {
  failed: 'Failed',
  customer_approval_denied: 'Refused by the bank',
  charged_back: 'Charged back',
};

function whoHasntPaid() {
  const today = Utilities.formatDate(new Date(), 'Europe/London', 'yyyy-MM-dd');

  const members = {};
  // Leavers too: a family can still owe money after a young person leaves.
  readAll('/members').concat(readAll('/members?status=archived')).forEach(function (m) {
    members[m.id] = (m.preferredName || m.firstName) + ' ' + m.lastName;
  });
  // Published events. For a camp now archived, the request's own description names it.
  const events = {};
  readAll('/events').forEach(function (e) {
    events[e.id] = e.title;
  });

  // Unpaid requests: oldest due first.
  const requests = readAll('/payment-requests');
  const notPaid = requests
    .filter(function (r) { return OUTSTANDING[r.status]; })
    .sort(function (a, b) { return a.dueDate.localeCompare(b.dueDate); })
    .map(function (r) {
      return [
        safe(members[r.memberId] || ''),
        safe(events[r.eventId] || r.description),
        Number(r.amount),
        r.dueDate.slice(0, 10),
        r.dueDate.slice(0, 10) < today ? 'Overdue' : 'Due',
        OUTSTANDING[r.status],
        safe(r.parent ? r.parent.name || '' : ''),
        safe(r.parent ? r.parent.email || '' : ''),
      ];
    });
  writeTab('Not paid', [['Young person', 'For', 'Amount (£)', 'Due', 'When', 'Status', 'Parent', 'Email']].concat(notPaid));

  // Direct Debits that failed or were charged back.
  const byRequest = {};
  requests.forEach(function (r) { byRequest[r.id] = r; });
  const failed = readAll('/payments')
    .filter(function (p) { return FAILED[p.status]; })
    .sort(function (a, b) { return b.chargeDate.localeCompare(a.chargeDate); })
    .map(function (p) {
      const request = p.paymentRequestId ? byRequest[p.paymentRequestId] : null;
      return [
        p.chargeDate.slice(0, 10),
        Number(p.amount),
        FAILED[p.status],
        p.subscriptionId ? 'Regular subscription' : safe(request ? request.description : 'One-off payment'),
        safe(request ? members[request.memberId] || '' : ''),
        safe(p.parent ? p.parent.name || '' : ''),
        safe(p.parent ? p.parent.email || '' : ''),
      ];
    });
  writeTab('Failed Direct Debits', [['Date', 'Amount (£)', 'What happened', 'For', 'Young person', 'Parent', 'Email']].concat(failed));

  SpreadsheetApp.getActive().toast(notPaid.length + ' not paid, ' + failed.length + ' failed Direct Debits.');
}

// Replaces a tab's contents with these rows.
function writeTab(name, rows) {
  const book = SpreadsheetApp.getActive();
  const sheet = book.getSheetByName(name) || book.insertSheet(name);
  sheet.clearContents();
  sheet.getRange(1, 1, rows.length, rows[0].length).setValues(rows);
  sheet.setFrozenRows(1);
}

// Every item in a list, following nextCursor to the last page.
function readAll(path) {
  const items = [];
  let cursor = null;
  do {
    let url = BASE + path + (path.indexOf('?') === -1 ? '?' : '&') + 'limit=200';
    if (cursor) url += '&cursor=' + encodeURIComponent(cursor);
    const body = fetchScoutworks(url);
    items.push.apply(items, body.data);
    cursor = body.nextCursor;
  } while (cursor);
  return items;
}

// Calls the API. Waits and tries again if the rate limit is reached.
function fetchScoutworks(url) {
  const apiKey = PropertiesService.getScriptProperties().getProperty('SCOUTWORKS_API_KEY');
  if (!apiKey) throw new Error('Add SCOUTWORKS_API_KEY in Project Settings → Script Properties.');
  for (let attempt = 0; attempt < 3; attempt++) {
    const res = UrlFetchApp.fetch(url, {
      headers: { Authorization: 'Bearer ' + apiKey },
      muteHttpExceptions: true,
    });
    const body = JSON.parse(res.getContentText());
    if (res.getResponseCode() === 200) return body;
    if (res.getResponseCode() === 429) {
      Utilities.sleep((body.retryAfter || 30) * 1000);
      continue;
    }
    throw new Error(body.error.code + ': ' + body.error.message);
  }
  throw new Error('Scoutworks is still busy. Try again in a minute.');
}

// Stops text that starts with = + - or @ from running as a formula.
function safe(value) {
  const text = String(value);
  return /^\s*[=+\-@]/.test(text) ? "'" + text : text;
}
```

## 3. Add your key

Choose **Project Settings** (the cog), then **Script Properties → Add script property**. Property: `SCOUTWORKS_API_KEY`. Value: the [sandbox key](https://developers.scoutworks.app/guides/sandbox.md) to try it, or your own key.

## 4. Run it

Choose **whoHasntPaid** and press **Run**. The first time, Google asks you to allow the script to reach an outside service.

* **Not paid** lists each request still waiting for money, oldest due date first. **Being collected** means a Direct Debit is on its way: give it a few days before you chase.
* **Failed Direct Debits** lists each collection that failed, that the parent's bank refused, or that it reversed, newest first.

To refresh it every morning, add a **Day timer** trigger for `whoHasntPaid`, as in [Your members in Google Sheets](https://developers.scoutworks.app/recipes/google-sheets.md#4-refresh-it-every-morning).

## 5. Switch to your group

Change `api-demo.scoutworks.app` to `api.scoutworks.app`, and replace the sandbox key with your own. The key needs `payments:read` for the amounts and dates, `payments.people:read` for the parent and the young person each payment is for, `members:read` for names and `events:read` for camp and trip names.

> [!WARNING]
>
> This sheet holds parents' names and emails, and who owes money. Share it only with the leaders who need it, and delete it when the camp is paid for.

## Variations

* **One camp.** Filter the **For** column, or keep only rows whose request has the camp's `eventId`.
* **Hear about a failure the moment it happens.** [Tell the treasurer when a Direct Debit fails](https://developers.scoutworks.app/recipes/direct-debit-failed.md) sends a message within a minute, using a webhook.
* **Chase by email.** Use the **Email** column with a mail merge add-on. Write the message yourself: a kind reminder works better than a demand.

## If something goes wrong

* **The Young person or Parent column is empty**: the key does not have `payments.people:read`.
* **`403 insufficient_scope`**: the key is missing one of the scopes above. The message says which.

See [Errors](https://developers.scoutworks.app/guides/errors.md) for every code.


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