LaunchX GitHub
New v1.10.0: offsite backups and a restore button

Build the core.
We handle the rest.

LaunchX is a complete SaaS starter in plain PHP. No framework, no packages, no build step. Sign-in, payments, invoices, a store, affiliates, an app people install with free push notifications, an admin panel and an API are done and tested, so every hour you spend goes into what makes your product yours.

MIT licencePHP 8.1+MySQL 8 or MariaDB 10.4+Runs on shared hosting
6.8msTo build the home page
on the server (median)
2MBMemory for
a typical page
0Packages to update,
audit or lose
959End-to-end tests
before every release
01 Complete

Every SaaS needs the same checklist. Ours is already go.

The parts every product needs and nobody wants to build twice: written, wired together and tested end to end. You start at the last line.

Pre-flight checklistAll systems go
  1. T−12Sign-in, passkeys, SSO, two-stepSTBYGO
  2. T−11Bot protection, rate limits, CSRFSTBYGO
  3. T−10Plans, limits, team seats, free trialsSTBYGO
  4. T−09Stripe, Bayarcash, any provider in one fileSTBYGO
  5. T−08Invoices and tax by countrySTBYGO
  6. T−07Every currency, every languageSTBYGO
  7. T−06A store with guest checkoutSTBYGO
  8. T−05Affiliates, discount codes, sales campaignsSTBYGO
  9. T−04Install as an app, free push, email broadcastsSTBYGO
  10. T−03SEO, pixels, server-side events, trafficSTBYGO
  11. T−02Admin, tickets, backups, activity logSTBYGO
  12. T−01REST API and signed webhooksSTBYGO
  13. T−00Your productYOURS

Wired together

A payment grants access, issues the invoice, credits the affiliate and fires the webhook, whichever payment method took the money.

Tested like a browser

959 end-to-end checks sign up, pay, refund, sign in through SSO and click through the admin panel before every release.

Made for the whole world

Any currency, tax by country, phone numbers from any country, each member's own language and time zone, and every screen readable in light and dark.

Happy on cheap hosting

PHP 8.1 and MySQL or MariaDB are all it needs. It even keeps working where the host turns off exec or has no mysqldump.

02 Who it's for

What will you launch?

One foundation, many kinds of products. Pick who you are and see what's already done for you, and the one part that's left.

Solo founder

An AI writing tool with monthly plans

You have the idea and the evenings. You don't have three months for sign-up forms, billing edge cases and an admin panel.

You build

The editor, and the AI behind it.

LaunchX handles

  • Sign-up with Google, or email and a code
  • Plans with a free trial, no card needed
  • Stripe subscriptions, with a grace period when a card fails
  • A launch-week discount code, and an invoice for every payment
  • An affiliate program, so users bring users
  • An app they install from the browser, and free push to bring them back
Sign-inPlansFree trialsStripeInvoicesAffiliatesPush
03 Grow for free

Your app on their phone. Your news on their lock screen.

LaunchX installs like an app, straight from the browser: no app store, no review queue, no store fee. Then every sale, new feature or announcement goes to your members' phones as a push notification. It doesn't wait in a crowded inbox or a spam folder: it lights up the lock screen, and sending it costs nothing. The same message can go by email too, to exactly the members you pick.

Admin › BroadcastTry it
Send to

A tap opens /subscription?code=FLASH40, with the discount already applied.

$0per push you send: Firebase Cloud Messaging doesn't charge for messages
0app stores: no review, no store fee, and every update is live the moment you deploy
4ways to narrow it down: plan, language, country and last visit
3places it lands: the lock screen, the inbox inside your app, and their email

Push reaches members who allow notifications; the in-app inbox reaches everyone you sent to; email reaches everyone who hasn't unsubscribed. On iPhone and iPad, push works once the app is on the home screen (iOS 16.4 or newer).

Broadcasts · try it

Bring quiet members back with one message.

Write it once and it goes to their inbox, their lock screen and their email. Pick who gets it: free members who haven't been back in a month, everyone in Malaysia, your Pro customers. You see how many it reaches before you press Send.

  • Win back the quiet ones. "Away for 30 days" finds the members who drifted off, so your "here's what you missed" reaches them, not the people who came by this morning.
  • Email that feels written for them. Their first name and their own language, sent from your own mail server, at a pace your provider accepts.
  • One-click unsubscribe, built in. Every email has the link and the unsubscribe button Gmail and Yahoo ask bulk senders for. Receipts and password resets still reach everyone.
  • Know before you send. The count changes as you pick, and a test lands in your own inbox first. Or send it from your code with one API call.
Broadcast
Narrow it down
Send it by
Reaches 1,330 members1,250 by email · 612 with push
From YourApp · to AishaWe miss you: here's what's new

Hi Aisha,

Since your last visit: team plans, invoices in your currency and two-step sign-in. Come and have a look.

Open You're getting this because you have an account at YourApp.

A sample audience of 5,000 members. Pick who gets it, then send.

Languages · try it

Speak your customer's language.

Every member page, the store, checkout and the emails come in each customer's own language, so a market that doesn't read English can still sign up, pay and stay. English and Bahasa Melayu are built in. Another language is one file.

  • Each member picks theirs. From the globe menu or their profile. It's kept on their account, so it follows them to every device.
  • Ads that land in the right language. ?lang=ms on any link opens the site in Malay, and a first visit gets the language the browser asks for.
  • The emails follow. Each email has a copy in each language, with the dates written their way: 3 Dis 2026.
YourApp
  • Dashboard
  • Subscription
  • Team
  • Support

Good morning, Aisha

Your planProRenews on 3 Dec 2026Manage plan
EmailYour free trial ends in 3 days

Another language? Copy lang/ms.php to lang/fr.php and translate its lines, like 'Your plan' => 'Votre forfait',

A growth engine that's already built.

Every step from stranger to promoter has a tool in LaunchX, and none of them needs a marketing platform you pay for each month.

Stranger to visitor

They find you

  • Search and sharing tags for the site and every sales page: a title, a description and a 1200×630 image
  • Affiliate links your members share, like yourapp.com/?i=aisha
  • A sign-up link per country: /register/my gives that member ringgit prices
  • In their language: add ?lang=ms to an ad and the site opens in Malay
  • Pixels on the home page for Meta and TikTok ads that reach new people
Visitor to member

They sign up

  • One tap with Google, Apple, Microsoft, GitHub or Facebook, or an email with a code
  • A free trial with no card, once per member
  • A home page that's ready, showing your real plans and prices
  • Pixels for members that match ad clicks to sign-ups with a hashed email
Member to customer

They buy

  • Discount links: send ?code=SAVE20 and every plan shows the lower price
  • Sales campaigns with a start, an end and a SALE badge on each plan
  • An announcement bar and a promo pop-up on the member dashboard
  • Purchase events sent from your server, so ad platforms count the sale even when a browser blocks the pixel
Customer to regular

They stay

  • Push and the in-app inbox for news, features and offers
  • Emails before a trial or a plan ends, and when a card fails
  • A grace period while Stripe tries the card again
  • The Explore page, pointing members to your other products
Regular to promoter

They bring friends

  • Commission for as long as each customer they referred keeps paying
  • A higher rate on a paid plan: 30% instead of 10%, by default
  • Payouts drawn up each month, with their bank, PayPal, Wise or crypto details
  • Rankings for this month and all time
04 Earn

Every way to get paid, and to keep getting paid.

Sell plans, access by the day or one-off products, in each customer's own currency, through the payment methods they already trust. And when a card fails, LaunchX works to keep the customer instead of cutting them off.

Pay by the day · try it
90days−15%
$38.25$45.00$0.42 a day
Price per day, by days bought
3+$0.50 30+$0.45 90+$0.42 180+$0.40 365+$0.35

Members pick anything from 3 to 365 days, and longer means cheaper. These are example prices: you set the daily price and each discount, a campaign's bigger discounts switch on and off by date, and the server works the total out again before charging.

Prices per currency

Pro, 30 days

  • United States$12.00
  • Europe€11.00
  • United Kingdom£9.50
  • India₹999.00
  • AustraliaA$18.00
  • MalaysiaRM49.00
  • Japan¥1,800
  • KuwaitKD 3.700

You set every price, so none is a rough conversion. A member's currency comes from the sign-up link they used, and yen or dinars charge correctly through Stripe.

Team plans · try it

Sell to the whole team, not one seat at a time.

Give any plan seats. The buyer invites colleagues by email, and each one gets the same access with their own sign-in, on one bill. Every person invited signs up to your app, brought in by a customer who already pays.

  • One renewal keeps everyone in. Access follows the owner's plan, so a renewal, a refund or an upgrade reaches the whole team at once.
  • Downgrades without drama. With fewer seats, the last to join waits for a seat. Nobody's account is touched.
  • Invites only the right person can use. The link works for 14 days, for the invited email only, and is stored as a hash.
Lindqvist Studio
3 of 5 seats in use, the owner's included
  • MMaya Lindqvistmaya@studio.exampleOWNER
  • TTheo Parktheo@studio.exampleACCESS
  • PPriya Nairpriya@studio.exampleACCESS

Invite someone: they join with their own account.

Plan limits · try it

Let the limit sell the upgrade.

Give each plan its numbers: 20 exports a month on Free and 300 on Pro, 10 projects, a custom domain. Members watch their meters, plan cards list what each plan includes, and the moment someone needs more, they see the plan that has it.

  • Upgrades at the moment of need. At the limit, members get a page that offers your plans instead of an error, right when they want more.
  • One line in your code. usage_try('exports') checks and counts in one step, so two clicks can't both take the last one.
  • Cards that match the rules. Plan cards, the Usage page and the checks all read the same grid, so you change a number once.
  • One heads-up, not a flood. Reaching a limit sends the member one email and your server one webhook. API requests and support tickets are counted for you.
Usage
  • Exports18 of 20 used this month90%
  • Projects1 of 1 used100%
  • Custom domainNot in your plan

Export a report: each one counts toward this month's 20.

Changing plans · try it

Upgrades that feel fair, so members say yes sooner.

Members move to any plan whenever they like, up or down, and the days they already paid for come off the new price, counted to the second. Nobody waits for a plan to run out before buying a bigger one, and nobody pays twice for the same days.

  • Upgrade today, not at renewal. They pay only the difference, and the new plan starts now for its full length. Every plan card shows the real price before they click, with the sum one tap away.
  • Downgrades with no refunds to send. When the unused days cover a cheaper plan, the switch is free and they get the extra days instead. No money goes back out, and nothing they paid is lost.
  • Stripe subscriptions too. Plans that renew with Stripe switch through Stripe, with the charge shown first, asked from Stripe itself. A declined card changes nothing.
  • A credit nobody can game. Trial days, gifted days and what a discount code paid for are worth nothing, so a credit is never more than was paid. The invoice shows it as its own line.
Maya's plan: Team
Day 12: 18 days left
Move to
Business for 30 days
$99.00
Unused days of Team18 days left
−$35.40
Today
$63.60

Business starts today and runs for 30 days.

Slide through the month and pick a plan: the price follows the days left. Example prices.

Failed renewals

A failed card doesn't have to be a lost customer.

For Stripe subscriptions, LaunchX keeps the member in while Stripe tries the card again, and tells them how to fix it.

  1. Day 0The renewal failsThey keep access for a grace period, 7 days by default, and get an email with a link to pay.
  2. Days 0 to 7Stripe tries againTheir plan page says the payment didn't go through, with an Update payment button.
  3. Day 4A reminderA second email, about three days before the grace period ends.
  4. PaidBack on trackThe new period starts from the day they'd paid up to: no days lost, none given away.
Plans your wayFixed plans with their own feature lists, or pay by the day. A lasting discount on each plan, and a bigger one while a campaign runs.
Free trials, no cardOnce per member. An email comes about three days before it ends, and paying adds the plan's days after the trial.
Discount codes and linksA percentage, or an amount in each currency. Limit the uses, the dates, or first purchases only, and share it as a link.
A store, no account neededSales pages with offers and quantities. Buyers check out as guests and get their download link or message the moment they pay.
Paid the way they likeStripe for cards and wallets, once or on repeat. Bayarcash for FPX, DuitNow QR, Touch 'n Go, GrabPay, ShopeePay and Boost. Any other provider is one file.
Invoices and tax by countryA numbered invoice and PDF for every payment. VAT, GST or SST by country, and reverse charge for businesses abroad.
Refunds, handledWhen Stripe reports a refund or a chargeback, access ends, the invoice is marked and the code's use comes back. On recurring plans, so does the unpaid commission.
What each customer is worthEvery payment adds to a member's lifetime value and every refund takes it off, ready in the users download.
05 Run

Mission control for the whole business.

Who's visiting, who's paying, what changed and what needs an answer: it's all in your admin panel. No analytics service, help desk or backup tool to sign up for.

StatisticsRevenue today, this month and all time, a 12-month chart, and one currency at a time so amounts are never mixed.
Traffic, built inHome page visitors by country, language, device, browser, referrer and hour, counted on your own server.
UsersSearch, edit, give days of access, verify an email, or sign in as someone to see exactly what they see.
Activity logWho changed what, with the old and new values. Passwords and keys show only as "changed".
Support ticketsThreaded conversations in one queue, with statuses and the member's profile a click away.
Email, under controlEdit each template with a live preview, send yourself a test, and see every email sent or failed.
Backups you can count onThe database and your files on a schedule, a copy of each sent to S3 or another server, and a restore button. Works even where mysqldump doesn't exist.
Errors and scheduled jobsEvery error with its stack trace, and every run of the hourly job with its result.
Maintenance modeA "back soon" page with a countdown, while you still sign in through a secret address.
Files and databasesA file manager with a trash, and a SQLite explorer, in the browser. Off until you turn them on.
CSV for everythingUsers, payments, payouts, invoices and the activity log, safe to open in Excel.
Affiliate payoutsWho's owed what, who's due a payout, where to send it, and one click to mark it paid.
06 Protect

Locked down before liftoff.

The security work that usually comes last is already done. Bots are stopped at the door, every form is protected, and secrets are kept only as hashes, so there's little worth stealing.

Two-step sign-inAny authenticator app, ten recovery codes, and each code works once. Require it for every admin.
Providers and SSOOnly the ones you turn on. A provider stands in for the password, never for the two-step code.
Bots stopped at sign-upA hidden field, a time trap and, if you want it, Cloudflare Turnstile on sign-up and sign-in.
Rate limitsOn sign-in, passkeys, sign-up, password resets, two-step codes, discount codes and every API key.
Every request checkedA CSRF token on every form, prepared statements for every query, security headers on every page.
Sessions follow the accountChange a password, turn on two-step or remove a passkey, and every other device is signed out at once.
Little worth stealingPasswords, reset links, remember-me tokens, recovery codes and API keys are stored only as hashes.
Uploads checkedImages are checked by what's inside them, not their names, and kept apart from the app's own files.
Their data, their callMembers download everything about them in one file, or delete their account themselves.
Consent where the law asksAds and analytics wait for a yes in the EU, EEA, UK and Switzerland, or everywhere if you choose.
Private by defaultNothing loads from another server until you turn a service on, and pages are never kept offline for the next person on the device.
Signed and scopedWebhooks carry an HMAC signature. API keys are read, write or admin, can expire, and can be revoked.
Passkeys · try it

Sign in with a glance. Nothing to type, nothing to steal.

Members add a passkey once, then sign in with their face, their fingerprint or the PIN that already unlocks their phone. There's no password to forget, reuse or type into a fake page, and it counts as both steps of two-step sign-in.

  • Fewer "forgot password" emails. Nothing to remember means nothing to reset. Passkeys kept in iCloud Keychain, Google Password Manager or a password manager follow members to their next phone.
  • Phishing gets nothing. A passkey only works on the site that made it, so a look-alike page can't ask for it. Your database keeps only public keys, which open nothing.
  • Both steps in one touch. The phone already proves it's them, so members who turned on two-step sign-in skip the code.
  • A lost phone isn't a lost account. Members see each passkey, get an email when one is added and remove one in a click. You can remove them for a member too.
Sign in
yourapp.com/login
Welcome back aisha@example.com

Aisha added a passkey on her phone last week. Press the button to sign in as her.

Offsite backups · try it

Lose the server, keep the business.

Every backup also goes somewhere else the moment it's made: any S3-compatible storage, or another server over SFTP. If this server dies, gets hacked or is deleted by mistake, a new one is running your site again with every member, payment and setting as it was.

  • Copies the storage company can't read. Set a passphrase and each copy is encrypted on your server before it leaves. A copy that was tampered with won't open.
  • A restore button, with an undo. Pick a backup, type RESTORE, and it's back. The database as it was is saved first, and an older backup is brought up to date.
  • The storage you already pay for. Amazon S3, Cloudflare R2, Backblaze B2, Wasabi, DigitalOcean Spaces, MinIO, or a second server or NAS over SFTP. No SDK, no backup service to sign up for.
  • You hear when it fails. Save and test names the exact problem, and the backup.failed webhook tells your monitoring.
Admin › Backups
This server48 backups, hourly
acme-backupsCloudflare R2 · 30 copies
What the storage company can read

It's 14:30 and the last backup was at 14:00. Press the button to lose the server.

LaunchX hasn't had an outside security review yet. Found something? Please report it privately, as SECURITY.md explains.

07 Lightweight and fast

No framework. Nothing to carry.

A request runs the code it needs and stops. No container to boot, no packages to load, nothing fetched from other servers. It's fast on a cheap server because there's so little in the way.

Time to build each page on the server

Median, in milliseconds. Shorter is faster.

Store page5.2 ms
Admin: users6.5 ms
Home6.8 ms
Sign in7.5 ms
Plans7.9 ms
Sign up8.4 ms
Member dashboard8.6 ms
Profile9.6 ms
Admin: every setting37.8 ms
PHP 8.4 with OPcache on a desktop processor, database on the same machine, median of repeated requests. Peak memory is 2 MB a page, 4 MB for the settings page that shows every setting at once.
0scripts, fonts or trackers from other servers, out of the box
0build steps: what's in the folder is what runs
~1 MBto download, all of it code you can read
1front controller every request goes through
08 Modular

Every module has a switch.

Billing, the store, affiliates, the extension, push and maintenance mode: turn each one on or off in the admin panel, with no code to change. Try it.

Admin › Settings

A payment provider is one file.

Write how a payment starts and how it's confirmed. Drop the file in payments/, and it shows up in checkout and in the admin panel with its own settings. No routes, no changes to checkout.

The admin panel even hands you a blueprint to give an AI assistant.

