> ## 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.

# A fundraising thermometer

> Show a campaign’s total against its target on your group’s website. It updates itself, and no key ever sits in the website’s code.

> [!NOTE]
>
> * **For:** treasurers and whoever runs the website
> * **You get:** a thermometer on your website that fills as donations come in, with no key in the website's code
> * **Time:** about fifteen minutes
> * **Scopes:** `fundraising:read`

This recipe puts a fundraising thermometer on your group's website: a bar that fills as donations come in, with the total raised and the target. It updates itself as people give through Scoutworks.

It has two parts, and it takes about fifteen minutes:

1. A Google Sheet that reads your campaigns from Scoutworks every hour.
2. A small piece of HTML on your website that reads the sheet.

> [!WARNING]
>
> **Never put an API key in your website's code.** Anyone can read a web page's code, so a key there is public. The website reads only a published sheet of totals. The key stays in the sheet's script, in Script Properties, where visitors cannot see it.

## 1. Fill a sheet with your campaigns

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

```javascript Code.gs theme={null}
// Scoutworks → fundraising thermometer. https://developers.scoutworks.app/recipes/fundraising-thermometer

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

function updateTotals() {
  const campaigns = readAll('/fundraising-campaigns');

  // Only open and ended campaigns: a draft is not public yet.
  const rows = [['slug', 'raised', 'target', 'donations', 'status']];
  campaigns.forEach(function (c) {
    if (c.status === 'draft') return;
    rows.push([c.slug, c.totalRaised, c.targetAmount || '', String(c.donationCount), c.status]);
  });

  const book = SpreadsheetApp.getActive();
  const sheet = book.getSheetByName('Totals') || book.insertSheet('Totals');
  sheet.clearContents();
  const range = sheet.getRange(1, 1, rows.length, rows[0].length);
  range.setNumberFormat('@'); // Plain text, so 1250.00 is never shown as 1,250.
  range.setValues(rows);
}

// 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.');
}
```

Then:

**1. 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.

**2. Run it**

Choose **updateTotals** and press **Run**. Open the **Totals** tab. Each campaign has a row, found by its `slug`: the last part of the campaign's address on your donate page.

**3. Refresh it every hour**

Choose **Triggers** (the clock), then **Add Trigger**. Function: `updateTotals`. Event source: **Time-driven**. Type: **Hour timer**. Every: **hour**.

## 2. Publish the totals tab

In the sheet, choose **File → Share → Publish to web**. Under **Link**, choose the **Totals** tab (not **Entire document**) and **Comma-separated values (.csv)**. Choose **Publish** and copy the address.

The published tab holds only campaign totals: no donor names, no amounts of single gifts and no key. Google updates a published sheet within about five minutes of a change.

## 3. Add the thermometer to your website

Paste this where the thermometer should go. Change the two lines at the top: the address you copied, and your campaign's slug.

```html Thermometer theme={null}
<div id="thermometer" style="font-family: sans-serif; max-width: 420px;">
  <div style="background: #e5e7eb; border-radius: 999px; height: 24px; overflow: hidden;">
    <div data-bar style="background: #7413dc; height: 100%; width: 0; transition: width 1s;"></div>
  </div>
  <p data-text style="margin: 8px 0 0;">Loading…</p>
</div>
<script>
  (function () {
    const SHEET_CSV = 'PASTE_THE_PUBLISHED_CSV_ADDRESS';
    const CAMPAIGN = 'PASTE_THE_CAMPAIGN_SLUG';

    const box = document.getElementById('thermometer');
    const money = new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'GBP' });

    fetch(SHEET_CSV)
      .then(function (res) { return res.text(); })
      .then(function (csv) {
        // Every cell is a slug, a number or a status, so a comma always splits cells.
        const row = csv.trim().split(/\r?\n/).map(function (line) { return line.split(','); })
          .find(function (cells) { return cells[0] === CAMPAIGN; });
        if (!row) throw new Error('No campaign called ' + CAMPAIGN);

        const raised = Number(row[1]);
        const target = Number(row[2]);
        const text = target
          ? money.format(raised) + ' raised of ' + money.format(target)
          : money.format(raised) + ' raised';
        box.querySelector('[data-text]').textContent = text + ' from ' + row[3] + ' donations';
        if (target) {
          box.querySelector('[data-bar]').style.width = Math.min(100, (raised / target) * 100) + '%';
        }
      })
      .catch(function () {
        box.querySelector('[data-text]').textContent = 'The total is not available just now.';
      });
  })();
</script>
```

Most website builders take this in an **HTML**, **Embed** or **Code** block. Change the bar's colour to match your site.

## 4. Switch to your group

In the script, change `api-demo.scoutworks.app` to `api.scoutworks.app`, and replace the sandbox key with your own. Your key needs the `fundraising:read` scope. **Give it no other scope.** In the snippet, change `CAMPAIGN` to your own campaign's slug.

## Notes

* **The total matches Scoutworks.** It counts paid donations only, without Gift Aid added.
* **A campaign with no target** shows the total raised and no bar.
* **How fresh.** The sheet reads Scoutworks every hour, and Google publishes the change within about five minutes. A donation reaches the thermometer within about an hour.
* **Your own server instead.** If your website has its own server, it can call `GET /fundraising-campaigns` itself, keep the key in its settings, and pass only the totals to the page. The rule is the same: the key never reaches the browser.


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