Skip to content

About

Express API that takes donations through Stripe Checkout, logs them to Google Sheets, and emails receipts.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

Donation API

CI License: MIT

An Express and TypeScript API that takes donations through Stripe Checkout. When a payment succeeds, Stripe calls the API's webhook, which adds a row to a Google Sheet and emails the donor a receipt. It comes with a small donate page, Docker Compose with an nginx reverse proxy, and tests that run in CI without any secrets.

In plain terms, a donor fills in a short form and pays on Stripe's secure page. The organization then sees the gift in a spreadsheet it already uses, and the donor gets a thank-you email with the amount and a payment reference. Card details never touch this server.

What it looks like

These screenshots come from one real test-mode donation, run with this repo's make dev setup.

1. Donate page 2. Stripe Checkout (test card)
Donate form with preset amounts, name and email fields Stripe Checkout in sandbox mode with the 4242 test card filled in
3. Back on the site 4. Receipt email (in Mailpit)
Thank-you page showing the payment reference Receipt email: Dear Ada Lovelace, we received your donation of $25.00

The same donation in the Google Sheet. The API created the Donations tab and its header row on first use.

Google Sheet with a Donations tab: header row and one row for Ada Lovelace, 25 USD, with the receipt time

The full values, since the sheet cuts off the longer cells:

Date Checkout session Donor name Donor email Amount Currency Receipt sent at
2026-12-02T10:03:42.268Z cs_test_a0K5we30… Ada Lovelace ada.lovelace+1796205806@example.com 25 USD 2026-12-02T10:03:43.191Z

How a donation flows

  1. The donate page posts the donor's name, email and amount to POST /create.
  2. The API validates the input, converts the amount to cents, and creates a Stripe Checkout Session. The page redirects the donor to Stripe.
  3. The donor pays on Stripe's hosted page. Stripe sends them back to /success.html.
  4. Stripe sends a checkout.session.completed event to POST /webhook. The API checks the event's signature against the webhook secret and rejects anything Stripe didn't sign.
  5. The API appends a row to the Google Sheet, emails the receipt, then writes the time it sent the receipt into that row.

If step 5 fails, the webhook answers 500 and Stripe retries the event later. Each row stores the Checkout Session id, so a retried or duplicated event never adds a second row or sends a second email.

Quick start

You need Docker and a free Stripe account. Everything runs in Stripe's test mode, so no real money moves. Google Sheets is optional; without it, donations are kept in memory.

git clone https://github.com/wubeZ/donation-api.git
cd donation-api
cp .env.example .env
  1. Copy your test secret key from the Stripe dashboard into .env as STRIPE_SECRET_KEY. It starts with sk_test_.

  2. Get the webhook signing secret that the Stripe CLI uses, and put it in .env as STRIPE_WEBHOOK_SECRET:

    make webhook-secret   # prints whsec_...
  3. Start the API, nginx, Mailpit and the Stripe CLI:

    make dev
  4. Open http://localhost:8080 and donate with card 4242 4242 4242 4242, any future expiry date and any CVC.

  5. Open http://localhost:8025 to read the receipt in Mailpit.

Follow one test donation end to end

This is the same run as the screenshots above, with what to look for at each step. It assumes the quick start is running.

  1. Donate $25 at http://localhost:8080. The server log shows the session:

    {"level":30,"sessionId":"cs_test_a0K5…","amountCents":2500,"msg":"Created checkout session"}
    
  2. Pay on Stripe Checkout with the 4242 card. Stripe sends you back to /success.html?session_id=cs_test_….

  3. The Stripe CLI receives the event and forwards it through nginx (make logs):

    --> checkout.session.completed [evt_1UiANy…]
    <--  [200] POST http://reverse-proxy:8080/webhook [evt_1UiANy…]
    
  4. The server records the donation and sends the receipt:

    {"level":30,"sessionId":"cs_test_a0K5…","row":2,"msg":"Donation recorded"}
    {"level":30,"sessionId":"cs_test_a0K5…","msg":"Receipt sent"}
    
  5. With Google Sheets configured, the Donations tab has a new row. The API creates the tab and its header row on first use.

  6. Mailpit shows "Your $25.00 donation to Hope Foundation".

  7. Send the same event again to see the duplicate protection:

    docker compose exec stripe-cli stripe events resend evt_1UiANy…

    Stripe delivers it again and the API answers 200, but logs Donation already recorded and Receipt already sent. The sheet still has one row and Mailpit still has one email.

Connect Google Sheets

  1. In Google Cloud, create a project and enable the Google Sheets API.

  2. Create a service account, then add a JSON key under Keys.

  3. Create a Google Sheet and share it with the service account's client_email as Editor.

  4. Fill in .env:

    GOOGLE_CLIENT_EMAIL=donation-api@your-project.iam.gserviceaccount.com
    # private_key from the JSON file, on one line, keeping the \n sequences
    GOOGLE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMIIE...\n-----END PRIVATE KEY-----\n"
    # the id in docs.google.com/spreadsheets/d/<id>/edit
    GOOGLE_SHEET_ID=your-sheet-id
  5. Restart with make dev.

The API writes cells as plain text (valueInputOption: RAW), so a donor name such as =HYPERLINK(...) is stored as text and never runs as a formula.

Run without Docker

Requires Node.js 24, the Stripe CLI and an SMTP server. Mailpit works for local email: docker run -p 1025:1025 -p 8025:8025 axllent/mailpit.

npm install
stripe listen --forward-to localhost:8000/webhook   # copy the whsec_ into .env
npm run dev                                          # http://localhost:8000

npm run dev runs the TypeScript source directly with Node's type stripping and restarts on changes. npm run build && npm start runs the compiled output.

API

POST /create

