Documentation
Refreal documentation
Refreal is a self-hosted affiliate tracker. It runs on Cloudflare Pages with a D1 database, so there is no server to maintain. It records referral clicks, credits sales from Polar.sh, Stripe or a custom checkout, calculates commissions and helps you pay affiliates.
What's in the box
- An admin dashboard at
/adminfor affiliates, conversions, payouts and settings. - A private portal for each affiliate at
/portal?token=…, plus an optional public sign-up page at/signup. - A tracker script at
/tracker.jsthat you add to your storefront. - Webhook endpoints at
/webhooks/polar,/webhooks/stripeand/webhooks/generic. - Optional emails through Resend, Brevo or Mailgun.
How a referral works
- An affiliate shares your store link with their code, for example
https://yourstore.com/?via=MAYA25. tracker.jssends the click to Refreal and stores a click ID in a cookie on your store's domain.- The tracker adds that click ID to your Polar or Stripe checkout links as
reference_idorclient_reference_id. - When the order is paid, the provider calls your Refreal webhook. Refreal finds the click, credits the affiliate and records the commission as pending.
- You approve conversions and mark them paid when you pay the affiliate.
You need: a Cloudflare account (free is enough), a GitHub account to hold the code, and a Polar.sh, Stripe or custom checkout to track.
Deploy to Cloudflare
Plan on about ten minutes. You deploy Refreal as a Pages project connected to a GitHub repository.
1. Put the code in GitHub
Unzip the download and push the folder to a new repository. A private repository works. The repository root must contain the public/, functions/ and migrations/ folders.
2. Create the Pages project
- In the Cloudflare dashboard open Workers & Pages → Create → Pages → Connect to Git and pick the repository.
- Set Framework preset to None and leave Build command empty.
- Set Build output directory to
public.
Do not skip the output directory. If it is left at the default, the pages load with no styling because the CSS files are never published. To fix an existing project, change it under Settings → Builds and retry the deployment.
3. Create the database and bind it
- Go to Storage & Databases → D1 → Create database. The database name can be anything in lowercase, for example
refreal. - Open your Pages project, then Settings → Bindings → Add → D1 database. Set the Variable name to exactly
DB(capitals) and choose your database.
The database name and the variable name are two different things. The app only looks for the variable DB.
4. Set the admin password
Under Settings → Variables and Secrets add a secret named ADMIN_PASSWORD with the password you want for the first login. Add it for the Production environment.
5. Redeploy and log in
Bindings and secrets only apply to new deployments. Open Deployments and retry the latest one. Then open https://your-project.pages.dev/admin and log in. The database tables are created automatically on the first request.
After logging in, open Settings → Master Password and change the password. Once you do, the password you choose is stored (hashed) in the database and ADMIN_PASSWORD is no longer used for login. Changing it also signs out every other session.
6. Add your own domain (optional)
In the Pages project open Custom domains and add a domain or subdomain such as refer.yourstore.com. This is optional. Your project already has a free your-project.pages.dev address, which works just as well.
Two addresses, two jobs. Your Refreal address hosts the dashboard, the tracker script and the webhooks. Your store is where affiliates send visitors. They do not need to be on the same domain. Throughout these docs, your-refreal-address means the first one.
Prefer the command line?
The schema is also provided as migrations/0001_init.sql. You can apply it with wrangler d1 migrations apply if you prefer, but it is not required.
Add the tracker
Open Settings → Tracker Snippet and copy the tag. Paste it before </body> on every page of your store. Both addresses in the tag are your Refreal address, not your store's. It looks like this:
<script src="https://your-refreal-address/tracker.js"
data-refreal-endpoint="https://your-refreal-address"></script>
What the tracker does
- When a visitor arrives with
?via=CODE, it sends the click to/clickand stores the returned click ID in a cookie calledrefreal_via. The cookie lasts for the number of days set in Cookie Expiry. - On every page, it adds the click ID to your checkout links:
- Links to
polar.shget?reference_id=…. - Links to
buy.stripe.comget?client_reference_id=….
- Links to
- It also tags links that are added to the page later and links that open in an overlay.
Other checkout links
For a checkout on another domain, mark the link yourself:
<!-- uses reference_id -->
<a href="https://pay.example.com/checkout" data-refreal-checkout>Buy</a>
<!-- uses a parameter name you choose -->
<a href="https://pay.example.com/checkout" data-refreal-param="ref">Buy</a>
Allowing your store to call Refreal
Your store and Refreal are normally on different domains, so the browser needs permission for the tracker to call Refreal. CORS Allowed Origins in Settings defaults to *, which works everywhere. To restrict it, enter your store's address, for example https://yourstore.com. Separate several stores with commas.
The click ID is also available to your own code as window.__refreal_click_uid after a tracked visit.
Polar.sh
1. Add the webhook in Polar
- In Polar open Settings → Webhooks → Add endpoint.
- Set the URL to the Polar webhook address shown in Settings → Integrations (
https://your-refreal-address/webhooks/polar). - Choose the Raw format and subscribe to
order.paidandorder.refunded. - Copy the secret Polar generates.
2. Save the secret in Refreal
Paste the secret into Settings → Integrations → Polar and save. From that moment Refreal rejects any request that is not signed with this secret.
Until a secret is saved, signature checks are skipped. That is fine for local testing, not for production. Save the secret before you go live.
3. Use Polar checkout links
Use normal Polar checkout links on your storefront. The tracker adds reference_id to them, Polar copies it onto the order, and Refreal reads it from the webhook.
Refunds
order.refunded marks the conversion as refunded, and it no longer counts toward payouts.
API version notice
Polar retires old API versions after a period. The dashboard shows a banner when the version your webhooks use is close to being retired or has been. Update the endpoint in Polar if you see it.
Stripe
1. Add the webhook in Stripe
- In Stripe open Developers → Webhooks → Add endpoint.
- Set the URL to
https://your-refreal-address/webhooks/stripe. - Select the events
checkout.session.completedandcharge.refunded. - Copy the Signing secret. It starts with
whsec_.
2. Save the secret in Refreal
Paste it into Settings → Integrations → Stripe Signing Secret. Once saved, unsigned requests are rejected.
3. Use Stripe Payment Links
The tracker adds client_reference_id to buy.stripe.com links, and Stripe returns it on the completed session. If you create Checkout Sessions in your own code, pass the click ID as client_reference_id, or as metadata[refreal_click].
Test mode
Stripe uses a different signing secret in test mode. Use the test secret while testing, then replace it with the live one.
Custom checkout
For any other store, call the generic endpoint from your own server when an order is paid.
1. Create an API key
Refreal generates a key for you. Open Settings → Integrations → Custom Checkout, press Show and then Copy. Use Regenerate API Key if it ever leaks, then update your integration. Keep the key on your server only.
2. Report a sale
curl -X POST https://your-refreal-address/webhooks/generic \
-H "Content-Type: application/json" \
-H "X-Refreal-Api-Key: YOUR_KEY" \
-d '{
"event": "sale",
"external_id": "order_1042",
"click_uid": "the-click-id-from-the-cookie",
"customer_email": "[email protected]",
"amount_cents": 4900,
"currency": "USD"
}'
| Field | Required | Notes |
|---|---|---|
external_id | Yes | Your unique order ID. Sending the same ID twice does not create a second conversion. |
click_uid or ref_code | One of them | The click ID from the refreal_via cookie (best), or the affiliate's referral code. |
event | No | sale (default) or refund. |
amount_cents | No | Order total in the smallest currency unit. |
currency | No | Three-letter code. Defaults to USD. |
customer_email | No | Shown in the conversion list. |
The API key can be sent in the X-Refreal-Api-Key header or as api_key in the JSON body. Use the header: the key is never stored with the conversion, but headers are the safer habit.
3. Report a refund
{ "event": "refund", "external_id": "order_1042" }
Responses
Success returns {"ok": true, "result": {…}}. A missing external_id or a missing click or code returns 400, and a wrong key returns 401.
Attribution
Refreal decides who gets credit using the click ID that travelled with the order.
- If the order carries a click ID, Refreal looks up that click and its affiliate.
- If there is no click ID but the order carries a referral code (generic endpoint), the affiliate is found by code.
- If neither matches an affiliate, the conversion is recorded as unattributed with no commission.
Attribution window
A click can only earn commission for a limited time. Settings → Attribution Window (days) sets the default, and each affiliate can override it on their edit form. If the order arrives after the window has passed, the conversion is recorded as expired unattributed and earns no commission. You still see it in the list.
The window is measured from the click to the order. Cookie Expiry is separate: it controls how long the visitor's browser remembers the click.
Conversion statuses
| Status | Meaning |
|---|---|
| pending | Credited to an affiliate, waiting for your approval. |
| approved | You approved it. It is part of the unpaid balance. |
| paid | Included in a payout you marked as paid. |
| refunded | The order was refunded. No commission is owed. |
| expired unattributed | The click was older than the attribution window. |
| unattributed | No affiliate could be matched. |
Duplicates
A conversion is identified by its source and order ID. If a provider retries a webhook, the repeat is ignored.
Commissions
Set the default under Settings → Affiliate Signup → Default Commission Type and Default Rate. A commission is either:
- Percent: a percentage of the order amount.
- Flat: a fixed amount per sale.
Each affiliate can have their own type and rate. Open the affiliate and edit their commission. The rate is applied when the sale is recorded. Changing a rate later does not rewrite existing conversions.
Commission is calculated on the amount the checkout provider reports for the order.
Affiliates and portal
Add affiliates yourself
Open Affiliates and press the add button to open the New Affiliate form. Enter a name and email, and Refreal creates a referral code and a private portal link. You can set the commission, an attribution window override, a status and internal notes.
Let people apply
With Affiliate Signup switched on in Settings, the public page /signup accepts applications. If Require manual approval is on, new people appear as pending, and the dashboard shows a banner until you approve or reject them. Without approval, they are active immediately.
The portal
Every affiliate has a private link, /portal?token=…. The link is the login, so treat it like a password. From the portal an affiliate can:
- copy their referral link,
- see their clicks, conversions and earnings,
- choose how they want to be paid and edit their payout details (PayPal, Wise, bank transfer or a manual note).
Settings → Program Name replaces the provider name in each conversion's label, so affiliates see "Acme sale" instead of "Polar sale".
Replace a leaked link
On an affiliate's edit form, Regenerate link creates a new token and stops the old link working.
Statuses
Active affiliates are tracked. Pending and rejected affiliates are not. Deleting an affiliate removes their clicks; their past conversions stay in your records without an affiliate attached.
Payouts
The Payouts page lists conversions and lets you act on several at once.
- Filter by status, for example pending.
- Tick the conversions you want and choose Approve Selected. They become part of the unpaid balance.
- Pay your affiliate outside Refreal, using the payout details shown for them.
- Tick the approved conversions and choose Mark Paid. Refreal records a payout and links the conversions to it.
Settings → Minimum Payout Threshold sets the smallest balance you want to pay out.
Export
Download the current list as a CSV. Cells that could be misread as spreadsheet formulas are neutralised, so the file is safe to open in Excel or Google Sheets.
Refreal does not move money. It tracks what you owe and what you have paid.
Email is optional and off by default. When on, Refreal sends a welcome message, an approval message, a payout notice and, if you want, an alert to you when someone applies.
Refreal sends through an email provider's HTTPS API, not SMTP. Choose a provider under Settings → Transactional Email.
| Provider | What you enter |
|---|---|
| Resend | API key |
| Brevo | API key |
| Mailgun | API key, sending domain and region (US or EU) |
- Verify your sending domain with the provider.
- Pick the provider, paste the key and enter a From Address on the verified domain.
- Save, then use Send Test. If it fails, the provider's reason is shown.
Leave a key field blank to keep the saved key. Keys can also be set as Cloudflare secrets named RESEND_API_KEY, BREVO_API_KEY or MAILGUN_API_KEY.
The Admin Notification Email receives a message when someone applies through the sign-up page.
Settings reference
| Setting | Default | What it does |
|---|---|---|
| Store / Landing Page URL | empty | Where affiliate links point. Used to build referral links. |
| Cookie Expiry (days) | 30 | How long a visitor's browser remembers the click. |
| Attribution Window (days) | 30 | How long after a click a sale can earn commission. |
| Default Currency | USD | Currency used for display and totals. |
| CORS Allowed Origins | * | Which sites may call the click endpoint. |
| Program Name | empty | Label shown on conversions in the portal, for example "Acme sale". |
| Minimum Payout Threshold | 0 | Smallest balance to pay out. |
| Affiliate Signup | On | Enables the public /signup page. |
| Require manual approval | On | New sign-ups wait as pending. |
| Default Commission Type / Rate | percent / 20 | Applied to new affiliates. |
| Polar Webhook Secret | empty | Verifies Polar webhooks. |
| Stripe Signing Secret | empty | Verifies Stripe webhooks. |
| API Key | generated | Protects the custom checkout endpoint. |
| Email provider and keys | Off | See the Email section. |
| Master Password | from ADMIN_PASSWORD | Admin login. Changing it signs out all sessions. |
Endpoints
| Method and path | Used by | Auth |
|---|---|---|
POST /click | tracker.js | None (public). Allowed origins are set in Settings. |
POST /webhooks/polar | Polar.sh | Signature (Standard Webhooks) |
POST /webhooks/stripe | Stripe | Signature (Stripe-Signature) |
POST /webhooks/generic | Your server | API key header |
GET /portal?token=… | Affiliates | Private token |
GET /signup | Applicants | None |
/admin/* | You | Password session |
POST /click
{ "ref": "MAYA25", "landing_url": "https://yourstore.com/?via=MAYA25", "referrer": null }
Returns { "click_uid": "…", "cookie_days": 30 }. An unknown or inactive code returns an error and no cookie is set.
Database
Refreal stores everything in your D1 database. Five tables are created automatically.
| Table | Holds |
|---|---|
settings | Key and value pairs for every setting. |
affiliates | Name, email, referral code, portal token, commission, status, payout method and details. |
clicks | Click ID, affiliate, landing page, referrer, a hashed IP and the user agent. |
conversions | Source, order ID, amount, commission, status, the raw provider payload. |
payouts | Amount, method, status and note for each payout. |
You can browse the data in the Cloudflare dashboard under D1 → your database → Console. To back up, use Export in the D1 page or wrangler d1 export.
IP addresses are stored only as a hash.
Security
- Signed webhooks. Once a Polar or Stripe secret is saved, requests without a valid signature are rejected. The custom endpoint requires its API key.
- Admin sessions. The session cookie is signed and tied to your password, so changing the password ends all existing sessions.
- Passwords. Stored as PBKDF2-SHA256 hashes, never in plain text.
- CSRF protection on every admin and portal form.
- Escaping. All page output is HTML-escaped automatically.
- CSV exports neutralise spreadsheet formulas.
- Portal links are long random tokens. Regenerate one if it leaks.
Recommended
- Change the password right after the first login.
- Save the Polar and Stripe secrets before going live.
- Set CORS Allowed Origins to your store's address.
- Use a custom domain you control for the tracker and webhooks.
- Optionally put
/adminbehind Cloudflare Access for a second login.
Updating
Because your data lives in D1 and not in the code, updating is replacing the code:
- Download the new version and copy its files over your repository, keeping your Git history.
- Commit and push. Cloudflare Pages deploys automatically.
Refreal adds new tables and default settings by itself and never overwrites your saved settings. Back up the database from the D1 page before a major update.
Troubleshooting
The pages have no styling
The Build output directory is not set to public. Fix it under Settings → Builds and redeploy.
"Refreal is not set up yet: the D1 database binding named DB is missing"
The D1 binding is absent or has the wrong variable name. Add a D1 binding named exactly DB, then redeploy.
I can't log in
Confirm the ADMIN_PASSWORD secret exists for the Production environment and that you redeployed after adding it. If you already changed the password in Settings, that new password is the one to use.
Clicks are not being recorded
- Check that the tracker tag has
data-refreal-endpointpointing at your Refreal address. - Open the browser console and look for CORS errors. Set CORS Allowed Origins to your store's address or
*. - Check that the code in
?via=belongs to an active affiliate.
A sale shows as unattributed
The order did not carry a click ID. Check that your checkout link is one the tracker recognises, that the visitor came through a tracked link first, and that the click happened in the same browser. For other checkouts, add data-refreal-checkout to the link.
A sale shows as expired unattributed
The click was older than the attribution window. Raise the window in Settings, or on that affiliate.
Webhook returns 401 or "invalid signature"
The saved secret does not match the one in Polar or Stripe. Copy it again with no spaces. Remember that Stripe test and live mode use different secrets.
Test email fails
The provider's own error is shown. The usual causes are an unverified sending domain, a From Address on another domain, or a key for the wrong Mailgun region.
Changes to settings or variables don't apply
Cloudflare applies new bindings and secrets only to new deployments. Retry the latest deployment.