class PaddleGateway extends PaymentGateway
{
    public function id(): string   { return 'paddle'; }
    public function name(): string { return 'Paddle'; }

    // Send the buyer to pay
    public function start(array $payment): array { … }

    // Check with Paddle that it was paid
    public function confirm(array $request): ?array { … }
}
09 AI agent friendly

Made for you, and your coding agent.

AGENTS.md tells an AI agent how a request flows, where every helper lives and the house rules for code, text and design. Point your agent at it, and it changes LaunchX the way a careful person would.

AGENTS.md

Requests

public/index.php loads config, helpers, middleware, models, controllers and services, then dispatch(). A new controller must be required there.

Helpers

auth(), db(), setting(), url(), format_currency(), admin_log(), local_date()… Always prepared statements.

Payments, tax and invoices

Take the discount off before any payment method. Never trust a total from the browser. An invoice is a copy: never change it after it's issued.

Writing for the screen

Sentence case, plain words. 4.5:1 contrast in both themes. Every field has a label; no sideways scrolling at 390 px.

Tests

Run the groups your change touches, and php -l every changed file.

An example sessionillustration
  1. YOUAdd Paddle as a payment method.
  2. READSAGENTS.md and .agents/rules/payment-gateways.md
  3. WRITESpayments/PaddleGateway.php: one file, nothing else changes
  4. CHECKSphp -l, then the payments test group
  5. DONEPaddle shows up in checkout and in the admin panel, with its own settings
A good first prompt

Before you change anything, read AGENTS.md and follow the rules in /.agents/rules/*.md.

Plain PHP it already knowsNo framework conventions to guess, no magic to reverse-engineer. Every line it reads is the line that runs.
Small, clear seamsA provider is one file. A schema change is one numbered migration. A page is one controller method and one template.
A safety net959 end-to-end tests drive the app like a browser, so you can check an agent's work before you ship it.
10 See it

Calm in dark. Clear in light.

Every screen follows the visitor's light or dark setting, works at 390 pixels wide, and keeps text at 4.5:1 contrast or better in both. Switch this page's theme to see the other one.

The LaunchX admin statistics page: sign-ins today, paying users, revenue today, this month and all time, new users, affiliate payouts and a revenue-by-month chart.

The admin's view of the business: sign-ins, paying users, revenue and payouts, with a chart drawn without a chart library.

11 Every feature

All 656 features, in plain words.

17 modules, from the router to the refund webhook. Each card gives the main point; open it for every detail, or search them all at once.

656 features in 17 modules

01Core, routing and public pagesOne front controller, a small router, settings that create themselves and numbered migrations. Read it in an afternoon.Router and front controllerSettings that create themselvesViews and layoutError pages, maintenance mode and error handlingHome page (`GET /`)+4 moreShow all 48Close
Router and front controller8
  • One entry point Every request enters through public/index.php, which loads the watcher, starts the session, and requires config, database, helpers, middleware, core, models, all controllers, and services in a fixed order before dispatching. One entry point means one rewrite rule (try_files) makes the whole app work.
  • get() / post() routes Routes are declared as get($uri, [Controller::class, 'method'], $middleware = []) (and post()), stored in a global $routes array keyed by HTTP method.
  • Pattern-based route params Any {name} segment is compiled to a regex ([^/]+) and captured values are passed positionally to the controller method, for addresses like user/{id} or support/{hash}.
  • Controller-array or closure actions dispatch() supports both [Controller::class, 'method'] and plain closures.
  • Per-route middleware pipeline The 3rd argument is an array of middleware run before the action; entries can be named functions ('authMiddleware') or inline closures (used for roleMiddleware('Admin')).
  • index.php-prefix stripping The router strips a leading index.php/, so the app works on servers without pretty-URL rewriting.
  • 404 fallback Unmatched routes call abort(404) to render the branded not-found page.
  • Address prefix for store pages The route for store pages is registered last, using setting('store_page_prefix', 'p'); a blank prefix serves pages at /{slug}.
Settings that create themselves3
  • setting($key, $default) Reads the settings table once per request and keeps the values in memory.
  • Missing settings are added The first time an unknown key is read, its default is saved with INSERT IGNORE, so a new setting works without a seeder. If the database is read-only or the table is missing, the default is returned.
  • On/off settings Most features have a switch (home_enabled, docs_enabled, billing_enabled, affiliate_enabled, extension_enabled, store_enabled, fcm_enabled, pwa_enabled, maintenance_enabled, announcement_enabled, promo_enabled, campaign_enabled, turnstile_enabled, and more), so the owner turns modules on or off from the admin settings.
Views and layout11
  • view($file, $data) renderer Renders a plain-PHP template from views/, extract()ing $data into local variables (and injecting the view name as $view).
  • url($path) / redirect($url) Build absolute URLs from BASE_URL (passing through already-absolute links) and issue header redirects with exit.
  • Shared master layout views/layout.php is the universal shell: theme bootstrap (instant dark/light via localStorage to avoid flash), shared styles (cards, stats, forms, buttons, badges, tables, alerts, toggles, modals), navbar/sidebar/footer inclusion, flash messages, and SEO/social/tracking injection. Views buffer content with ob_start() and hand it to the layout.
  • Conditional chrome The layout conditionally renders the sidebar (only for authed non-home/non-store views), the footer (only on home/store pages), and a full-canvas body mode that suppresses navbar/footer for full-width pages.
  • Per-page SEO override Store pages can pass a $seo array (title, description, og_image) that overrides global meta for that page.
  • SEO and sharing tags Builds <title>, meta description, canonical URL, full Open Graph (type, url, title, description, site_name, locale, logo, 1200×630 image) and Twitter card tags from settings and the current request.
  • Cache-busted favicon Resolves the favicon path (webp/png fallback), derives MIME type, and appends a filemtime-based version query so browsers refresh the icon when it changes.
  • fb_domain_verification_token($raw) Extracts the bare token whether the admin pastes the raw token or the full <meta> tag, then injects the verification meta site-wide.
  • Navbar partial Sticky top bar with brand name, theme toggle, and context-aware auth buttons (Sign in / Get started for guests — preserving the ?i= affiliate tag — or Dashboard / Sign out for users) plus a mobile menu toggle.
  • Sidebar partial Collapsible navigation. Member links: Dashboard, Notifications (with an unread count), Profile, Subscription (when billing is on), Affiliate (when billing and the affiliate program are on), Support, Extension (when it's on) and Explore more. Admins also get grouped sections (Insights, People, Notifications, System, Store). The current page is highlighted, and an "Install As App" button installs the PWA.
  • Footer partial Public-page footer with dynamic copyright year, app name, links to the privacy policy and the terms, and a "Cookie settings" button unless consent is turned off.
Error pages, maintenance mode and error handling6
  • abort($code) Sets the HTTP status and renders branded error views for 403, 404, 419, and 500 (falling back to a plain Error N), then exits.
  • Error pages 403/404/419/500 pages that follow the theme, with buttons to go to the home page, go back or reload.
  • Global error & exception handlers core.php registers set_error_handler and set_exception_handler that funnel everything into logSystemError(); in debug mode they render full stack traces, otherwise a clean 500. dispatch() also wraps routing in a try/catch that logs Critical errors.
  • Maintenance mode When maintenance_enabled is on, non-admins see a lock screen or are redirected home (signed-in members are signed out). Admins aren't affected. The secret sign-in path (login/{secret}, default admin-access), the two-step sign-in step, sign-out, and Bayarcash's subscription/callback and subscription/webhook stay reachable; other addresses send visitors to the home page, including the Stripe webhook, the store's payment addresses, /pay/{id}/notify and /run-cron. The API (/api/v1) keeps working.
  • Maintenance screen Shows the estimated end and a countdown in the visitor's time zone, from maintenance_until (with a preview/dummy-timer mode for admins).
  • Privacy & Terms pages Public legal pages show the text the admin writes (plain text is escaped; HTML is shown as HTML), with a graceful "being updated" placeholder. Routes GET /privacy-policy, GET /terms-and-conditions.
Home page (GET /)3
  • Home page A hero with buttons, a preview of the app drawn in CSS, three feature cards, prices (only when billing_enabled is on) and a closing call to action, all in the theme from settings.
  • Home toggle If home_enabled isn't 1, the landing page redirects to /login, letting the owner run the platform as a pure app with no public marketing site.
  • Traffic log with visitor countries Every home page visit is logged to traffic_logs (path, IP, user agent, referrer, country, language). It detects bots via user-agent regex, takes the country from Cloudflare's CF-IPCountry header, or (only when ipinfo_token is set) looks it up at IPinfo over HTTPS once per visitor session with a 2-second limit; with neither, no visitor address leaves the server.
Built-in docs (GET /docs)3
  • Docs page A page with its own theme, a grouped sidebar, search across titles and text, the current section highlighted, a back-to-top button, and copy buttons on code blocks.
  • Docs visibility toggle Hidden from the public when docs_enabled isn't 1, but admins can always view it.
  • What it covers Requirements, local setup with OWN DevKit, migrate/seed, a prompt for AI coding agents, putting the site online with Project OWN (Open Web Node), Nginx/aaPanel and URL rewriting, the folders, cron, adding payment methods, every admin settings card, billing and plans, email templates, the store, Explore, the browser extension, users, affiliates, support, statistics, the file manager, backups, the error log and notifications.
Scheduled jobs (cron)3
  • /run-cron One address runs every scheduled job: affiliate payouts (checkAndGeneratePayouts), backups (BackupController::triggerIfDue), plan expiry emails and the subscription.expired webhook (SubscriptionController::checkExpirations; it doesn't take access away), and webhook retries (Webhooks::retryDue). It answers with a JSON status and logs the run. When CRON_SECRET is set in config.php, it needs ?key=… and answers 404 without it. Call it once an hour from cron.
  • Without cron Payouts and backups also run when someone opens the dashboard, and payouts when someone opens the affiliate page, so they still happen without a cron job.
  • logCronActivity() audit trail Writes every cron run/job (status, message/JSON, execution time, IP, user agent, location, job name) to cron_logs, surfaced in the admin Cron Logs dashboard.
Error watcher (watcher.php)5
  • Loaded first Before the database and the session, it catches errors, uncaught exceptions and fatal errors (through register_shutdown_function), including crashes that would leave a blank page.
  • Errors in SQLite watcher_log() writes errors to database/system_errors.sqlite, creating its table when needed, so errors are recorded even when MySQL is down.
  • logSystemError() The app's logging function (falling back to error_log if the watcher is absent); the codebase rule is to always log via this.
  • File-flag Debug Mode A database/debug_mode.on flag toggles full error display + raw stack-trace pages; toggleable from the admin UI.
  • php_function_enabled($fn) Confirms a function both exists and isn't in php.ini disable_functions, preventing fatal crashes on shared hosting (reused by the mailer and backups).
Migrations, seeding and database setup6
  • Versioned migration runner (migrate.php) Applies un-run, alphabetically-sorted migrations from database/migrations/, tracking each in a migrations table with batch numbers (auto-creating the table on first run). The only way to change the schema.
  • Migration rollback php migrate.php rollback reverses the most recent batch via each migration's down() in reverse order.
  • Anonymous-class migration format Each file returns an anonymous class with up($pdo) / down($pdo) methods.
  • Seeder runner (seed.php) Runs every seeder in database/seeders/, each a class with run($pdo), to fill in system data (email templates, settings, plans). No accounts are seeded: create-admin.php makes the first admin.
  • Self-creating database (db()) Returns a cached PDO connection; if the DB doesn't exist (error 1049) it CREATE DATABASEs it with utf8mb4 and reconnects — a fresh install needs no manual DB creation.
  • Dynamic timezone sync On bootstrap, PHP's default timezone is set from app_timezone and the MySQL session timezone is synced to match, so timestamps and charts align.
02Sign-in, accounts and securitySign-up to passkeys and two-step sign-in, Google, GitHub, Microsoft, Apple, Facebook and your customers' own SSO, with bot protection and rate limits.RegistrationEmail verification (code and link)Sign-in, sessions and remember meTwo-step sign-inPasskeys+8 moreShow all 79Close
Registration8
  • Sign-up GET/POST /register asks for name, email, phone and password, then signs the person in or sends them to email verification. The phone is optional by default; signup_phone makes it required or hides it.
  • Region-tagged signup with currency lock-in GET/POST /register/{region} ties the new account's billing currency to a region segment (e.g. /register/en) via currency_for_region(), persisting currency_code, currency_symbol, and currency_position onto the user row at creation so prices show in their currency from then on.
  • Stale-region protection On GET the URL region is always honored; on POST it falls back to $_SESSION['reg_region'], so a validation re-render keeps the correct currency while navigating to plain /register drops a stale region.
  • Phone number A list of every country (shown as, for example, "US +1"), starting at the visitor's Cloudflare country, else default_country (default US), and the number. It's stored in international form by phone_e164().
  • Affiliate referral attribution at signup A referral tag is read from ?i= or the aff_tag cookie into a hidden affiliate_tag field; a match sets the new account's affiliate_id to the referrer.
  • Duplicate email/phone guard Rejects an already-registered email or phone before insert, with distinct messages for each.
  • Password strength minimum Registration, reset, and profile updates enforce an 8-character minimum on the server.
  • Admin toggle to skip email verification With disable_email_verify = 1, new accounts are created already verified and signed straight into the dashboard.
Sign-in, sessions and remember me6
  • Email + password login GET/POST /login verifies credentials with password_verify() against the bcrypt hash and starts a session via loginUser().
  • Last-login tracking loginUser() records last_login_at on every sign-in (powering the "Logins Today" stat), gives the session a new id, and keeps the user row in the session without the password or two-step secrets.
  • Remember-me persistent login Ticking "Remember me" sets a 30-day selector:validator cookie (HttpOnly, SameSite=Lax); the database keeps only a SHA-256 hash of the validator. Changing or resetting the password signs every remembered device out.
  • Secret/token login route GET/POST /login/{secret} accepts a $secret segment (used for the maintenance-mode admin entry path).
  • Messages kept off the address bar Success and error messages travel in the session (flash()), so a link can't make the sign-in page say anything.
  • Logout with cookie cleanup POST /logout (with its form token) clears the session and forgets this device, then redirects to login.
Two-step sign-in7
  • A code from an authenticator app Anyone can turn it on from their profile page: scan the QR code (drawn by LaunchX itself, services/QrCode.php) or type the key, then enter a code to confirm. Standard TOTP (RFC 6238: 6 digits, 30 seconds), so any authenticator app or password manager works.
  • Asked after the password, and after a sign-in provider twofa_begin() sends the person to GET/POST /login/two-step; nothing is signed in until the code is given, within 10 minutes and 5 tries. "Remember me" from the password step is kept.
  • Each code works once The last step used is stored (totp_last_step), so a code seen over someone's shoulder can't be used again.
  • Ten recovery codes Shown once with Copy and Download buttons, kept only as SHA-256 hashes, each usable once. New ones can be made with a code from the app.
  • Turning it on signs out other devices Devices that stayed signed in skipped the new step, so they are signed out.
  • The browser extension asks too POST /api/extension/login answers two_step_required until a code is sent.
  • Admins Admin > Users > Edit shows whether it's on and can turn it off for someone who lost their phone. Admin > Settings > Two-step sign-in can require it for admins: until they turn it on, admin pages send them to their profile and their admin API keys act as write keys.
Passkeys9
  • Sign in with a face, fingerprint or device PIN WebAuthn in plain PHP with openssl (services/Passkeys.php, controllers/PasskeyController.php, public/assets/passkeys.js), no library. Members add passkeys on their profile (the Passkeys card) and sign in with Sign in with a passkey, or right from the email field's autofill where the browser offers it (conditional mediation, autocomplete="username webauthn").
  • Nothing to phish A passkey only signs for the site it was made for, and the site keeps only its public key: no password to leak, guess or type into a fake page.
  • What's checked A one-time challenge from the session (5 minutes to add a passkey, 10 to sign in), the origin and the RP ID (the host of BASE_URL), that someone was there and that the device checked it's them (user verification), the signature (ES256 or RS256), and the counter of keys that keep one: a count that doesn't go up means the key was copied, so it's refused. No attestation is asked for.
  • Both steps at once The device checks the member's face, finger or PIN, so a passkey sign-in skips the two-step code. "Remember me" works with it.
  • Adding one Asks for the password first (once per 15 minutes, 5 tries), unless the account has none. Up to 20 per account. Named after the provider when it's a known one (iCloud Keychain, Google Password Manager, Windows Hello, 1Password, Bitwarden...), else the browser and system ("Chrome on Windows"); members can rename them. The card shows which are synced across devices and which are kept on one, when each was added and last used. The member gets the passkey_added email (with a Malay copy). An admin viewing the site as a member can't add one to their account.
  • Removing one It stops working at once, and other devices signed in are signed out (users.passkeys_reset_at is part of the session stamp); the device that removed it stays signed in.
  • In the database passkeys: the public key as PEM (never a secret), the credential id and its SHA-256 to look it up, the counter, transports, AAGUID and the sync flags. users.passkey_handle is the random id the member's passkeys know them by, never their account number or email.
  • Where they work Browsers only offer passkeys on https with a domain name, or on localhost. On an IP address the button stays hidden and Admin > Settings says why. Passkeys belong to the domain they were made on.
  • Admins Admin > Settings > Two-step sign-in and passkeys turns them off (passkeys_enabled, on by default). Admin > Users > Edit lists a member's passkeys, with Remove passkeys for a lost device: it signs them out everywhere and goes in the activity log.
Sign in with Google, GitHub, Microsoft, Apple, Facebook or your own SSO6
  • Only what the admin picks Admin > Settings > Social and SSO sign-in turns each provider on with its own keys; the sign-in and sign-up pages show buttons only for the ones that are on and filled in.
  • Your own single sign-on Any OpenID Connect provider (Okta, Keycloak, Authentik, Microsoft Entra, Google Workspace...) from its issuer URL, with a button label of your choice. Microsoft can be limited to one tenant.
  • Which account a visitor gets An outside account already connected signs that member in. Otherwise, when the provider vouches for the email address and a member has it, the two are connected (sso_link_by_email; never for admin accounts, which connect providers from their profile). Otherwise a new, already verified account is made, when sign-up through providers is on (sso_signup_enabled).
  • Safe linking If the matching account had never confirmed its email, its password is cleared when the provider proves the address: whoever made it without owning the address can't keep signing in.
  • Connect and disconnect Members connect and disconnect providers from their profile; an account without a password can't disconnect its last provider.
  • Still two steps A provider stands in for the password, not for the authenticator code: two-step sign-in is still asked when it's on.
Password reset4
  • Forgot-password request GET/POST /forgot-password emails a reset link (forgot_password template) that works for 1 hour; the database keeps only a hash of its token. One email per address per 15 minutes.
  • Email-enumeration protection Always returns the same "If an account exists…" message whether or not the email is registered.
  • Time-limited reset link GET/POST /reset-password/{token} only accepts tokens whose reset_expires is still in the future.
  • New-password set with confirmation Requires a matching confirmation (min 8 chars), re-hashes, and nulls out the token/expiry so the link can't be reused.
Bot and abuse protection5
  • Honeypot field The sign-up form has a hidden website_url field; a submission that fills it is blocked with a 403.
  • Time-trap detection register_start_time is recorded on page load; sign-ups sent less than 5 seconds after the page opened are rejected.
  • "Action Blocked" page Detected bots see a 403 page that explains the block, with a retry link.
  • Cloudflare Turnstile CAPTCHA When turnstile_enabled is on (with site + secret keys), login and registration render the Turnstile widget and validate cf-turnstile-response server-side via verify_turnstile(); it fails closed if Cloudflare is unreachable. Keys: turnstile_enabled, turnstile_site_key, turnstile_secret_key.
  • Rate limits Sign-in: 5 failures per email and 30 per IP in 15 minutes. Sign-up: 10 per IP per hour. Forgot password: 10 per IP per 15 minutes. Two-step codes: 10 tries per 15 minutes. Passkey sign-in: 30 failures per IP in 15 minutes.
CSRF and request security6
  • Session CSRF tokens on all forms csrf_field() injects a per-session _csrf token (32 random bytes) into every POST form; verify_csrf() enforces it on all POSTs and renders a 419 page on mismatch.
  • Webhook/API CSRF exemptions verify_csrf() skips machine-to-machine addresses: subscription/callback, subscription/webhook, subscription/stripe-webhook, store/callback, store/webhook, api/extension/login, api/extension/logout and pay/{id}/notify.
  • JSON body merge for POSTs verify_csrf() auto-decodes a JSON request body into $_POST, so AJAX/JSON clients satisfy CSRF and field-reading uniformly.
  • Prepared statements everywhere All queries go through PDO prepared statements (via BaseModel and inline db()->prepare()), guarding against SQL injection.
  • Encoded IDs in addresses hash_id() / decode_id() turn a numeric ID into a short URL-safe code and back (e.g. /user/{hash}). It's an encoding, not a secret: each page still checks that the visitor may see the record.
  • Security headers Every page sends nosniff, X-Frame-Options: SAMEORIGIN, a Content-Security-Policy, a Referrer-Policy and a Permissions-Policy, plus HSTS over HTTPS.
Roles, access control and middleware4
  • Auth gate middleware authMiddleware() redirects unauthenticated visitors to /login; applied to nearly every dashboard, account and admin route. The API uses keys or tokens instead.
  • Role-based middleware roleMiddleware($roles) returns a 403 unless the user's role is allowed; admin routes wrap it as roleMiddleware('Admin').
  • Role & entitlement helpers hasRole($roles) checks roles; isPro() and hasExtension() gate pro features by expires_at/extension flag; when billing_enabled is off, any logged-in user is treated as pro.
  • Current-user accessor auth() returns the logged-in user array (or null) from the session.
Profile, account and payout details12
  • Profile page GET /user/{id} (only for the owner or an admin; anyone else gets a 404) shows a hero card with avatar initial, name, email, join date, and inviter (affiliate) name when present.
  • Self/admin profile editing POST /user/{id} lets a user (or any Admin) update name, phone, and optionally password; the editable form only renders for the owner or an Admin.
  • Email is read-only Shown as a disabled field; the update handler never changes it, keeping the verified identity stable.
  • Phone uniqueness on update Rejects a phone already registered to a different user.
  • Optional password change Blank keeps the current password; a new one needs at least 8 characters. Changing your own needs the current password (5 tries per 15 minutes); an account without a password can set one.
  • Multi-method payout details capture The Payout Details card (shown when billing_enabled and affiliate_enabled are both on) stores affiliate-payout info across Local Bank, International Bank (SWIFT/BIC + country), and E-Wallet/Crypto. Fields: payout_method, bank_name, bank_account_number, bank_account_holder, bank_country, bank_swift_code, paypal_email, wise_email, crypto_wallet_address, crypto_network.
  • Dynamic payout form togglePayoutFields() JS shows/hides the relevant inputs based on the selected method.
  • Your data: download it The "Your data" card on your own profile has Download your data (POST /user/data/download): one JSON file with the account, payout details, connected sign-ins, payments, store orders, support tickets, messages sent to you, API keys, passkeys (names and dates) and affiliate commissions and payouts. Secrets are left out (password and token hashes, the two-step key, recovery codes), and so are other people: members you referred are only counted. Up to 10 downloads an hour.
  • Your data: delete the account In the same card, Delete your account (POST /user/delete) asks for the email address typed out, the password (when the account has one; members who only use a sign-in provider have none) and a code from the authenticator app when two-step sign-in is on. It deletes as Admin › Users does, signs out every device and sends the user.deleted webhook. The only admin can't delete their own account, and an admin viewing the site as a member can't delete that member here. 5 tries per 15 minutes.
  • Account currency on the user record Each account carries its own currency (set at registration by region), which current_currency() uses to render prices in the logged-in user's currency.
  • Language Members pick the language of their pages and emails (shown when the site offers more than one); see §17.
  • Time zone Dates and times are shown in each member's time zone (local_date()). While the profile's Time zone is Automatic, the browser reports its zone (POST /user/timezone, kept as auto:Zone in users.timezone) and it follows the member to another country; a zone chosen on the profile stays. An admin signed in as a member never passes on their own zone. Members with none yet see the site's time zone.
Push notification tokens2
  • Save FCM push token POST /fcm/save-token upserts the device's FCM token into push_tokens (the page sends its form token in the JSON body), reassigning ownership if a different user logs in on the same device. Returns JSON.
  • Delete FCM push token POST /fcm/delete-token removes a specific token or all of the user's tokens when none is specified. Returns JSON.
Sign-in internals4
  • Session helpers loginUser() / logoutUser() centralize session establishment/teardown (the latter clears any impersonation marker original_admin_id).
  • Sessions follow the account On every page, auth_sync() reads the signed-in user again by id (one lookup): an account deleted since is signed out; so is a session opened before the password or two-step sign-in was changed, or a passkey removed, on another device (the session keeps a hash of them, auth_stamp); a new role, name or plan applies at once. The device that made a change stays signed in (auth_restamp()). The session copy never holds the password hash or the two-step secrets (session_user()).
  • Admin impersonation primitives impersonateUser(), stopImpersonating(), isImpersonating() let an Admin "log in as" another user while preserving the original admin ID for a clean switch-back (and powering a site-wide impersonation banner).
  • Lightweight active-record base BaseModel gives User find($id), where($col,$op,$val), create($data), and all() over PDO.
03Subscriptions, plans and payment methodsFixed plans or pay by the day, plan changes that credit the days left, limits per plan with usage meters, team plans with seats, discount codes, free trials, a grace period for failed renewals, Stripe, Bayarcash, and any provider as one file.Billing switch and pricing modelsFixed plans (admin)Plan discounts (normal and campaign)Discount codesFree trials+11 moreShow all 109Close
Billing switch and pricing models4
  • Billing switch Every subscription, checkout, sync, redeem, plan-management, and expiry routine first checks billing_enabled (on by default in code, but a fresh install is seeded with it off). When it's off, users go to the dashboard and admins to settings, nothing can be bought, and every signed-in user has full access.
  • Two pricing models Runs in flexible mode (a daily-rate slider) or fixed mode (admin-defined packages), switched by pricing_model, each with its own plans page.
  • Flexible daily pricing slider Users pick 3–365 days on a slider (or type an exact number); the total is days × daily_price computed live in JS and re-validated server-side.
  • Tiered duration discounts Flexible pricing applies percentage discounts by band (30–89, 90–179, 180–364, 365+) from discount_30_89/_90_179/_180_364/_365, gated by discount_enabled, shown as "-X%" bubbles on the slider.
Fixed plans (admin)4
  • Plans list dashboard GET /admin/plans shows all packages with name, ID, computed (discounted) price, struck-through original, duration, active/inactive status, and a "Recurring, Stripe payment link" badge for payment-link plans.
  • Create / Edit / Delete plan GET/POST /admin/plans/create, /edit/{id}, and POST /admin/plans/delete/{id} manage name, per-currency pricing, duration days, feature list, active toggle, discounts, and optional Stripe recurring config. Inactive plans hide from buyers while preserved for existing users.
  • Per-currency plan pricing Each plan stores an explicit price per enabled currency as JSON (prices[USD]=12, prices[MYR]=50, …); the legacy amount column stays synced to the default currency and is the fallback for any blank currency. The grid auto-populates from the Settings region currency map, marking the default currency required.
  • Per-plan feature bullets A newline-separated features textarea renders as the plan's bullet list.
Plan discounts (normal and campaign)5
  • Standard discount per plan normal_discount_type (percentage/amount) + value produces a permanent slashed price and a real checkout reduction.
  • Sales Campaign override per plan campaign_discount_type/campaign_discount_value overrides the normal discount whenever a master Sales Campaign is live, showing a red "SALE X% OFF" badge.
  • Time-boxed master campaign Campaign discounts activate only when campaign_enabled=1 and the current time is between campaign_start and campaign_end (isCampaignActive()).
  • Campaign-specific flexible bands When a campaign is live, the slider's discount bands switch to campaign_discount_30_89/…_90_179/…_180_364/…_365.
  • Server-side discount enforcement checkout() independently recalculates normal-then-campaign discounts from the plan's base price, so the charged amount can't be tampered with.
Discount codes9
  • Made by the admin Admin › Insights › Discount codes (GET /admin/coupons, /admin/coupons/new, /admin/coupons/{id}): a code (letters, digits, - and _, kept in capitals), a note only admins see, and a percentage (0.01–100) or an amount in each enabled currency. "Make one up" suggests a code without look-alike characters. Every change is in the activity log.
  • Where it works For plans, the store, or both (applies_to), and only some plans or products if any are ticked. A start and an end, typed in the admin's time zone.
  • Limits Uses in all (max_uses), uses per person (max_per_user, by account or by email), and "first purchase only" (no paid plan before, or in the store no paid order before).
  • On the plan page "Have a discount code?" shows while a code could be used. The code is kept in the member's session, every plan shows its price with it, and checkout checks it again for the plan, the currency and the member before charging. A link to /subscription?code=SAVE20 puts it in.
  • In the store The checkout box has a code field. POST /store/coupon answers with the new lines and total before paying, and a link with ?code=SAVE20 on any product or page fills it in. The code comes off before tax and the payment fee.
  • Every payment method The discount is taken off the amount LaunchX charges, so Stripe, Bayarcash and every method in payments/ charge the lower price. A code that takes off the whole price completes the order at once (gateway coupon), with no payment page.
  • Counted when paid A use is recorded in coupon_redemptions once the order is paid (once per order, however often the payment service reports it), and given back when Stripe refunds the payment. The code's page lists the 25 latest orders that used it. Orders keep the code and the amount it took off (coupon_code, discount_amount) even after the code is deleted.
  • Stripe payment links For a plan billed through a Stripe payment link, Stripe takes the payment, so make the same code in Stripe as a promotion code, turn on Allow promotion codes on the link, and tick "Also on Stripe subscription links": LaunchX passes it as prefilled_promo_code.
  • Guessing Ten wrong codes in ten minutes from one address, and that address can't try more for a while (plans and store together).
Free trials5
  • Days per plan Each fixed plan has a "Free trial (days)" field (trial_days, 0 for none); pay as you go has one in Settings › Pricing (trial_days).
  • Who can start one A signed-in member whose email is verified (unless verification is turned off), with no current access and no paid, refunded or disputed payment before. Once per member (users.trial_used_at, set in one atomic update, so two clicks can't start two).
  • What it does POST /subscription/trial gives the plan's access for the trial days with no card, and records a payment with status trial and an amount of 0 (order number TRIAL-…). It sends the trial.started webhook.
  • On the plan page Plans with a trial say "Free for the first N days" and offer Start a N-day free trial first, with paying as the second choice. During the trial the status card says so and when it ends. Paying for the same plan adds its days after the trial's; another plan ends the trial and starts at once, without the "no refunds" warning.
  • Before it ends The cron job emails trial_ending about three days before.
One-time checkout6
  • Unified checkout dispatcher A single checkout() action (POST /subscription/checkout) handles flexible and fixed plan purchases, saves a pending order, then sends the buyer to the chosen payment method.
  • Choosing a payment method The buyer picks from the methods that are turned on and can charge their currency: Stripe, Bayarcash, or any added in payments/. With only one, it's chosen for them; with none, the page says payments aren't set up yet.
  • Human-readable order numbers Every purchase mints TX-{6 random digits}-{yymmdd} as the cross-system transaction key.
  • Per-currency charge resolution Fixed-plan charges use the user's tied currency and that currency's explicit price; flexible plans stay in the global currency. Sessions predating multi-currency are backfilled from the DB.
  • Currency check A method that can't charge the order's currency is refused before any order is saved ("Bayarcash can't take payments in USD. Please choose another payment method."). Bayarcash takes MYR only, so it isn't offered for other currencies.
  • Changing plans A member with paid time left can move to any other plan, and the unused days come off its price (see Changing plans). During a free trial nothing was paid, so a plan bought then starts when the trial ends.
Changing plans (unused days taken off)11
  • Credit for unused days PlanChange::credit() works out what the days left on the member's plan are worth. Each payment for that plan, newest first, is worth what was paid for it (without the tax when tax is added; with any credit it used), spread over its days and counted to the second, the way Stripe prorates. Payments for another plan or in another currency, free trials, days an admin gave and what a discount code paid for count for nothing, so a credit is never more than was paid. It's rounded down to the cent. In a grace period, only the days up to grace_from count.
  • The price before paying On the plan page, each other plan shows what moving to it costs today ("With your unused days: $23.27 today") and a How it's worked out table: the plan for its days, a discount code, the unused days of the current plan with how many are left, the tax and the total.
  • Paying the difference PlanChange::quote() takes a discount code off first, then the credit, and the tax is worked out on what's left. Checkout saves the credit with the payment (subscriptions.credit_amount, credit_note) and the switch in meta. Once paid, the new plan starts that day for its full length, and its end date is kept on the payment (subscriptions.expires_at).
  • Free switches When the credit covers the new price, no payment method is needed (gateway credit): the member confirms in a window and gets as many whole days of the new plan as the credit buys (36,500 at most). A discount code typed isn't used, so it stays for later.
  • Unpaid days kept Days left that weren't paid for (given by an admin) are added on top of the new plan.
  • No double change If the member's plan or end date changed between checkout and payment (another payment, a renewal, an admin), the new days are added on top instead of replacing, and a warning is logged.
  • Team seats When the new plan has fewer seats than the people on the team, its card says how many would lose their seat (the ones who joined last, until a seat is free), from PlanChange::seatsLost().
  • Invoices, history and API The invoice shows the unused days as a line taken off ("Unused days of Pro"), the billing history says "$6.73 of unused days taken off", and the API's payments and invoices carry credit (amount, from_plan).
  • Activity log and webhook Each change writes "changed the plan of" to the activity log (by the member or by Stripe) and sends the plan.changed webhook with from, to, credit, paid, access_until and via (checkout or stripe).
  • Stripe subscriptions A member whose plan renews by itself with Stripe switches through Stripe's API. GET /subscription/change/preview?plan_id= asks Stripe what it will charge (/v1/invoices/create_preview) for the window that asks first; POST /subscription/change moves the subscription's item to the new plan's stripe_price_id with proration_behavior=always_invoice and payment_behavior=pending_if_incomplete, at the preview's proration date. Stripe charges the difference for the rest of the period, less the unused part, and renews at the new price. A declined card changes nothing, and the member gets Stripe's invoice link to pay. A plan with no Stripe price ID can't be reached this way: the member is asked to turn off renewal in Manage billing first. Rate limited per member (30 previews in 10 minutes, 10 changes an hour).
  • Stripe events after a switch invoice.paid with billing reason subscription_update records the charge (no days added, the credit taken from Stripe's proration lines); a switch that charged nothing only moves the plan. Renewals take the plan from the price on the invoice line, and customer.subscription.updated follows a plan changed in Stripe's billing portal. Stripe's older invoice shape and the 2025 one are both read.
Stripe (one-time and recurring)19
  • Stripe Checkout Session creation StripeService::createCheckoutSession() builds a hosted one-time checkout with the order number as client_reference_id, prefilled email, and zero-decimal-aware amounts.
  • Sandbox/live key switching Automatically uses test or live secret/webhook keys based on stripe_sandbox.
  • Configurable payment methods Allowed methods (e.g. card,fpx) come from stripe_methods and are passed as payment_method_types.
  • Success landing + verification stripeSuccess() calls the Stripe API to confirm payment_status === paid before granting access (not trusting the redirect).
  • Webhook with signature verification stripeWebhook() HMAC-verifies the Stripe-Signature header before processing, returning 400 on bad signatures and 500 (for retry) on transient errors.
  • Event routing Handles checkout.session.completed (one-time subs, Store ORD- orders, recurring Payment Links), invoice.paid (renewals, and plan changes made through Stripe), invoice.payment_failed (the grace period), customer.subscription.updated and customer.subscription.deleted (cancelled, resumed, ended or moved to another price in Stripe), and charge.refunded/charge.dispute.created (reversals).
  • Recurring Stripe Payment Links A plan can carry a payment_link_url; its Subscribe button sends users to Stripe-hosted recurring checkout with prefilled email and a client_reference_id of {userId}:{planId}; Stripe handles billing and renewals.
  • Price-authoritative plan resolution Recurring grants resolve the plan from the Stripe Price ID actually paid (stripe_price_id), so a forged reference or a coupon can't change the plan; the price seen on the first payment is then bound to the plan.
  • Payer-email anti-fraud A recurring payment is only granted if the Stripe-verified paying email matches the claimed account's email.
  • 10% floor Before a price is bound, the fallback claimed plan is only honored if the amount paid is ≥10% of plan price (skipped when Stripe reports a genuine discount).
  • Renewal invoice handling handleStripeInvoicePaid() skips the first subscription_create invoice and extends access on each subsequent renewal; a subscription_update invoice (a plan change) records the charge without adding days.
  • Idempotent recurring grant grantStripeRecurringAccess() wraps the dedup-marker INSERT and entitlement UPDATE in one transaction keyed on a UNIQUE stripe_invoice_id/order_number; a duplicate webhook trips error 1062 and is treated as already-processed.
  • Race-free expiry extension Renewals extend expires_at atomically via DATE_ADD(GREATEST(COALESCE(expires_at,NOW()),NOW()), …).
  • Missing duration A recurring plan with no duration_days defaults to 30 days and logs a warning.
  • Manual "Check my payment" fallback POST /subscription/recheck re-syncs directly from Stripe if a webhook was missed (with a 30-second per-session cooldown), granting through the same idempotent path.
  • Manage billing A member who paid with Stripe gets a Manage billing button (plan page and dashboard): POST /subscription/billing makes a Stripe billing portal session for their own Stripe customer and sends them there (their card, invoices, cancelling a renewal), then back to the plan page. Turn the portal on once in Stripe (Settings › Billing › Customer portal). Without a Stripe customer, the button opens the link in stripe_portal_url instead, if one is set (https only).
  • Refunds and chargebacks (Stripe) On charge.refunded (full refunds only) or charge.dispute.created, the payment is found by its invoice (recurring plans) or by its payment intent (paid once, kept as stripe_payment_intent). For a plan, access days are taken off, customer value is lowered (never below 0), the payment is marked refunded or disputed, unpaid affiliate commission is taken back and a discount code's use is given back (payment.refunded). For a store order, it is marked refunded or disputed, its code's use given back, and order.refunded is sent. Refunds made through Bayarcash or an added payment method aren't followed.
  • Stripe campaign promo codes A plan's stripe_promo_code is auto-appended to the Payment Link as prefilled_promo_code during a live campaign, with a "PROMO AT CHECKOUT" badge.
  • Recurring tracking A per-plan recurring_tracking switch: only on plans with it on do recurring payments (first and renewals) send the server-side purchase events and credit affiliate commission.
Failed renewals and the grace period (Stripe subscriptions)7
  • A grace period On the first invoice.payment_failed of a period, the member keeps access for billing_grace_days more days (7 by default, 0–60, Settings › Pricing) while Stripe tries again. The date their paid access really ended is kept in users.grace_from, and the failure in payment_failed_at.
  • Emails Once per failed period, payment_failed with the amount, the date access lasts until, and Stripe's hosted invoice link (or the plan page). About three days before the grace period ends, the cron job sends payment_retry_reminder.
  • On the plan page "Your last payment didn't go through", with an Update payment button to Stripe's billing portal when one is set up.
  • Paid on a later try invoice.paid counts the new period from grace_from, never short of the period Stripe charged for, and clears the failure: a late payment doesn't add the grace days on top.
  • Stripe gives up On customer.subscription.deleted, access goes back to the paid-through date (or now), and the grace period and the failure are cleared.
  • Renews by itself users.auto_renew follows the member's current Stripe subscription: set when it's paid, cleared when they cancel in Stripe's billing page (cancel_at_period_end) or it ends, set again when they resume. The plan page says "Your plan renews by itself on…", and expiry warning emails skip members whose plan renews.
  • Logged Each failed try is in the activity log (payment.failed, by Stripe) and sends the payment.failed webhook; cancelling, resuming and ending are logged too.
Bayarcash (FPX and Malaysian methods, MYR only)8
  • FPX payment intent initiation BayarcashService::initiatePayment() creates a payment intent with portal key, order number, amount, payer details, and return/callback URLs, returning a hosted checkout URL.
  • Selectable payment channels Seven channels (IDs 1,12,16,18,21,6,17 — FPX, Credit Card, TNG eWallet, GrabPay, ShopeePay, DuitNow QR, Boost) each toggle via bayarcash_channel_{id}.
  • HMAC checksum signing Outgoing intents are signed with a sorted-payload hash_hmac('sha256', …, secret) checksum.
  • Sandbox/live switching Selects sandbox vs live base URI and token/secret based on bayarcash_sandbox.
  • Return-URL (callback) verification callback() HMAC-verifies returned fields and maps status codes (3=paid, 2=failed, 4=cancelled). A buyer whose session ended signs in again.
  • Webhook webhook() verifies the signed payload and updates the status server to server, replying 200 OK after a valid checksum, 400 for a bad one, and 503 when no secret is set.
  • Transaction requery / sync GET /subscription/sync/{id} re-queries a pending/failed transaction live from Stripe (for cs_ sessions) or Bayarcash and reconciles the local record.
  • Payment debug panel With payment_debug=1, the page shows the raw gateway payload, the signed text, and whether the checksum matches (never the expected checksum itself).
Payment methods added as one file3
  • One file per method Any other payment service is added as payments/{Name}Gateway.php, a class that extends PaymentGateway (services/PaymentGateway.php). LaunchX finds it on its own and gives it a card under Admin › Settings › Payment Gateways, with its own fields and on/off switch. Every method starts off.
  • Two addresses The buyer comes back to /pay/{id}/return?order=… and the service reports payments to /pay/{id}/notify. LaunchX checks that the order exists, was started with that method, and was paid in full in its currency, then grants it once.
  • Blueprint The Add a payment method button gives a guide with the base class, an example and the site's currencies, to paste into an AI assistant. A file that fails to load is switched off, and the reason shows in Settings and Admin › Errors. Rules for developers: .agents/rules/payment-gateways.md.
Access, expiry and history6
  • Idempotent grant with double-processing guard updateSubscription() ignores already-paid orders; on payment it extends expires_at, sets plan_id, and adds to LTV, stacking days for active plans, or starting the new plan that day when it's a switch with credit (see Changing plans).
  • Plan expiry email reminders (cron) checkExpirations() emails a warning ~3 days before expiry and a notice on expiry (plan_expired), each de-duplicated via expiry_notice_sent_at/expired_notice_sent_at. The warning is trial_ending during a free trial, payment_retry_reminder after a failed renewal, and plan_expiry_warning otherwise. Members whose Stripe plan renews by itself get neither while it does.
  • Active-subscription status card Shows plan name, days remaining, and the exact valid-until date.
  • Paginated billing history Lists transactions (10/page) with date, order ID, plan, price, and status/reason badges.
  • Printable receipts Paid transactions expose a "Receipt" button showing a printable receipt with the site's branding.
  • Payment result modals Post-payment status modals report success, pending, or failure/cancel based on the gateway status code.
Teams (several people on one plan)8
  • Seats per plan Each fixed plan has "People per plan (seats)" (subscription_plans.seats, default 1, up to 1000). The seats count the buyer, so a 5-seat plan covers its buyer, the team's owner, and 4 more people. Plan cards on the plan page and the home page say "For up to N people"; GET /api/v1/plans gives seats.
  • Team page (GET /team) In the menu while billing is on. An owner sees the seats in use (their own counted) with a meter, the people who joined, the invites waiting, and a field to rename the team (made on first visit as "{first name}'s team"). A member sees whose plan they're on, since when, until when, and a Leave button. Anyone else sees the plans that have seats.
  • Invites by email POST /team/invite sends the team_invite email template with a link that works for 14 days. The link is also shown once on the page, to send in a chat. Only a SHA-256 hash of its token is stored. 20 invites an hour per team; inviting your own email, someone already on the team, or past the free seats is refused. Invites waiting to be used hold a seat.
  • Joining GET /team/join/{token} explains the invite. Signed out, it asks to sign in or make an account and keeps the invite in the session; the dashboard brings them straight back after sign-in. Joining needs an account with the invited email, one team per person (team_members.user_id is unique), and someone running a team of their own can't join another. The last seat is re-counted with the team row locked, so two people can't take it at once.
  • Access worked out live Teams::access() gives a member the owner's end date while they hold a seat and the owner's access is on, computed from the owner's account each time (once per request), never copied: a renewal, refund, grace period or plan change reaches the whole team at once. user_has_active_access(), isPro(), access_until(), the dashboard, the plan page, the extension, broadcast audiences, the API and webhook user data all count it. A member who pays for their own plan keeps whichever lasts longer.
  • Fewer seats than people If the owner moves to a plan with fewer seats, the members who joined first keep the seats and the others see "No seat" until one frees up; nobody is removed. When the owner's plan ends, members lose access with it, and the owner's page says so.
  • Managing The owner sends an invite again (POST /team/resend, the old link stops working), cancels invites and removes people (POST /team/remove), and renames the team (POST /team/rename). Members leave with POST /team/leave. Deleting the owner's account removes the team.
  • Admin and data Admin › Users › Edit shows the team a member is on (with a link to the owner) or the team an owner runs. Seat changes on a plan go in the activity log. "Your data" includes the team (and, for an owner, the people invited). Webhooks team.member_joined and team.member_left (with by: member or owner); /api/v1/me gives subscription.team.
Plan limits and usage7
  • Limits per plan (GET /admin/limits) Admin › Plans › Limits lists what each plan includes, by key (exports, projects...: lowercase letters, digits and _). A limit is each month (starts again on the 1st, server time), in all (never starts again) or on or off (a feature a plan has or not). One grid: a row per limit, a column for Free, each plan (inactive ones marked) and pay as you go or other paid access; one column for everyone while billing is off. An empty box is no limit, 0 is not included. Saving goes in the activity log with old and new values; a number that isn't whole is refused and the old one kept. Tables plan_limits, plan_limit_values and usage_counters (migration 017).
  • Who gets which column Limits::tiersOf(): the member's own plan while they have access, the owner's plan for someone with a team seat (their count stays their own), Free otherwise. With several, the most generous wins. Admins have no limits.
  • Counting usage_try($key, $n) counts only if it fits, in one atomic statement (two requests can't both take the last one); usage_add() counts whatever the limit, and a negative number gives some back (never below 0); usage_set() stores a count your code keeps. limit_reached($key) stops with the 402 page (lock or gauge, used of limit, the reset date, See plans and See your usage), or JSON {"error": "limit_reached", ...} when the request asks for JSON. A key that isn't listed has no limit, is counted by the month, and is listed for the admin under "Counted by your code, not listed here".
  • Counted by LaunchX Once listed: api_requests (every call with a member's key, after the maintenance check; admin keys don't count; 402 limit_reached past it) and support_tickets (the new-ticket form and POST /api/v1/me/tickets).
  • What members see Plan cards on the plan page and the home page list the limits ticked On cards ("Exports: 300 a month", "Projects: unlimited", a feature that's on), before the admin's own lines. The Usage page (GET /usage, in the menu once a limit exists) shows the member's plan, a meter per limit (amber from 80%, red at 100%, "<1%" for a little), what's not in the plan, and when monthly counts start again. The dashboard has a Usage tile with the limit closest to full.
  • Told once Reaching a limit above 0 sends the usage_limit_reached email template (English and Malay copies included, in the member's language) and the usage.limit_reached webhook, once per period, and again only after the count went back under.
  • Admin and data Admin › Users › Edit has a Usage card with Reset to 0 per limit (logged as usage.reset). Deleting a plan deletes its values; deleting a limit keeps what was counted. "Your data" includes usage. The cron job removes monthly counts older than 13 months. API: GET /me/usage, GET and POST /admin/users/{id}/usage (try, add, set), and limits on each plan in GET /plans.
What happens on every payment3
  • Server-side purchase events Each paid transaction sends Meta Purchase and TikTok PlaceAnOrder server-side events with hashed user data and the order value, unless the buyer declined tracking.
  • Affiliate commission crediting On payment, a referred (non-self) buyer credits commission at a Pro/free rate (affiliate_rate_pro/affiliate_rate_free, default 30%/10%) depending on the referrer's current subscription, on the price without tax and in the currency paid, gated by affiliate_enabled.
  • Lifetime Value (LTV) tracking Every paid charge increments customer_value; refunds/disputes decrement it (floored at 0).
04Invoices and tax by countryA numbered invoice and PDF for every payment, with no gaps in the numbers, and tax by country with reverse charge.InvoicesTax by countryShow all 21Close
Invoices10
  • One for every paid payment While invoices_enabled is on (it is by default), every paid plan payment and store order gets an invoice the moment it's paid, whichever payment method took the money (Invoices::forPayment(), Invoices::forOrder()). Issuing one sends the invoice.issued webhook.
  • Numbers in order, with no gaps A prefix (invoice_prefix, INV-{YYYY}- by default; {YYYY}, {YY} and {MM} become the year and month), the next number and how many digits. The counter is locked in the same database transaction that writes the invoice (SELECT ... FOR UPDATE), so two payments at once never share a number and none is skipped. A payment gets one invoice however often its payment service reports it (a unique key on the payment).
  • A copy, made once The seller, the buyer, the lines, the discount and the tax are copied in when it's issued, so later changes to the settings, the plans or the member's details never change an invoice already sent.
  • Seller details Admin › Insights › Invoices › Invoice and tax settings (GET/POST /admin/invoices/settings): business name, address, country, your tax ID, an email, and a note at the bottom.
  • Buyer details Members fill in a name or company, an address, a country and a tax ID under Billing details on their plan page (POST /subscription/billing-details). Store buyers open "Buying for a business?" at checkout; a signed-in buyer's saved details are filled in.
  • Its own page and PDF Each invoice has a private link, /invoice/{token} (a random 32-character token; the page isn't indexed, sends no referrer and isn't cached), with Print and Download PDF. The PDF (/invoice/{token}/pdf, ?view=1 to open it in the browser) is A4 and made by LaunchX itself with the standard PDF fonts, no library (services/InvoicePdf.php).
  • Where buyers find it An Invoice link in the member's billing history, and one on the store's thank-you page.
  • Refunds and disputes When Stripe reports one, the invoice is marked Refunded or Disputed. Its number and amounts stay.
  • Admin list GET /admin/invoices: search by number, order, name or email; filter by status and dates; a total for each currency; View, PDF and Edit buyer on each. GET /admin/invoices/export downloads the list as CSV. Admin › Transactions and the store's orders link to each payment's invoice.
  • Correcting the buyer POST /admin/invoices/{id} fixes a typo, or adds a missing company name or tax ID. The amounts, the lines and the number stay as issued, and the change goes in the activity log.
Tax by country11
  • For plans, the store, or both tax_enabled, with tax_plans and tax_store. In the store, tax applies to every item on a sales page and to products marked "Add store tax".
  • A rate for each country A list of countries, each with a tax name (VAT, GST, SST…) and a rate (tax_rules), plus a rate for everywhere else (tax_default_rate, named tax_default_name). With an empty list, one rate applies everywhere.
  • Added, or included Tax is added at checkout (20.00 plus 8% costs 21.60), or prices already include it (tax_included: a price of 21.60 has 1.60 of tax in it, and the invoice says so).
  • Whose country The member's billing details, else the country they're browsing from (Cloudflare's CF-IPCountry, or the IPinfo lookup when a token is set), else the site's default country. Store checkout asks for the country while there are rates for countries or reverse charge is on.
  • Reverse charge With tax_reverse_charge on, a buyer who gives a tax ID, in another country than the seller's, pays no tax, and the invoice says "Reverse charge: the buyer accounts for the tax." What a tax ID is called is yours to set (tax_id_label: VAT number, GST number, ABN…).
  • On the plan page A note says which tax applies ("SST 8% for Malaysia is added at checkout", with Change your country), and each plan shows its price with tax.
  • At store checkout The tax line follows the country picked and the tax ID as the buyer types: POST /store/quote works the lines out on the server, and checkout charges what the server works out, never figures from the browser.
  • Stripe renewals Stripe charges the payment link's price, so a renewal is recorded as including the member's tax at their country's rate, and its invoice shows it.
  • Kept with each payment Payments and orders keep the tax amount, rate, name and country, and whether it was included, so reports and invoices don't change when rates do. Affiliates earn on the price without tax.
  • From 1.2 The store's single tax rate (store_tax_*) becomes the rate for everywhere else, for the store only (migration 013_invoices.php).
  • For developers Tax::rate($what, $country, $taxId) gives the rate, name and whether it's included or reverse-charged; Tax::split($amount, $rate, $currency) gives the tax and the total.
05Currencies and regional pricesEvery customer pays in their own currency, at prices you set for each one, with the right decimals everywhere.Region and currency mapEach member's currency, set at registrationPrices per plan and per itemStore currency switcherFormatting+2 moreShow all 26Close
Region and currency map6
  • Admin-managed region/currency map A single JSON setting (currency_map) drives the whole engine: each row maps a registration URL segment to a currency with region, code, symbol, position, enabled, and is_default. Decoded and cached per-request by get_currency_map(), filtering out malformed rows.
  • Currency map editor In Settings, the owner adds/removes rows with inline fields for region segment, code, symbol, prefix/postfix, an On toggle, and a single Default radio; rows serialize to JSON on submit (no hand-editing).
  • requestSubmit safeguard The editor uses form.requestSubmit() so the on-submit serializer always fires (fixing a bug where form.submit() wiped the saved map).
  • Default currency default_currency() returns the is_default enabled row, else the first enabled row, else the global currency.
  • Global currency, the last fallback global_currency() reads the older currency_code (default USD), currency_symbol ($) and currency_position (prefix).
  • Currency normalization normalize_currency() standardizes any row to uppercase code, a symbol, and a validated position (anything not postfix becomes prefix).
Each member's currency, set at registration5
  • Region-tagged signup URLs GET|POST /register/{region} ties a new account to the region's currency via currency_for_region() (case-insensitive), falling back to the default for unknown/blank segments.
  • Currency frozen onto the user record At registration the resolved code/symbol/position are written to the users table, and kept when the map changes later.
  • Region remembered across POST re-render The opening GET stores $_SESSION['reg_region']; POST recovers it from URL or session, while GET always honors the URL to avoid a stale region.
  • Admin-created users get the default currency Manually-created accounts are assigned default_currency().
  • Per-request "current currency" current_currency() returns the logged-in user's tied currency, else the global currency; current_currency_code() exposes just the code.
Prices per plan and per item4
  • Explicit per-currency plan prices with legacy fallback plan_price($plan, $code) reads the plan's prices JSON for the requested currency, falling back to the legacy amount.
  • Per-currency plan price editor The plan editor auto-generates a price input for every enabled currency, pre-fills the default box from amount, marks the default currency required, and posts prices[CODE] values.
  • Per-product / per-page pricing with sale offers StoreController::itemView() reads each product's prices and offers JSON keyed by currency, computes the effective price (offer if lower → "on sale" with a compare-at price), and flags free items in the active store currency.
  • Currency-aware totals computeTotals() builds subtotal via plan_price() in the selected currency, then layers tax, shipping, and fees, never trusting client amounts.
Store currency switcher4
  • Currency menu When more than one currency is available, catalog/product/checkout pages render a switcher that POSTs to store/set-currency and re-renders all prices, showing each option as CODE (symbol).
  • Set-currency endpoint POST /store/set-currency validates the code against allowed switcher currencies, stores it in session, and redirects back to a sanitized internal path only (open-redirect-safe).
  • Switcher toggle & enabled-only list switcherCurrencies() honors store_currency_switcher: off locks the store to the default currency; on lists every enabled currency.
  • Sticky store currency storeCurrency() resolves the session-selected currency (validated) and otherwise falls back to default_currency(); the chosen code is persisted on the orders row.
Formatting2
  • Money formatter format_currency($amount, $currency) uses the currency's own number of decimals (0 for JPY, 3 for KWD, 2 for most) with the correct symbol and prefix/postfix placement; with no currency it uses request context, and accepts a code string or an explicit ['symbol','position'] array to force a specific currency.
  • Currency display metadata lookup currency_meta($code) returns symbol/position for any code by scanning the map, falling back to global — so an order's stored currency_code always formats correctly even if it isn't the viewer's currency.
Minor units for Stripe2
  • Major → minor stripe_major_to_minor() uses a ×1 multiplier for zero-decimal currencies (BIF, CLP, DJF, GNF, JPY, KMF, KRW, MGA, PYG, RWF, UGX, VND, VUV, XAF, XOF, XPF) ×1000 rounded to a multiple of 10 for three-decimal currencies (BHD, JOD, KWD, OMR, TND), and ×100 otherwise. Applied in createCheckoutSession().
  • Minor → major stripe_minor_to_major() reverses it (÷1000 for the three-decimal currencies) so amounts read back from sessions, invoices, and recurring webhooks are recorded correctly.
Currency at checkout3
  • Charge in the user's tied currency Fixed plans charge in the user's currency_code using that plan's explicit per-currency price; flexible/extension stay global. Pre-migration sessions are backfilled from the DB.
  • Currency check A payment method that can't charge the order's currency (Bayarcash outside MYR) is refused before the order is saved, with a message to choose another method.
  • Per-order/subscription currency persistence The resolved code is stored on every subscriptions and orders row so history, statistics, and receipts show the actual currency charged.
06Affiliate programReferral links, commission for as long as a customer pays, monthly payouts in each currency earned, and rankings.Affiliate links and tagsCommission rates and earningsCommissions taken back on refunds and chargebacksAffiliate dashboard (`GET /affiliate`)Referrals, earnings and payout history+3 moreShow all 28Close

Members earn commission on the customers they refer, for as long as those customers pay. The program is switched by affiliate_enabled (off after a fresh seed) and needs billing_enabled on.

Commission rates and earnings6
  • Two commission-rate tiers Paid ("Pro") affiliates earn affiliate_rate_pro (default 30%), free ones affiliate_rate_free (default 10%); chosen automatically based on whether the affiliate has an active subscription at the time of sale. (This is two rate tiers on a single-tier referral — not a multi-level structure.)
  • Commission for as long as they pay One-time payments by a referred member always earn commission. Recurring Stripe payments (first and renewals) earn it only on plans with recurring tracking on. Redeemed orders never do.
  • Every payment method Commission rows are written where every paid plan is granted, whichever method took the payment; each row records amount, rate, commission, its currency (currency_code), the referred user, and a source_invoice_id.
  • One currency per amount A commission is in the currency its payment was made in; a renewal's commission is worked out on the price before tax. Balances, payouts, rankings, statistics and CSV downloads keep each currency apart and never add different currencies together. Commissions made before 1.4.0 get the currency of their payment when you migrate, else the main currency.
  • Self-referral protection Skipped when a user's affiliate_id equals their own ID.
  • Upgrade prompt Free affiliates see their current rate and a prompt to upgrade for the higher rate.
Commissions taken back on refunds and chargebacks2
  • Taken back automatically (recurring Stripe plans) On Stripe charge.refunded/charge.dispute.created for an invoiced charge, handleStripeRefundOrDispute() revokes access and deletes the matching unpaid commission (matched via source_invoice_id, only where payout_id IS NULL) — already-paid commissions are protected.
  • Partial-refund safety Partial refunds are detected and left in place; only full reversals trigger clawback.
Affiliate dashboard (GET /affiliate)6
  • Stat cards Month Earnings, Lifetime Earnings (one line per currency when there's more than one), current Earning Rate, and Total Referrals.
  • Withdrawal progress bar Live meter of unpaid "cycle earnings" vs. the minimum payout, one bar per currency: affiliate_minimum_payout (seeded 100, 50 if unset) for the main currency, affiliate_minimum_payouts (JSON, from "Minimum payout in other currencies") for the others; a currency with no minimum is paid whatever its balance.
  • Payout schedule Shows the monthly payout day (affiliate_payout_day, default the 15th) and that smaller balances roll over.
  • Recent previews Latest 5 referrals, latest 5 commission entries, and recent payout requests, each with "View All" links.
  • Privacy masking for free users Non-Pro affiliates see referred users' names/emails partially masked (e.g. j****n@gmail.com) with an "Upgrade to see details" link; Pro affiliates see full details.
  • Auto-payout generation on page visit Loading the dashboard calls checkAndGeneratePayouts('/affiliate'), so payouts are made even without cron.
Referrals, earnings and payout history3
  • Full paginated referrals list GET /affiliate/referrals (20/page) with the same Pro/free masking.
  • Full paginated earnings ledger GET /affiliate/earnings (date, transaction amount, rate, commission, 20/page).
  • Full paginated withdrawal history GET /affiliate/payouts with status badges (PROCESSING / COMPLETED / FAILED), "Sent to: {bank} ({account})" for completed/processing, and an "Action Required" message for failed.
Payout methods and payouts3
  • Multiple payout methods per affiliate Local Bank, International Bank (SWIFT + country), and E-Wallet/Crypto (PayPal, Wise, crypto wallet + network), saved on the profile (see §2 Profile).
  • Automated monthly payout generation checkAndGeneratePayouts() runs once per month on/after the payout day, aggregates each affiliate's unpaid commissions before the cycle cutoff, and for each currency at/above its minimum creates a processing payout in that currency, snapshots bank details, links the earnings, and logs the run (guarded by a last_payout_run month flag).
  • Carry-forward of sub-threshold balances Affiliates below the minimum keep their unpaid earnings for the next cycle; nothing is lost. Affiliates with no payout details for their chosen method get no payout either, and their balance carries forward.
Rankings (GET /affiliate/rankings)2
  • Monthly and lifetime leaderboards A toggle switches between current-month and all-time top-10 by total commission, in one currency at a time ("Commissions in" picks it when commissions came in more than one).
  • "Your current position" card Computes and highlights the user's exact rank and period total, with their row highlighted in the top-10 if present.
Settings1

(Admin-side payout management is covered in §12.)

  • affiliate_enabled (seeded off), affiliate_rate_pro (30) / affiliate_rate_free (10), affiliate_minimum_payout (seeded 100; 50 if unset) and affiliate_minimum_payouts (per other currency), affiliate_payout_day (15), affiliate_cookies_enabled (seeded off) / affiliate_cookie_duration (seeded 7 days; 30 if unset).
07Store (sales pages and guest checkout)Sales pages with their own checkout. Buyers need no account, and get their download link or message the moment they pay.Sales pagesItems on a sales pageGuest checkoutTax, shipping and feesDelivery+7 moreShow all 45Close
Sales pages5
  • Pages at a prefix you choose Published custom_pages answer at /{prefix}/{slug}; the prefix is store_page_prefix (default p), and a blank prefix serves them at /{slug}. Unpublished pages give a 404.
  • HTML content A page's content is output as HTML, for sales, landing or legal pages.
  • Full-width pages Pages with full_canvas drop the site header and footer.
  • A checkout on the page A page with items gets a checkout box under its content, with an optional checkout_heading. A page with no items is a plain content page.
  • Store switch store_enabled (on by default) turns the Store menu, the product catalogue and checkout on or off. Published pages stay up while it's off, but their checkout can't be used.
Items on a sales page5
  • Several items in one order Items are stored with the page (checkout_items JSON) and listed in the checkout box, where the buyer sets quantities.
  • Quantity and stock Optional quantity steppers. Items with stock tracking are capped at the stock count, on the page and on the server. The stock count isn't lowered when items sell.
  • Coming soon and out of stock These items are shown but can't be bought, and the server leaves them out.
  • Sale prices and badges A sale price crosses out the normal price; each item can have a coloured badge and a one-line description; a price of 0 shows as FREE. An item with no price in the buyer's currency counts as free in it.
  • Order names An order with several items is named like "First item +2 more".
Guest checkout9
  • No account needed POST /store/checkout takes the buyer's details; if they're signed in, the order is also linked to their account.
  • Buyer details Name, mobile number (any country, saved in international form) and email. The server requires a valid email; the browser also asks for the name and number.
  • Extra fields The page's own fields (text, long text, email, number, or a list), checked on the server when required and saved with the order.
  • Prices from the server Totals are always worked out on the server; amounts from the browser are never used.
  • Country and business details While tax differs by country, the buyer picks theirs (their likely country is chosen for them). "Buying for a business?" opens fields for a company name, tax ID and address, which go on the invoice. See Invoices and tax by country.
  • Discount codes An optional code field shows while a store code could be used. Apply asks POST /store/coupon for the new lines and total, and checkout checks the code again. See Discount codes.
  • Payment methods The buyer picks from the methods the page takes (all, or the ones ticked) that are turned on and can charge their currency: Stripe, Bayarcash, or any added in payments/.
  • Order numbers and links Each order gets an ORD-######-YYMMDD number and a random 32-character token for its thank-you page.
  • Pending until confirmed Orders are saved as pending and become paid only when the payment is confirmed.
Tax, shipping and fees4
  • Tax Tax by country (see §4), while tax_enabled and tax_store are on: on every item on a sales page, and on products marked "Add store tax".
  • Payment fee When store_fee_enabled is on, store_fee_percent% of the subtotal plus tax, plus a fixed store_fee_fixed amount per currency, named store_fee_label.
  • Shipping A fee per currency (store_shipping_fee) for products that need shipping. Sales pages don't charge shipping.
  • What the buyer sees The checkout box shows the subtotal, the tax for the country picked (or "reverse charge"), the payment fee and the total, and updates them as the buyer changes the country or tax ID (POST /store/quote). The order keeps each amount.
Delivery2
  • Per item on a page Each item can deliver a link or a text (download or text). When the order is paid, it keeps "Item name: content" for each item, shown on the thank-you page and in the confirmation email. Every buyer of an item gets the same text.
  • Licence keys (products only) A product of type keys takes one unused key from product_keys per sale (a single-row UPDATE ... LIMIT 1, so a key is never sold twice). When none are left, the order still completes and tells the buyer the key will follow by email. Products have no admin screen in this version (see §8).
Thank-you page5
  • Private link GET /store/thank-you?o={token} finds the order by its token (404 otherwise).
  • Paid or pending "Thank you!" when paid, or "We are confirming your payment…" while pending.
  • Receipt Each item with its quantity and amount (or "FREE"), the total and the status.
  • Delivery Once paid, what was delivered is shown; a single link shows as a "Download / Access" button.
  • Invoice Once paid, a link to the order's invoice and its PDF.
Search, sharing and pixels for each page4
  • Search and sharing Each page has its own seo_title, seo_description and og_image, which layout.php uses instead of the site-wide ones.
  • Pixels of its own Each page has its own meta_pixel_id and tiktok_pixel_id, separate from the site-wide pixels. They load only for visitors who may be tracked.
  • Events PageView, and ViewContent when the page has a checkout; InitiateCheckout when the checkout box loads and each time a quantity changes; Purchase (Meta) and CompletePayment (TikTok) on the paid thank-you page, with the order number as the event ID.
  • Server-side purchase events When the order is paid, Meta Purchase and TikTok CompletePayment are sent with the page's meta_capi_token / tiktok_capi_token, the buyer's hashed details and the order number as the event ID, so each purchase counts once. They aren't sent for a buyer who declined tracking.
Product catalogue3
  • Catalogue GET /store lists active products as cards (name and price in the visitor's currency), by sort then newest first.
  • Product pages GET /store/{slug} shows the image, description, price and a checkout box (email, with the name optional); unknown or inactive products give a 404.
  • No admin screen yet Products can't be made from the admin in this version (see §8), so the catalogue stays empty unless products are added to the database another way.
Currencies0

(See §5.) When store_currency_switcher is on and more than one currency is turned on, buyers can switch currency on sales pages, the catalogue and product pages.

    Payment and order completion6
    • Stripe Sends the buyer to a Stripe Checkout page and back to GET /store/return?session_id=..., which checks payment_status=paid before completing the order.
    • Bayarcash The buyer comes back to GET|POST /store/callback, and the server notification arrives at POST /store/webhook; both check the signature.
    • Added payment methods Use /pay/{id}/return and /pay/{id}/notify, as for plans (see §3).
    • Back to the page A failed or cancelled payment sends the buyer back to the page they bought from (or the product, or the catalogue).
    • Completed once finalizeByOrderNumber() uses UPDATE ... WHERE status<>'paid' in a transaction, so only one caller marks the order paid, and delivery, the email, the purchase events and the order.paid webhook happen once.
    • Payment ID The payment service's ID is saved with the order.
    Order confirmation email1
    • Sent on payment The order_confirmation template is sent in the background with the buyer's name, the order number, the item, the total, the delivery and a link to the thank-you page.
    Reliability and security1
    • Prepared statements throughout; errors are logged and never stop the buyer; output is escaped; fixed routes are registered before page and product addresses, so a slug can't hide them.
    08Store admin: pages, items and ordersBuild pages, items, offers and checkout fields, preview them, and follow every order.PagesContent editor (three tabs)Item builderExtra checkout fieldsCheckout heading and payment methods (per page)+6 moreShow all 45Close

    Store admin pages are for admins only. They live in StoreAdminController with views under views/admin/store/.

    Pages4
    • Custom pages list GET /admin/store/pages lists every landing/sales page (newest first) with title, live public URL (linked), and an Active/Hidden badge.
    • Create / Edit / Delete page GET/POST /admin/store/pages/create, /edit/{id}, and POST /admin/store/pages/delete/{id} (with JS confirm).
    • Auto slug + uniqueness Blank slugs auto-generate from the title; slugs are normalized and made unique by appending -2, -3, etc.
    • Published A checkbox controls whether the page is live; new pages default to active.
    Content editor (three tabs)4
    • Rich text tab An editor with bold/italic/underline, H2/H3/paragraph/blockquote, bullet/numbered lists, insert-link/image, and clear-formatting.
    • HTML tab A raw monospace code textarea, kept in sync with the Rich text tab both ways.
    • Preview tab Shows the content in a sandboxed frame.
    • Full-canvas toggle Makes the page render full-width with no site header/footer.
    Item builder9
    • Item cards Each item is defined on the page (no product record needed), as a card you can drag, with an "Add item" button and a count.
    • Drag-to-reorder, duplicate, delete Reorder via the grip handle (order preserved on save); one-click duplicate and delete per item.
    • Per-currency pricing Prices per item per currency, with a currency selector offering only enabled currencies (falls back to default).
    • Offer / sale price (strikethrough) An optional discounted price per currency, applied only when below the base price (stored as offers).
    • Badges with custom color A short label with a hex color picker (validated, default #7c3aed).
    • Short description / subtitle, quantity toggle, stock tracking, coming-soon flag Per-item controls for subtitle, a buyer-facing quantity stepper (default on), stock_enabled+stock_qty, and a Coming Soon label.
    • Delivery per item None, Download or link, or Licence text, plus what the buyer gets, shown after payment and emailed.
    • Content-only pages An empty items list produces a pure content/landing page with no checkout.
    • Server-side sanitization cleanCheckoutItems() drops unnamed items, rounds prices, uppercases codes, validates badge color and delivery type, and clamps stock before persisting JSON.
    Extra checkout fields4
    • Add custom fields Beyond default Name/Mobile/Email, collect extra details via a drag-to-reorder card builder with duplicate/delete.
    • Field types Text, Paragraph (textarea), Email, Number, or Dropdown (select).
    • Required toggle & dropdown options Any field can be required; select fields take a comma-separated options list.
    • Server-side validation cleanCustomFields() discards label-less fields, slugifies keys, whitelists types, and stores JSON.
    Checkout heading and payment methods (per page)2
    • Optional checkout heading A free-text heading above the form.
    • Payment methods per page Tick the methods the page takes (Stripe, Bayarcash, or any added in payments/). With all ticked, the page takes every method that's turned on, including ones added later. The site-wide keys are used.
    Checkout preview1
    • Updates as you edit Redraws on every change, showing the heading, default + custom fields, a line-item table with badges, sale/strikethrough pricing, FREE handling, Coming Soon/Out of Stock states, quantity steppers, stock counts, payment-method radios, a running total, and a disabled "Complete payment" button.
    Full-page preview1
    • Preview page in a new tab POST /admin/store/pages/preview renders the real public page template from the unsaved form without persisting; the Pay button is disabled and real Meta/TikTok pixels are suppressed so no tracking fires.
    Search, sharing and pixels (per page)2
    • Per-page SEO Own SEO title (defaults to page title), meta description, and uploadable OG image (thumbnail in edit mode, saved via the shared product-image uploader).
    • Independent Meta & TikTok pixels Own Meta Pixel ID + CAPI token and TikTok Pixel ID + CAPI token for page-level tracking.
    Orders4
    • Orders list with revenue GET /admin/store/orders paginates (20/page) with order number, buyer, product, formatted total, status badge, and date; the header shows the order count and the total of paid orders, one total for each currency.
    • Search & status filter Free-text across order number/email/name/product, plus Paid/Pending/Failed/Cancelled filter; the total follows the filters; filters persist across pages.
    • Download orders GET /admin/store/orders/export with the same filters: date, order number, status, product, buyer, currency, subtotal, tax, shipping, fee, total, payment method and id, shipping address and the extra checkout fields.
    • Order detail view GET /admin/store/orders/{id} shows a Summary card (status, product, subtotal, conditional tax/shipping/fee, total, gateway, payment ID, date), a Buyer card (name, email, optional phone, each custom field), a conditional Shipping card, and a conditional "Delivered" card showing the exact license/text/link. The order's invoice and the buyer's business details are shown when there are any.
    Store settings7
    • Settings save GET/POST /admin/store/settings upserts to the settings table.
    • Store enable + currency switcher store_enabled and store_currency_switcher.
    • Custom page URL prefix store_page_prefix (default p); blank serves clean root URLs.
    • Tax Set with the invoice settings (see §4); the store page links there.
    • Gateway/processing fee store_fee_enabled, store_fee_label, store_fee_percent, and per-currency store_fee_fixed.
    • Per-currency shipping fee store_shipping_fee per enabled currency.
    • Settings whitelist Only allow-listed keys are written; per-currency grids are JSON-encoded, preventing injection.
    Products (code present, no admin routes)7

    > products(), createProduct(), editProduct(), deleteProduct() and their views exist, but no admin/store/products... routes are registered in routes.php and there is no menu link, so products can't be made from the admin. The product catalogue, product pages and licence-key delivery work only with products added to the database another way.

    • Products list Thumbnail, name, /store/{slug} path, default-currency price, delivery type (with available-key count for keys), Active/Hidden status.
    • Create / edit / delete product Standard CRUD; delete also removes the product's license keys.
    • Per-currency product pricing A price grid per enabled currency with the default required; parsePrices() derives the canonical amount and stores the rest as JSON.
    • Delivery types None, Download/access URL, Licence text (same for all), or Licence keys (one used per sale).
    • Licence keys Paste keys (one per line) appended additively; edit view shows "available of total."
    • Product image upload PNG, JPG, GIF or WebP, checked by its contents, stored under public/uploads/products with a randomized name.
    • Product options Active, Taxable, Requires-shipping toggles, plus a sort-order field.
    09Browser extensionA starter Chrome extension that signs in with your site's accounts and checks for an active plan.Sign-in with a tokenAccess and version checksExtension pageBranded downloadThe starter extensionShow all 17Close

    LaunchX includes a starter Chrome extension (Manifest V3, side panel) that signs in with the site's accounts, checks the member's access and the minimum version each time it opens, then shows an empty screen to build your tool on. Each download carries the site's name, address and icon.

    Sign-in with a token5
    • Login with site credentials POST /api/extension/login takes the email and password, and the authenticator code when two-step sign-in is on; the email must be verified unless verification is off. It allows 8 tries per 15 minutes per IP and email, and 30 per IP. On success it makes a token, stored only as a SHA-256 hash in api_tokens, and returns it with the user, subscription and version details. Members who only sign in with a provider have no password, so they can't sign in here.
    • Bearer-token session GET /api/extension/session re-validates a stored token on every load (token via Authorization: Bearer, X-Auth-Token, or a token query param), bumping last_used_at; invalid/missing tokens return 401.
    • Logout POST /api/extension/logout deletes the token server-side, invalidating it everywhere.
    • Simple CORS requests Session checks pass the token and extension version as query params (?token=&ev=) so they work before host permission is granted on a dev install; the API sets permissive CORS headers and answers OPTIONS preflights. The login/logout routes are CSRF-exempt.
    • Token helpers api_user_by_token() resolves the user row from any token transport; api_require_token() emits a 401 JSON guard — both reusable for future API endpoints.
    Access and version checks3
    • Per-load access gate user_has_active_access() grants access when billing is off, when users.extension = 1 (lifetime extension access), or while expires_at is in the future; otherwise the extension shows an "inactive" screen linking to the plans page.
    • Minimum-version gate version_gte() numerically compares the extension's reported version against ext_min_version; an out-of-date install is blocked with an "update required (you have X, need Y)" screen linking to the download.
    • Gate payload Each login/session response carries subscription (active, plan name, expiry, days-left) and version (min, latest, download URL, blocked flag) so the extension routes to the right screen.
    Extension page1
    • Status & download page GET /extension (signed-in members; 404 when extension_enabled is off) shows access status ("N days left until …" or "Full access"), a versioned download button, and a step-by-step install & sign-in guide; users without access see a "Subscription required" card linking to the plans page.
    Branded download5
    • On-the-fly branded ZIP GET /extension/download (members with access, or admins) builds the extension ZIP per request, prepending runtime config (APP_VERSION, APP_BASE_URL, APP_API_URL, APP_NAME) to background.js and sidebar.js.
    • Dynamic manifest rewriting Sets the version, sets the extension name and description from settings, and appends the SaaS host to host_permissions so each deployment's build is unique.
    • Admin icon override An ext_icon PNG upload replaces the bundled icon.png in the build.
    • New builds without redeploying Admins upload a new build as a ZIP (ext_zip), unpacked over /extensions/ext-app/. ext_version sets the version; ext_last_updated and ext_mirror_link are saved but not used yet.
    • On/off switch extension_enabled (on in code, but seeded off) controls the page and the download; off returns 404.
    The starter extension3
    • Side-panel UI A dark four-screen panel (login, version-blocked, subscription-inactive, app) backed by chrome.storage.local for the token, user, and optional self-host server URL.
    • Blank app dashboard Once both gates pass, the app screen shows the signed-in email, version, and days-left around a single "Your extension UI goes here" placeholder, left empty for your own tool.
    • Minimal service worker Opens the side panel on toolbar click; no other logic.
    10Email, notifications and PWAAn app people install from the browser, free push to their lock screen, an in-app inbox, broadcasts by email to the members you pick with one-click unsubscribe, and email through your own SMTP with templates you edit.Sending emailEmail templates and placeholdersSending in the backgroundEmail logEmail templates in the admin+3 moreShow all 52Close
    Sending email7
    • Two ways to send send_mail() sends through its own SMTP client or PHP's mail(), chosen by mail_mailer (seeded smtp; PHP mail() only when the setting is missing); all emails are text/html.
    • Own SMTP client (no Composer or PHPMailer) Opens a raw socket to mail_host:mail_port and walks the full SMTP handshake (EHLO → STARTTLS/SSL → AUTH LOGIN → MAIL FROM → RCPT TO → DATA → QUIT) checking each answer.
    • TLS and SSL support Honors mail_encryption (tls via STARTTLS, ssl via ssl://), working with Gmail/SES/Mailgun on 587 or 465.
    • Optional SMTP auth Sends base64 AUTH LOGIN when mail_username is set, unauthenticated when blank.
    • Per-call config override Accepts a $config array to override mailer/host/port/user/pass/encryption/from for a single send.
    • Configurable From identity From name/address from mail_from_name (default "LaunchX") and mail_from_address, with proper headers.
    • Errors returned Returns true or a human-readable error string, surfaced by the admin test tool.
    Email templates and placeholders3
    • Template-driven transactional emails send_template_mail($to, $slug, $data) loads a row from email_templates, substitutes {{placeholder}} tokens in subject + body, and sends. Slugs include email_verification, plan_expiry_warning, plan_expired, forgot_password, order_confirmation, team_invite, etc.
    • Automatic {{app_name}} injection Every templated send auto-fills {{app_name}} from settings.
    • Placeholders Any $data key becomes a {{key}} in subject and body.
    Sending in the background5
    • Email in the background send_mail_bg() spawns a detached CLI worker (scripts/mailer.php) via popen, writing the body to a temp file so the page doesn't wait.
    • Cross-platform spawning Detects Windows (start /B) vs Linux (... > /dev/null 2>&1 &).
    • Disabled-function fallback If popen is disabled (common on aaPanel/shared hosting), it sends right away instead via php_function_enabled('popen').
    • Background templated send send_template_mail_bg() resolves template + placeholders in-request, then hands off to send_mail_bg().
    • Standalone CLI mailer worker scripts/mailer.php (web-SAPI-refusing) loads the app, reads the message from the tmp/mail_*.json file named on its command line, sends it and deletes the file.
    Email log2
    • Every email logged send_mail() records every send (success/failure) into email_logs with recipient, subject, template slug, status, and exact error.
    • Admin email log viewer GET /admin/emails lists templates plus a paginated "Email Sent Logs" table (default 25) with Sent/Failed badges (errors on hover).
    Email templates in the admin7
    • Templates dashboard Lists every template with name, description, and copyable placeholder chips.
    • Disabled-template awareness Flags templates that won't send (billing templates when billing_enabled is off; email_verification when disable_email_verify is on).
    • Editor with live HTML preview GET /admin/emails/edit/{id} edits subject + HTML body with a tabbed Edit/Preview toggle showing the email with sample values for common placeholders.
    • Save & test POST /admin/emails/update/{id} validates and persists (CSRF-protected); POST /admin/emails/test/{id} sends a test with sample values (order and code placeholders stay as {{tags}}) and reports the result.
    • SMTP-not-configured warning Warns inline (with a Settings link) when mail_host/mail_username are empty.
    • One-click placeholder copy A sticky sidebar lists each template's placeholders as copyable {{tag}} chips.
    • A copy in each language A tab per language (?in=ms) edits the copy members who use that language get, with its own test send; Remove this copy hands them the main email again. The list shows which languages each template has. See §17.
    Web push (Firebase FCM)8
    • FCM v1 sender services/FcmService.php is a client with no dependencies, using the HTTP v1 API.
    • Service-account JWT auth (no SDK) Reads the service-account JSON, RS256-signs a JWT with openssl_sign, and exchanges it at Google's OAuth2 endpoint, with granular error messages.
    • What a push holds Title, body, PWA icon (pwa_icon_192), and a click-through link (defaults to /notifications).
    • Per-token send with results map Loops recipient tokens and returns a per-token result map.
    • Save / delete token endpoints POST /fcm/save-token upserts (with ON DUPLICATE KEY UPDATE ownership swap); POST /fcm/delete-token removes one or all.
    • Client-side token lifecycle When fcm_enabled + a VAPID key are set, layout.php loads the Firebase compat SDK, initializes from admin config, calls getToken, and POSTs the token — only re-sending when it changes or is older than 7 days.
    • Foreground message display messaging.onMessage shows a native Notification for focused-tab pushes.
    • Stale token auto-cleanup After a broadcast, tokens returning UNREGISTERED/INVALID_ARGUMENT are deleted.
    Broadcasts and the inbox13
    • One message, three ways Admin › Notifications › Broadcast (GET /admin/notifications, BroadcastController, services/Broadcasts.php) sends a title, a message and an optional link to members' inbox, as a push notification (when FCM is set up) and by email (when a From address is set). Ways that aren't set up are greyed out with a link to their settings.
    • The audience Everyone, paying members (own access or a team seat whose owner's plan is on; everyone while billing is off) or free members, narrowed by plan (a team seat counts as the owner's plan), language (the default language includes members who never picked one), country (billing_country, else users.country, where they signed up from) and last visit (users.last_seen_at, set once a day: seen in the last N days, or not for N days or more). Only verified accounts. Broadcasts::audience() drops anything unknown.
    • Live count POST /admin/notifications/reach returns how many members it reaches, how many by email (those who haven't unsubscribed) and how many have a device for push, as the admin picks.
    • Email test POST /admin/notifications/test emails the admin a "[Test]" copy.
    • Background sending Emails are queued in broadcast_outbox and sent by scripts/broadcast.php (started with popen, like the mailer), at broadcast_per_minute (60 by default, 0 for no limit), up to 3 tries each, stopping after 5 failures in a row. A lock file keeps it to one sender, so no email goes twice. Where popen is off, the cron job sends them, and so does POST /admin/notifications/progress, which the open Broadcast page calls to show progress.
    • The email The broadcast template (with a Malay copy), in each member's language: their first name, the title, the message with paragraphs and clickable links, an Open button for the link, and an unsubscribe link. The subject is the title as written. List-Unsubscribe and List-Unsubscribe-Post: List-Unsubscribe=One-Click headers give mail programs their unsubscribe button.
    • Unsubscribing GET /unsubscribe/{token} asks first (mail scanners open links); POST to the same address unsubscribes, with no sign-in or CSRF token (the token in the address is the key), and counts it on the broadcast it came from (?b=). Unsubscribing skips the emails still queued for that member. They can subscribe again from the same page, from News by email on their profile (POST /user/email-news) or with PATCH /api/v1/me.
    • The sign-up box news_signup: ticked (default), unticked (what the EU and UK ask for) or off (no box: everyone gets news until they unsubscribe). Sign-up and SSO sign-up save email_news and the country (the phone number's, else Cloudflare's CF-IPCountry, else ipinfo when set up); an older account learns its country at its next sign-in.
    • The list of sent broadcasts Who it went to, by which ways, the link, and for email how many were sent, failed and unsubscribed, with a progress bar while it's sending. Delete one (its queued emails don't go) or all of them. Sending, deleting and settings are in the activity log.
    • User inbox GET /notifications shows the broadcasts meant for them since they joined: all, pro or free by their access, specific to them, or list (picked members, in notification_recipients). A broadcast sent by email or push only (in_inbox = 0) stays out. Unread dots, a "Read more" modal, and Open links. It works with push off.
    • Auto mark-as-read Viewing the inbox INSERT IGNOREs notification_reads, clearing the unread badge.
    • Unread badge counter unread_notifications_count() powers the sidebar indicator.
    • Browser permission UX With push on, JS detects Notification.permission and shows a "Get notified right away" banner (default), unblock instructions (denied), or a green confirmation (granted).
    Install as an app (PWA)7
    • Dynamic web app manifest GET /manifest.json serves an application/manifest+json populated from pwa_name, pwa_short_name, pwa_description, pwa_theme_color, pwa_bg_color, standalone display, and a /dashboard start URL.
    • Configurable icons & screenshots 192/512 icons (pwa_icon_192, pwa_icon_512) and wide/mobile screenshots for the install prompt.
    • Dynamically generated service worker GET /service-worker.js emits a per-install SW with a cache name derived from the app name. It handles only GET requests: forms (POST) go straight to the network.
    • Offline page, no stored pages Pages are never stored by the service worker, because they can hold private details (a profile, an admin page) that whoever uses the browser next must not see; only the manifest and the app icons are kept. With no internet, a page shows a short "You're offline" screen with a Try again button. On update, the copies of pages that older versions stored are deleted.
    • Cache versioning / cleanup On activate, deletes caches not matching the current CACHE_NAME.
    • Native push handling in the SW A push listener shows a notification that vibrates; clicking it focuses an open tab or opens the target URL.
    • Conditional bootstrap SW registration loads only when pwa_enabled/fcm_enabled are on, warning if the context isn't HTTPS/localhost. Google's Firebase scripts load only for a signed-in visitor, with push on and its keys filled in: everyone else gets no outside script.
    11Support ticketsThreaded tickets for members, one queue for your team.For membersFor adminsTechnical notesShow all 27Close

    Threaded tickets (support_tickets) for signed-in members, and one queue for admins. All routes require authMiddleware; admin routes add roleMiddleware('Admin').

    For members12
    • Submit a ticket GET/POST /support/create asks for name, email, subject and message (all four required), saved as open.
    • Pre-filled contact details Name/Email auto-populate from the signed-in account (still editable).
    • Confirmation A "Message received" card with links to the home page and to their tickets.
    • Their tickets GET /support shows only the user's own tickets (newest first) with subject, preview, status badge, and date.
    • Counts All, Open, Processing and Resolved, counted among the tickets on the page shown (up to 15).
    • Threaded conversation view GET /support/{hash} shows the original message plus all replies, with admin replies branded as "LaunchX Team" (shield icon).
    • Encoded IDs in addresses Links use hash_id()/decode_id(); ownership is checked on every view.
    • Ownership enforcement Viewing re-checks id = ? AND user_id = ?; a non-owner/invalid hash is blocked (403/404).
    • User reply POST /support/{hash}/reply appends a reply tagged is_admin = 0.
    • Closed tickets On the site, a closed ticket shows an "archived" notice instead of the reply box. A reply sent anyway, or through the API, opens it again.
    • Status badges & ticket numbers Zero-padded numbers (e.g. #00042) with consistent color coding.
    • Paginated list 15/page with Prev/Next, numbered pages, and an "X of Y" counter.
    For admins10
    • Global queue GET /admin/tickets shows every ticket (newest first) with submitter, subject, preview, status, and date.
    • Counts All tickets, Open, Processing and Resolved, counted among the tickets on the page shown.
    • Case detail view GET /admin/tickets/{id} shows the threaded conversation plus a customer/metadata sidebar (404 if missing).
    • Admin reply with auto-status bump POST /admin/tickets/{id}/reply appends a reply tagged is_admin = 1; if not closed, advances status to processing.
    • Manual status change POST /admin/tickets/{id}/status sets Open/Processing/Closed.
    • One-click Resolve & Close A sidebar button posts status=closed directly.
    • Customer identity panel Avatar initial, name, and email for immediate context.
    • Link to full user profile If user_id is present, a "View profile" button links to /admin/users/edit/{user_id}.
    • Direct email shortcut A mailto: link pre-filled with the address and a "Re: {subject}" line.
    • Opened-on timestamp & pagination The date the ticket was opened; 15/page admin queue.
    Technical notes5
    • JSON-stored reply thread Replies live as a JSON array in the replies column (user_id, is_admin, message, created_at), with safe fallbacks.
    • Tickets without a user The insert allows a null user_id, though current routes require auth.
    • XSS-safe rendering All user content is htmlspecialchars()-escaped, with line breaks preserved via white-space: pre-wrap.
    • CSRF-protected actions & integer-bound pagination Every form emits csrf_field(); list queries bind LIMIT/OFFSET as PARAM_INT with prepared statements.
    • Works on phones Dedicated breakpoints (fixed bottom reply bar, stacked stat grids).
    12Admin: users, payouts and statisticsUsers, sign in as a user, payouts, transactions, an activity log, statistics and traffic.UsersAffiliate payoutsTransactionsActivity logStatistics+5 moreShow all 49Close

    All routes are guarded by authMiddleware + roleMiddleware('Admin') (except stop-impersonating, login-only). Logic in AdminController; UI in views/admin/.

    Users12
    • All Users directory GET /admin/users lists every user (50/page, newest first) with a live search matching name, email, and inviter name/email. Each row joins plan name, inviter, and computed lifetime + current-month commission.
    • Per-user activity & status columns Plan status (PRO badge with exact days-left and expiry, or "Free"), join date, last-login ("Never" if absent), referral source, and monthly/lifetime commission.
    • Create user manually GET/POST /admin/users/create adds name, email, phone, password, role, and optional "pro_days"; auto-verifies the email, blocks duplicate email/phone, and stamps the site's default currency.
    • Edit user (full profile) GET/POST /admin/users/edit/{id} edits name/email/phone/role, optional password reset, expiry, plan, the extension flag, and the complete payout profile, and shows the team the user is on or runs. Rejects a phone already used by another account.
    • Delete user (with cascade) POST /admin/users/delete/{id} removes a user; subscriptions, earnings, and payouts cascade. Admins can't delete themselves.
    • Grant / set plan days ("Add Pro Days") POST /admin/users/add-pro-days/{id} sets access to exactly N days from today and assigns a plan, via a modal with a live "Ends on" estimate.
    • Remove all PRO access POST /admin/users/remove-plan/{id} clears plan_id, expires_at and lifetime extension access (extension), redirecting back to edit or list as appropriate.
    • Manually verify email POST /admin/users/verify/{id} stamps email_verified_at and wipes pending token/OTP.
    • Impersonate user POST /admin/impersonate/{id} takes over another user's session (not yourself, not another admin, and not while already impersonating).
    • Stop impersonating POST /admin/stop-impersonating exits and returns to the user list.
    • Export users to CSV GET /admin/users/export?type={all|free|paid} streams a dated CSV with 23 columns including contact, role, verification date, affiliate tag, plan, inviter email, customer value, and every payout/bank detail.
    • Every CSV is safe to open All downloads go through csv_download(): UTF-8 with a byte-order mark (so Excel keeps accents), dates in ISO 8601 with their offset, and a ' before any cell that starts like a formula (=, +, -, @). Each download is written to the activity log.
    Affiliate payouts5
    • Payout management dashboard GET /admin/payouts shows affiliates with unpaid balances, one row per affiliate and currency (flagged "ELIGIBLE FOR PAYOUT" at or above that currency's minimum, shown on the row) and the payout history, 25 a page (processing first). Gated behind billing_enabled + affiliate_enabled.
    • Per-affiliate payout detail rendering Renders the correct destination per chosen method (local bank, international/SWIFT, or e-wallet/PayPal/Wise/crypto), or flags "No payment details provided."
    • Process manual payout POST /admin/payouts/manual/{id} creates a "processing" record in the row's currency, snapshotting current details, sums that currency's unpaid earnings, and links them (blocks when the balance is zero).
    • Update payout status + notes POST /admin/payouts/{id} marks processing/completed/failed with quick-note presets; marking one "failed" unlinks its earnings so the balance comes back, unless it was already marked completed.
    • Download payouts GET /admin/payouts/export: every payout with its status, amount, payee and the details it was paid to.
    Transactions6
    • Transaction ledger with filters GET /admin/transactions lists all subscription payments (20/page) joined to user name/email, filterable by free-text, status, and date range. Gated behind billing_enabled.
    • KPI cards Total paid revenue (one total for each currency), paid count, pending count, and failed/cancelled count — all respecting active filters.
    • Invoices A paid payment with an invoice has a button that opens it.
    • Per-transaction detail modal Order number, payment ID, status, created date, and pretty-printed raw JSON metadata.
    • Color-coded status badges Paid/pending/failed/cancelled (green/yellow/red/gray).
    • Download payments GET /admin/transactions/export with the page's filters: date, order number, status, plan, days, amount and currency, payment method and id, the member, and their access date.
    Activity log5
    • Who changed what GET /admin/activity lists, newest first, 50 a page, what admins changed: settings (each key with its old and new value; keys, passwords, tokens and long texts only as "changed"), accounts, plans, payouts, notifications, store products and pages, email templates, Explore cards, files, backups, SQLite changes, API keys, CSV downloads, admins signing in (and how) and signing in as a member. Changes made through the API are listed under the key's owner, marked API; refunds and disputes Stripe reports are marked Automatic.
    • Filters By kind (settings, accounts, sign-ins, money, store, files, databases, done by the app), by admin, and by a word (an email, a file, a plan).
    • Download GET /admin/activity/export with the same filters.
    • How long POST /admin/activity/retention: 3 months to 5 years (1 year by default); the cron job deletes older entries.
    • For developers admin_log($action, [type, id, label], $detail) adds an entry, and admin_log_changes($before, $after) makes the "old → new" list, leaving out secrets. The admin's email and the target's label are copied in, so entries still read after the account or item is gone. A failure to write the log never stops the change itself.
    Statistics6
    • System overview GET /admin/statistics headline cards: logins today, active paid users, total users, today's revenue, this-month revenue, lifetime gross (revenue cards hidden when billing_enabled is off).
    • User growth panel Accounts joined today and this month.
    • Affiliate payouts overview Total "processing" and total "completed" payouts in the currency picked with "Revenue in" (billing + affiliate only).
    • One currency at a time When payments came in more than one currency, a "Revenue in" switch picks the currency for every revenue figure and the chart (?cur=EUR); amounts in different currencies are never added together.
    • 12-month revenue chart A line chart of monthly paid revenue, drawn by public/assets/lx-chart.js (no library), with a table of the numbers.
    • Daily transaction summary with date filter A range-filterable table of successful payments grouped by day (count + revenue), with a "Range Totals" footer (defaults to current month).
    Traffic5
    • Traffic dashboard GET /admin/traffic tracks home page visitors, with a page-path selector (auto-discovered from traffic_logs) and a from/to range.
    • Visitor KPI cards Visitors today, all-time, range views, and unique visitors (distinct IPs) in range — scoped to the chosen path.
    • Daily & hourly charts A daily page-views bar chart (zero-filled) and a 24-hour "Hourly Peak Traffic" chart.
    • Top dimensions Top 10 countries (geo-resolved; warns when no ipinfo_token), languages (from Accept-Language), platforms/OS, browsers (with brand icons), device-type split, referrer domains, and the top 10 full referrer addresses.
    • Home page off When the home page is off and no other page has traffic, a window explains that nothing is being tracked and links to settings.
    Error log and debug mode4
    • Error log viewer GET /admin/errors reads database/system_errors.sqlite newest-first with a page-size selector and pagination (times converted from UTC to app timezone).
    • Error detail modal Message, file:line, request URL, local timestamp, and full stack trace; levels color-badged.
    • Clear all error logs POST /admin/errors/clear deletes all errors and runs VACUUM.
    • Toggle debug mode POST /admin/errors/toggle-debug flips database/debug_mode.on, reflecting current ON/OFF state.
    Cron logs4
    • Execution history GET /admin/cron-logs lists cron_logs runs newest-first with time, job name, location, status, execution time, IP + UA, and a JSON details modal.
    • Job cards The scheduled jobs and how often they run: DB backup, files backup, affiliate payouts (on affiliate_payout_day), and subscription expiry notices, each listing trigger endpoints.
    • Cron URL helper A copy-to-clipboard /run-cron URL with hourly-ping guidance.
    • Clear cron logs POST /admin/cron-logs/clear truncates the table; links to email logs.
    Push notifications0

    (See §10 for the full notification system.) GET /admin/notifications console (gated behind fcm_enabled), POST /admin/notifications/send with all/free/pro targeting, automatic stale-token cleanup, and delete one/all.

      Other admin tools2
      • Test SMTP / email delivery POST /admin/settings/test-email sends a live test using the posted (unsaved) SMTP config and returns JSON.
      • Preview system/error pages GET /admin/preview-page/{slug} renders the 403/404/419/500/maintenance templates in preview mode.
      13Admin settings, branding, SEO and marketingYour brand, your SEO, pixels with server-side events, banners, campaigns and legal pages.Identity, branding and themeLocalisation and currencySEO and sharingPixels, server-side events and tracking (three audiences)Announcement and promo banners+10 moreShow all 35Close

      The Settings hub (GET/POST /admin/settings, rendered by views/admin/settings.php) is one page of collapsible cards. Each card is its own form posting form_section, so the owner saves one group at a time and comes back to that card (?section=... opens it). Only keys in the server's $allowedKeys list are saved (plus bayarcash_channel_* and each added payment method's fields), with INSERT ... ON DUPLICATE KEY UPDATE.

      Identity, branding and theme5
      • App name & favicon app_name plus a favicon upload (favicon → public/uploads/brand/favicon.{ext}; PNG, ICO, JPG or WebP, checked by contents) with live preview and cache-busting.
      • Primary accent color theme_color via hex input, native picker, or 10 preset swatches.
      • Public home page toggle home_enabled shows/hides the landing page (off redirects to login).
      • Documentation page toggle docs_enabled (admins can still view when disabled).
      • Application timezone app_timezone from the full PHP timezone list (with GMT offsets).
      Localisation and currency0

      The site's Language, the languages members can pick and whether guests get their browser's language (§17). (See §5 for the full multi-currency engine.) Base currency (currency_code/currency_symbol/currency_position) and the visual Region → Currency map editor (currency_map) live here.

        SEO and sharing4
        • SEO meta seo_title and seo_description (150–160 char recommendation).
        • OG locale og_locale (e.g. en_US, ms_MY).
        • OG logo upload og_logo → uploads/brand/og_logo.{ext} (stored as og_logo_path; falls back to favicon).
        • Social sharing banner sharing_banner → uploads/brand/og_banner.{ext} (stored as app_sharing_banner), 1200×630 recommended, with live preview.
        Pixels, server-side events and tracking (three audiences)6
        • Facebook domain verification meta_domain_verification renders the meta tag site-wide; fb_domain_verification_token() extracts the bare code even from a full <meta> tag.
        • Cold audience pixels (Home) Meta Pixel ID/test event/CAPI token (meta_pixel_id_cold, meta_test_event_cold, meta_capi_token_cold) + TikTok equivalents (tiktok_pixel_id_cold, tiktok_test_event_cold, tiktok_access_token_cold) — anonymous PageView/Page for cold traffic.
        • Registered audience pixels (dashboard pages and the plans page) Same fields suffixed _registered, with hashed email and name for matching, sending PageView (Meta) and Page (TikTok). When a buyer's return confirms a plan purchase, the plans page also sends Purchase (Meta) and PlaceAnOrder (TikTok) once, with the order number as the event ID.
        • Paid audience pixels (same pages) Same field set suffixed _paid, gated by meta_pixel_paid_enabled; falls back to registered-audience pixels if disabled/empty.
        • Custom scripts / GTM per stage custom_script_cold/_registered/_paid add GTM or any other script for each audience.
        • IPInfo geo-location token ipinfo_token lets the Traffic page find visitors' countries when the site isn't behind Cloudflare (Cloudflare's CF-IPCountry header comes first; with neither, no visitor address leaves the server).
        Announcement and promo banners2
        • Scrolling announcement banner announcement_enabled plus text, button text/URL, and three colors for a dashboard-wide marquee.
        • Full-page promo modal promo_enabled shows an image popup; upload promo_image (→ uploads/brand/promo_banner.{ext}) with an optional promo_link.
        Sales campaigns and discounts (with billing on)3
        • Scheduled sales campaign campaign_enabled with start/end, message, button, and colors; isCampaignActive() marks the card "LIVE". Campaign duration discounts (campaign_discount_30_89/…/_365) override standard ones.
        • Standard duration discounts discount_enabled plus per-tier percentages (discount_30_89/…/_365).
        • Pricing model selector pricing_model toggles flexible daily pricing (daily_price × days) vs fixed plans; discount/campaign cards hide under the fixed model.
        Billing and payment methods (with billing on)7
        • Billing master switch billing_enabled (off hides checkout, subscriptions, transactions, payouts and commissions, and gives every signed-in user full access).
        • Payment debug mode payment_debug surfaces raw callback data for Stripe and Bayarcash.
        • Stripe gateway gateway_stripe_enabled with live/test key sets (stripe_pk_live/sk_live/webhook_secret_live and _test), a stripe_sandbox toggle, allowed stripe_methods, a copyable webhook URL, and a stripe_portal_url Customer Portal link.
        • Bayarcash gateway gateway_bayarcash_enabled with live/sandbox API token/secret/portal-key sets and a bayarcash_sandbox toggle.
        • Channel toggles bayarcash_channel_{1,12,16,18,21,6,17} for FPX, Credit Card, TNG eWallet, GrabPay, ShopeePay, DuitNow QR, Boost.
        • Added payment methods Each file in payments/ gets its own card with its fields (pay_{id}_{key}) and switch (gateway_{id}_enabled); the Add a payment method button gives the blueprint.
        • Redeemable portals bayarcash_redeem_portals restricts manual redemptions to named portals.
        Affiliate program (with billing on)1
        • Commission/payout config: affiliate_enabled, affiliate_rate_pro/_free, affiliate_payout_day, affiliate_minimum_payout, affiliate_cookies_enabled, affiliate_cookie_duration. (Full program in §6.)
        Install as app (PWA)1
        • pwa_enabled plus pwa_name, pwa_short_name, pwa_description, pwa_theme_color, pwa_bg_color; 192/512 icons and desktop/mobile screenshots. (Runtime behavior in §10.)
        Push notifications (Firebase FCM)1
        • fcm_enabled plus a Service Account JSON upload (config/fcm-auth.json, with a delete action that disables FCM), VAPID public key, and full Firebase web config (fcm_api_key, fcm_project_id, fcm_sender_id, fcm_auth_domain, fcm_storage_bucket, fcm_app_id), with an in-app setup tutorial modal.
        Browser extension1
        • extension_enabled toggles the page/download; app_url is the base injected as the extension's API endpoint; set the brand ext_name/ext_description, the ext_version (latest) and ext_min_version (gate), ext_mirror_link and ext_last_updated (saved, not used yet), and an ext_icon PNG; upload a new build via ext_zip (extracts over /extensions/ext-app/, records ext_last_upload_file/_time). Hidden when extension_hide is set.
        Email and SMTP1
        • mail_mailer (SMTP or PHP mail; seeded SMTP), mail_host, mail_port, mail_username, mail_password, mail_encryption (TLS/SSL/none), mail_from_address, mail_from_name; disable_email_verify; and a live SMTP tester (POST /admin/settings/test-email) that sends using the unsaved form values and returns inline JSON.
        Bot protection1
        • Cloudflare Turnstile: turnstile_enabled, turnstile_site_key, turnstile_secret_key. (Enforcement in §2.)
        Maintenance mode1
        • maintenance_enabled restricts non-admin access; maintenance_until powers a countdown; maintenance_secret defines a secret /login/<secret> admin entry. System-page preview buttons open /admin/preview-page/{403|404|419|500|maintenance}.
        14Admin tools: backups, files, databases and logsDatabase and file backups with a copy sent to S3 or another server, sealed if you like, and a restore button; a file manager with a trash, a SQLite explorer, error and cron logs.Database and file backupsHow backups are madeOffsite copies (S3 and SFTP)Restore, bring back and uploadHosts that disable `exec` or `popen`+4 moreShow all 55Close
        Database and file backups8
        • Backups dashboard GET /admin/backups shows last-run timestamps, "next run in ~" countdowns, stored-file counts, and paginated tables of all DB (.sql) and file (.zip) backups.
        • One-click manual backups "Backup DB Now" / "Backup Files Now" (POST /admin/backups/run with type=db or files) run synchronously and surface the real outcome as a flash.
        • Backups on a schedule triggerIfDue() runs from the dashboard and /run-cron; when an interval has passed it starts the backup script in the background, so no cron job is needed.
        • Configurable intervals Separate DB/files schedules with a number + Hours/Days unit (backup_db_interval_hours/_type, backup_files_interval_days/_type); 0 disables.
        • Retention policy Keeps the newest N per type (backup_db_keep, default 48; backup_files_keep, default 4), auto-pruning older files.
        • Backup exclude list backup_files_exclude (default backups,tmp,node_modules,vendor,.git).
        • App-name-prefixed, timestamped filenames {AppName}_{Y-m-d_H-i-s}.sql/.zip.
        • Download and delete GET /admin/backups/download streams a chosen file and POST /admin/backups/delete removes it (both guarded against path tricks); delete asks first.
        How backups are made6
        • mysqldump when it's there Backups::dumpDatabase() runs mysqldump --single-transaction --routines --no-tablespaces, adding common MySQL install folders, /usr/bin and /usr/local/bin to PATH.
        • PHP fallback When mysqldump is missing or fails, Backups::phpDump() writes the structure and data as .sql over PDO, streamed to disk.
        • Dumps that load on MariaDB Backups::portable() rewrites MySQL 8 collations (utf8mb4_0900_*), so a dump from MySQL 8 also loads on MariaDB 10.4 or newer.
        • Checks Passes the database login through a private temporary file (never on the command line), and refuses to record success for a dump under 32 bytes, deleting it and logging the error.
        • Error log A failed backup, or a failed offsite copy, is written to backups/db/error.log or backups/files/error.log and to the error log, and sends the backup.failed webhook (kind, step, file, error).
        • ZIP archives Recursively zips the project, normalizes separators, and sets Unix file (0644)/dir (0755) attributes. The backups folder is always left out, and so are links that lead outside the project.
        Offsite copies (S3 and SFTP)8
        • A copy of every backup, somewhere else Admin › System › Backups › Offsite copies (POST /admin/backups/offsite). After each backup, scheduled or by hand, services/Offsite.php sends a copy to {folder}/db/ or {folder}/files/. A failed copy never loses the backup: it stays on the server, the page says what failed, and backup.failed is sent.
        • S3-compatible storage Amazon S3, Cloudflare R2, Backblaze B2, Wasabi, DigitalOcean Spaces, MinIO and others, signed with AWS Signature Version 4 in plain PHP (checked against AWS's published examples). Virtual-hosted addresses on Amazon, path-style elsewhere, an endpoint that may carry a path, and http:// only for this machine. Files over 64 MB go up in 16 MB parts, and a part that fails throws the upload away.
        • SFTP Through PHP's curl: a password or a private key (without a passphrase), and the server's SHA256 host key fingerprint pinned, so copies go to that server only. Each copy is written as .part and renamed when complete.
        • Sealed copies With a passphrase (12 characters or more), Backups::seal() encrypts each copy before it leaves: AES-256-GCM in 1 MB chunks, a key from PBKDF2-SHA256 with a random salt, and each chunk's number and "last" flag authenticated, so a copy that was changed, cut short, reordered or added to won't open. Sealed copies end in .enc.
        • Save and test Sends a small file, lists it, reads it back, compares it and deletes it, and names the step and the reason when one fails: a wrong access key or secret, region, bucket, user, password, key or fingerprint, or a server that can't be reached.
        • Keeps the newest there backup_offsite_db_keep (30) and backup_offsite_files_keep (8); older backup files in its db/ and files/ folders are deleted after each copy.
        • Secrets stay hidden The secret, password, private key and passphrase are never shown again; an empty box keeps the saved one, and a tick next to each clears it. The activity log records that they changed, never what to.
        • The last copy, on the page Each kind shows where its last copy went and when, or why it failed (backups/.offsite.json).
        Restore, bring back and upload3
        • Restore button Each database backup has one (GET /admin/backups/restore?file=… asks first). It needs the admin's password (when the account has one) and RESTORE typed, five tries in 15 minutes. It saves the database as it is ({AppName}_before-restore_{date}.sql), drops the tables, reads the backup in with a streaming SQL reader (quotes, comments, /*! */ and DELIMITER handled), applies the migrations the backup is missing (migrations_up()), and clears the settings cache. If the backup fails half-way, the copy saved first is read back in, so nothing changes. Logged as backup.restored.
        • Bring back "See the copies there" (GET /admin/backups?remote=1) lists the offsite copies, newest first, marking sealed ones and ones already on this server; "Bring back" (POST /admin/backups/fetch) downloads one into the server's backups, opened with the saved passphrase or one typed for it. That's how a site moves to a new server.
        • Upload POST /admin/backups/upload adds a .sql backup, or a sealed .sql.enc with its passphrase, under a safe name that never writes over another; a file that isn't a LaunchX database backup (no users and settings tables) is refused.
        Hosts that disable exec or popen4
        • exec()/popen() detection php_function_enabled() checks both function_exists() and php.ini disable_functions; canSpawn() picks popen on Windows vs exec elsewhere.
        • No crash on locked-down hosts On hosts where exec/popen is disabled (aaPanel/shared hosting), triggerIfDue() bails early so the dashboard never fatals, and the manual-run button returns a clear flash error.
        • Warning with fixes An amber banner explains the limitation with copy-paste cron commands and exact aaPanel steps to re-enable exec.
        • OS-aware background spawning runBackground() uses start /B (Windows) and ... > /dev/null 2>&1 & (Linux/cPanel).
        File manager12

        Off unless ADMIN_FILE_TOOLS is true in config.php (default false). When it's on, it asks for the admin's password again every 15 minutes.

        • Browser limited to the project GET /admin/file-manager browses any directory under the project root (folders-first natural sorting, sizes, dates, breadcrumb); every path is realpath-validated to stay inside ROOT_PATH.
        • In-browser code editor GET/POST /admin/file-manager/edit opens text files in a built-in editor (no outside script on a page that can change files on the server): line numbers, Tab and Shift+Tab indent and outdent a line or a selection, Ctrl+S saves, line and column shown, long lines wrap on request, and a warning before leaving with changes not saved. Esc, then Tab, moves keyboard focus on. Files that aren't text (a NUL byte, or not UTF-8, in the first 8 KB) or are over 2 MB don't open, and can't be saved over from it: they're downloaded instead.
        • File upload (drag-and-drop) POST /admin/file-manager/upload with a modal dropzone.
        • File download GET /admin/file-manager/download streams as an attachment with detected MIME (traversal-guarded).
        • Inline media preview Image/audio/video/PDF get an "eye" view button opening in a new tab (rewriting public/ paths to URLs).
        • Rename POST /admin/file-manager/rename via a modal. A name, never a path: it can't contain / or \, nor replace an item that's already there.
        • Trash POST /admin/file-manager/delete moves items to .trash, recording where each came from and when in .trash/.trash_manifest.json (shown in the trash list); move an item back by hand. Name clashes get a numbered name.
        • Permanent delete option A "skip trash" checkbox (and items already in trash) trigger recursive hard deletion with chmod fallbacks.
        • Empty trash POST /admin/file-manager/empty-trash.
        • Bulk operations Select mode with Select-All and a live count; bulk delete, compress (zip), unzip/extract, move, and copy (all root-validated: a zip's name and the folder a zip opens into stay inside the app's folder too). Every change is in the activity log.
        • Conflict pre-check (AJAX) POST /admin/file-manager/check-conflicts returns JSON listing destination filenames that already exist (inspecting ZIP entries for unzip), capped at 50, so the UI can show an "Overwrite All?" modal.
        • SQLite shortcut & refresh .sqlite/.db/.sqlite3 files link into the SQLite Explorer; a refresh button reloads the list.
        SQLite explorer11

        The same ADMIN_FILE_TOOLS switch and password check as the file manager.

        • File picker and file list GET /admin/sqlite-explorer opens any .sqlite/.db/.sqlite3 by path or from an auto-discovered list (bounded recursive scan: max depth 4, skips .trash/.git/vendor/node_modules/backups, caps at 100).
        • Checks safeDbPath() confirms the file is inside ROOT_PATH and is a real SQLite DB (verifies the header), treating a zero-byte DB-extension file as a valid fresh DB.
        • Table & view browser Lists all tables/views (excluding sqlite_*) with row counts and a live filter; counts skipped on very large DBs.
        • Row browser with paging GET /admin/sqlite-explorer/rows returns 50 rows/page; small DBs use numbered offset paging with exact COUNT(*), while DBs ≥100 MB switch to keyset paging.
        • On-demand exact count & column sorting GET /admin/sqlite-explorer/count computes a precise count only on click; rows sort by any real column (validated against the live schema).
        • Add / edit / delete rows POST /admin/sqlite-explorer/row uses prepared statements; addressing via rowid or PK for WITHOUT ROWID tables; views/keyless tables flagged read-only.
        • Explicit NULL handling A per-field NULL toggle maps a __null__ sentinel to SQL NULL; only real columns are accepted on write.
        • Structure tab Each table's CREATE statement and full column metadata.
        • Raw SQL console POST /admin/sqlite-explorer/exec runs arbitrary statements (Ctrl+Enter); SELECT/PRAGMA render in a grid, writes report affected rows; capped at 1000 rows with a "truncated" flag.
        • Large values jsonSafe() turns binaries into [blob, n bytes] and any value over 64 KB into [big] with a 2 KB preview.
        • Waits for locks PRAGMA busy_timeout = 5000; identifiers double-quote-escaped and table names validated against the live schema.
        Error watcher, logging and debug mode0

        (See §1 for the watcher internals.) database/system_errors.sqlite stores every caught issue (level, message, file:line, trace, request URL, timestamp); GET /admin/errors paginates them; POST /admin/errors/clear deletes + VACUUMs; POST /admin/errors/toggle-debug flips database/debug_mode.on; all logging routes through logSystemError().

          Cron activity log3

          All routes above are for admins only (the file manager and SQLite explorer through adminFileToolsMiddleware), and all POST forms carry CSRF tokens verified in dispatch().

          • Cron activity logging logCronActivity() records each job to cron_logs (status, message, execution time, IP, UA, location, job name); backups and manual runs all log here.
          • Viewer & clear GET /admin/cron-logs (paginated, newest-first) proves jobs ran and from where; POST /admin/cron-logs/clear truncates the table.
          • Run-cron address GET /run-cron (with ?key= when CRON_SECRET is set) is the address to call from cron; it also runs due backups.
          15API and webhooksA versioned JSON API with scoped keys and rate limits, and signed webhooks that retry.OverviewShow all 5Close

          The full reference, with examples, is API.md.

          Overview5
          • Turned on by the admin Admin > Developer switches the API on; each member then makes their own keys on their profile: read, write, or admin (admins only), expiring in 30, 90 or 365 days, or never.
          • Members' endpoints /api/v1/me: the account, subscription, payments, orders, invoices, notifications and support tickets (open a ticket, reply).
          • Admin endpoints Statistics, users (list, create, change, delete), payments, orders, invoices, tickets and broadcast notifications, with an admin key, which stops working the moment its owner is no longer an admin, and acts as a write key while the site requires two-step sign-in for admins and its owner hasn't turned it on.
          • Safe by default A key is shown once and only its SHA-256 hash is kept; requests are rate-limited per key (120 a minute by default); lists are paged; errors come back as JSON with a stable code. Admin > Developer lists the 200 most recently used keys with when and from where it was last used, and can revoke any.
          • Webhooks Signed with HMAC-SHA256 (X-LaunchX-Signature), sent for sign-ups, deleted accounts, payments, failed renewals, free trials, refunds, expired subscriptions, store orders and their refunds, invoices, new support tickets, and people joining or leaving a team, and tried again 1 minute, 5 minutes, 30 minutes, 2 hours and 12 hours later when your address doesn't answer 2xx. The last 25 deliveries are shown in the admin, and ones that weren't delivered can be sent again.
          16Explore pageCards that point your members to your other products.OverviewShow all 3Close
          Overview3
          • Cards for your other products GET /explore ("Explore more" in the member menu, for every signed-in member; no on/off setting) shows cards with a name, description, link, icon and sharing image, by sort then newest first.
          • Managed on the page Admins add and edit cards with Add SaaS (POST /explore/save; name and link required, https:// added when missing) and delete them with their images (POST /explore/delete/{id}). Images (PNG, JPG, WebP or GIF, checked by contents) are saved in public/uploads/explore/.
          • Hidden cards Cards not marked "Visible to users" are shown only to admins, with a "Hidden" badge. Cards are stored in explore_items (migration 003_explore_items.php).
          17LanguagesEvery member page, checkout and email in each customer's own language. English and Malay built in; another language is one file.OverviewShow all 12Close
          Overview12
          • Every member page in the member's language The member area, sign-in and sign-up, the plan, team and invoice pages, the store and checkout, the affiliate area, support, notices, error pages and the messages members see. English and Bahasa Melayu (Malaysia) come with it. The admin panel stays in English.
          • A language per member Members pick theirs under Language on their profile or from the globe menu in the top bar. It's saved on their account (users.locale), so it follows them to every device. An admin signed in as a member can read the pages in another language for that visit without changing the member's choice.
          • Guests The globe menu works signed out too (kept in a lang cookie for a year). ?lang=ms on any address opens the site in that language, for ads and links aimed at one audience. A first visit gets the language the browser asks for when the site offers it (a setting, on by default). Someone who signs up keeps the language they were using.
          • The admin's choice Settings › Identity and theme › Region: the Language guests and new members get first, the Languages members can pick, and whether to follow the browser's language. With one language offered, the menu and the profile field don't show.
          • Emails in each language Every email template can have a copy in each language (Admin › Emails, one tab per language, with its own test send). A member gets the copy in their language, or the main email when there's none; a guest buying in the store, or someone invited to a team, gets the language of the page it was sent from. Dates in the email follow the same language, cron emails included. Malay copies of the nine shipped emails come with it; a template you had already rewritten gets none, so your text is never replaced.
          • Dates Month and day names follow the language (3 Dis 2026, Ahad), in the member's time zone as before.
          • A new language is one file Copy lang/ms.php to lang/<code>.php (fr, de, pt-BR…), set its name and month names, and translate each line: 'English text' => 'translation'. It appears in Settings at once. php scripts/lang.php <code> lists the lines still missing and the ones no page uses any more, ready to paste; php scripts/lang.php --check fails when any language is missing a line. A missing line shows in English, so a language that's half done never breaks a page. Right-to-left languages set 'dir' => 'rtl'.
          • For developers t('Text with {name}', ['name' => $v]) gives plain text, te() the same escaped for HTML, th() escaped text with HTML in its placeholders (a link, bold text), tn() one or many, with_locale($code, fn) runs code in another language (an email to someone else), current_locale() is this request's language. The key is the English text itself, so templates stay readable. <html lang>, dir and og:locale follow the page's language.
          • API and webhooks /me has locale; PATCH /me changes it. The user data in webhooks has locale.
          • Invoices The invoice page follows the member's language like every other page. The downloadable PDF uses the fonts built into every PDF reader, which cover languages written in Latin letters (English, Malay, French, German, Spanish…); for other scripts, the invoice page's Print button saves the same invoice as a PDF with every letter intact.
          • Fits any language The top bar keeps its buttons on one line on a phone, however long the words get in a language; a long app name shortens instead.
          • Light A language is a plain PHP array that OPcache keeps in memory: no database lookups and no files to parse on each page.

          Nothing matches that. Try another word, such as "payment" or "admin".

          The same list on GitHub: docs/FEATURES.md · the API: docs/API.md

          12 Under the hood

          Code you can read in an afternoon.

          A small router, controllers and PHP templates. No container, no generated code, nothing you have to take on faith.

          public/index.php
          every request starts here
          routes.php
          get('/pricing', [HomeController::class, 'pricing'])
          controllers/
          one class per area: auth, billing, store, admin…
          views/
          plain PHP templates
          services/
          payments, tax, invoices, webhooks…
          payments/
          add a payment provider: one file
          database/migrations/
          numbered, applied by php migrate.php
          helpers.php
          auth(), setting(), url(), format_currency()…
          tests/run.php
          959 end-to-end tests
          AGENTS.md
          the house rules, for people and agents
          One way throughEvery request goes through the same front controller, so sign-in, CSRF, currency and error handling apply everywhere.
          Updates that don't break thingsgit pull, then php migrate.php. Settings create themselves, and uploads live outside the code.
          Tested like a browser wouldThe tests sign up, pay, sign in through a test identity provider, use the API and click through the admin panel against a running copy.
          Safe by defaultPrepared statements, CSRF on every form, hashed API keys, rate limits, and sessions that end when a password changes.
          $ curl https://yourapp.com/api/v1/me -H "Authorization: Bearer lx_your_key"
          {"data": {"id": 42, "name": "Ana Silva", "currency": "EUR",
                    "subscription": {"active": true, "plan": {"id": 2, "name": "Pro"}, "days_left": 30}}}
          13 The free stack

          From your laptop to your own server, without paying anyone.

          LaunchX is one of three free, open-source projects that fit together.

          1Build

          OWN DevKit

          A free, portable local web development environment for Windows. Add the LaunchX folder and it's running at launch-x.localhost.

          See OWN DevKit →
          2Start

          LaunchX

          A finished foundation: accounts, billing, invoices, a store, an admin panel and an API.

          Get the code →
          3Run

          Project OWN (Open Web Node)

          A free control panel for your own Linux server: the site, the database, HTTPS, backups and deploys from Git.

          See Project OWN →
          14 Ignition

          Running in five minutes.

          You need PHP 8.1 or newer and MySQL 8 or MariaDB 10.4 or newer. Nothing to install with a package manager.

          T−3

          Get the code

          Clone it, or download the latest release as a zip.

          git clone https://github.com/zaimzamzuri/launch-x.gitcd launch-x
          T−2

          Set it up

          Add your database details to config.php, then make the tables, the defaults and your admin account.

          cp config.example.php config.phpphp migrate.phpphp seed.phpphp create-admin.php
          T−1

          Put it online

          Point your web server at the public folder, add the hourly task, and sign in. The deploy guide covers Nginx, Apache and Project OWN.

          # the hourly task, with CRON_SECRET from config.phpcurl -s "https://app.example.com/run-cron?key=YOUR_CRON_SECRET"

          No account ever ships with a known password. Updating is git pull then php migrate.php. Full guide: docs/DEPLOY.md.

          ? Questions

          Questions people ask.

          Is LaunchX really free, for a paid product too?

          Yes. LaunchX is under the MIT licence: use it for a commercial product, change it, and keep your changes private. Keep the licence notice in the code, and that's it.

          Do I need Composer, npm or a build step?

          No. It's plain PHP, HTML, CSS and JavaScript with no framework. Copy the files to a server, run three commands, and it works.

          Does it run on cheap or shared hosting?

          Yes. It needs PHP 8.1 or newer and MySQL 8 or MariaDB 10.4 or newer, and it keeps working on hosts that turn off exec and popen or have no mysqldump.

          Which payment providers does it support?

          Stripe (cards, wallets and local methods, one-time or recurring) and Bayarcash for FPX in Malaysia are built in. Any other provider is one PHP file in payments/.

          Can my users sign in with Google, GitHub or their company account?

          Yes. Turn on the ones you want: Google, GitHub, Microsoft, Apple, Facebook, or any OpenID Connect single sign-on such as Okta, Auth0 or Keycloak. Only those show on the sign-in page.

          Can people install my product like an app, and get push notifications?

          Yes. Turn on Install as app, and people add it to their phone or computer from the browser, with your name, icon and colours, and no app store. Turn on push, and you send notifications from the admin panel to the members you pick, through Firebase Cloud Messaging, which doesn't charge for messages. On iPhone and iPad, push works once the app is on the home screen (iOS 16.4 or newer).

          Can members sign in without a password?

          Yes. Members add a passkey on their profile, then sign in with their face, fingerprint or device PIN: nothing to type, and nothing a fake sign-in page can catch. It counts as both steps of two-step sign-in. Passwords, Google and the other providers keep working alongside. Browsers offer passkeys on https sites with a domain name.

          Can I send newsletters and win-back emails?

          Yes. Admin › Broadcast sends one message to members' inbox, as a push notification and by email: to everyone, paying or free members, narrowed by plan, language, country or how long since their last visit. Emails go out from your own mail server in the background, in each member's language, at a pace you set, and every one has an unsubscribe link and the one-click unsubscribe button Gmail and Yahoo ask for. Members can turn news off on their profile; receipts and password resets still reach them.

          Can each plan include different amounts, like 300 exports a month?

          Yes. List what each plan includes under Admin › Plans › Limits: a number each month, a number in all, or a feature that's on or off. Plan cards show it, members get a Usage page with a meter for each, and at the limit they see a page that offers your plans. In your code it's one line: usage_try('exports').

          Can my app be in my customers' language?

          Yes. Member pages, the store, checkout and emails come in each member's language, picked from a menu or their profile and kept on their account. English and Bahasa Melayu are built in, guests get their browser's language or a ?lang= link, and you add another language by translating one file.

          What happens when a member changes plans?

          The days they paid for and haven't used come off the new plan's price, counted to the second. They pay the difference and the new plan starts that day, or, when the unused days are worth more, the switch is free and they get the extra days. Plans that renew with Stripe switch through Stripe, which shows the charge first. Trial days, gifted days and what a code paid for count for nothing, so a credit is never more than was paid.

          What if my server is lost or hacked?

          Turn on offsite copies under Admin › System › Backups, and every backup also goes to S3-compatible storage (Amazon S3, Cloudflare R2, Backblaze B2 and others) or another server over SFTP, sealed with a passphrase if you like. On a new server, install LaunchX, connect the same storage, bring back the newest copy and press Restore: every member, payment and setting comes back as of that backup.

          Do I need Google Analytics or another analytics service?

          Not to see who visits your home page. The Traffic page shows visitors, countries, languages, devices, browsers, referrers and the busiest hours, counted on your own server. To use an analytics or ad service as well, add its script, or Google Tag Manager, for each audience in the settings.

          Can an AI coding agent work on it?

          Yes. AGENTS.md explains how a request flows, where the helpers are and the house rules, and the end-to-end tests check the result. It's plain PHP, so there are no framework conventions to guess.

          Does it send data anywhere?

          No. Out of the box no page loads anything from another server and nothing is reported back. Services you choose to turn on, such as Stripe, Cloudflare Turnstile, Firebase push or ad pixels, load their own code only then.

          Is it ready for real customers?

          It runs end to end, and 959 automated tests drive it like a browser before every release. It hasn't had an outside security review yet: read the code that handles money, try your payment setup in sandbox mode first, and report anything you find privately (see SECURITY.md).

          Your product is the part that's left.

          Everything else is ready: free, fast, and yours to change.