Creates a Stripe Checkout Session.

curl -X POST http://localhost:8080/create \
  -H 'content-type: application/json' \
  -d '{"donorName":"Ada Lovelace","donorEmail":"ada@example.com","amount":"25.00"}'
{ "checkoutSessionId": "cs_test_...", "checkoutUrl": "https://checkout.stripe.com/c/pay/cs_test_..." }
Field Rule
donorName 1 to 100 characters
donorEmail a valid email address
amount a string or number from 1.00 to 999,999.99, with at most 2 decimals

Invalid input returns 400 with a list of errors:

{ "errors": [{ "field": "amount", "message": "Amount must be between 1.00 and 999,999.99" }] }

Each IP can call this endpoint 20 times every 15 minutes. After that it returns 429.

POST /webhook

Receives Stripe events. It needs the raw request body and a valid Stripe-Signature header, and returns 400 otherwise. It handles:

Event Action
checkout.session.completed Records the donation and sends the receipt if the payment is complete. Delayed methods such as bank debits arrive unpaid and wait for the next event.
checkout.session.async_payment_succeeded Records a delayed payment once it clears.
checkout.session.async_payment_failed Logs a warning.

GET /health

Returns {"status":"ok"}. The Docker healthcheck uses it.

GET /info

Returns the organization name, currency and whether Stripe is in test mode. The donate page uses it.

Configuration

Copy .env.example to .env. The server checks every variable at startup and exits with a list of problems if any is missing or malformed.

Variable Default Purpose
STRIPE_SECRET_KEY required sk_test_... or sk_live_...
STRIPE_WEBHOOK_SECRET required whsec_... from stripe listen or the dashboard webhook endpoint
PUBLIC_URL http://localhost:8000 (8080 in Compose) Where Stripe sends donors back to
ORG_NAME Example Charity Shown on the page and in receipts
CURRENCY usd One of usd, eur, gbp, cad, aud
GOOGLE_CLIENT_EMAIL, GOOGLE_PRIVATE_KEY, GOOGLE_SHEET_ID empty Set all three, or none to keep donations in memory
GOOGLE_SHEET_TAB Donations Tab to write to. Created if missing.
SMTP_HOST, SMTP_PORT Mailpit Any SMTP server. Port 465 uses TLS, other ports use STARTTLS when offered.
SMTP_USER, SMTP_PASS empty SMTP login, if the server needs one
MAIL_FROM Example Charity <donations@example.org> Sender of the receipt
ALLOWED_ORIGINS empty Comma-separated sites allowed to call /create from a browser. The bundled page needs none.
TRUST_PROXY 0 (1 in Compose) Number of proxies in front of the app, so rate limiting sees the real client IP
PORT 8000 Port the API listens on
LOG_LEVEL info pino log level
NODE_ENV production development turns on readable logs

Tests and CI

npm test         # unit and HTTP tests, no network or secrets needed
make check       # lint, type-check, tests and build, the same as CI

The tests sign webhook payloads with a test-only secret, so they exercise the real signature check. They cover:

  • input validation and the cents conversion (19.99 must become 1999, not 1998.9999999999998)
  • bad and tampered signatures
  • pending payments
  • duplicate and concurrent deliveries
  • a failed email being sent on Stripe's retry without a second row
  • the receipt template, including HTML escaping of the donor's name
  • config parsing, security headers, CORS and the rate limit

test/integration/flow.test.ts runs the flow through the real Stripe SDK against stripe-mock and sends a real email to Mailpit. CI starts both as service containers. Locally:

docker run -d -p 12111:12111 stripe/stripe-mock
docker run -d -p 1025:1025 -p 8025:8025 axllent/mailpit
STRIPE_MOCK_URL=http://localhost:12111 MAILPIT_URL=http://localhost:8025 npm test

GitHub Actions runs lint, type-check, all tests, the build and npm audit on every push and pull request. It also builds the Docker image.

Going live

  1. Switch STRIPE_SECRET_KEY to a live key.
  2. In the Stripe dashboard, add a webhook endpoint at https://your-domain/webhook for the three events above. Put its signing secret in STRIPE_WEBHOOK_SECRET.
  3. Set PUBLIC_URL to your domain, and the SMTP_* and MAIL_FROM variables to your email provider.
  4. Run make up behind a TLS-terminating proxy or load balancer. The bundled nginx listens on plain HTTP port 8080.

Known limitations

  • The lock that stops two copies of the same event from running at once is per process. A single server, or several servers receiving Stripe's normal one-at-a-time retries, records each donation once. Two servers receiving the same event at the same moment could both write a row. Fixing that needs a shared store such as Redis or a database.
  • If Stripe sends a paid session with no donor email, the webhook answers 500 and Stripe keeps retrying for up to 3 days. The bundled donate page always collects an email, so this only happens with sessions created some other way.
  • The ledger finds earlier rows by reading the session id column of the sheet. That is fine for thousands of donations. Past that, a database is the better ledger.

Project layout

src/
  server.ts            reads config, wires services, starts the server
  app.ts               Express routes and middleware
  config.ts            environment parsing and validation
  donations.ts         turns a Checkout Session into a donation, records it once
  money.ts             amount parsing and formatting
  receipt.ts           receipt email template
  validation.ts        request body schema
  services/
    payments.ts        Stripe Checkout and webhook verification
    ledger.ts          Google Sheets ledger and in-memory ledger
    mailer.ts          SMTP mailer
public/                donate page and success page
reverse-proxy/         nginx config
test/                  vitest tests, plus the stripe-mock and Mailpit integration test

License

MIT © Wubshet Zeleke

About

Express API that takes donations through Stripe Checkout, logs them to Google Sheets, and emails receipts.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages