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.
on the server (median)
a typical page
audit or lose
before every release
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.
- T−12Sign-in, passkeys, SSO, two-stepSTBYGO
- T−11Bot protection, rate limits, CSRFSTBYGO
- T−10Plans, limits, team seats, free trialsSTBYGO
- T−09Stripe, Bayarcash, any provider in one fileSTBYGO
- T−08Invoices and tax by countrySTBYGO
- T−07Every currency, every languageSTBYGO
- T−06A store with guest checkoutSTBYGO
- T−05Affiliates, discount codes, sales campaignsSTBYGO
- T−04Install as an app, free push, email broadcastsSTBYGO
- T−03SEO, pixels, server-side events, trafficSTBYGO
- T−02Admin, tickets, backups, activity logSTBYGO
- T−01REST API and signed webhooksSTBYGO
- 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.
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.
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
Templates, e-books and courses, sold from one page
Your audience is ready to buy. Send them to a page that sells, takes the money and delivers, with no account to make first.
You build
The things you sell.
LaunchX handles
- Sales pages with their own checkout, made in the admin panel
- Guest checkout: buyers need no account
- The download link or message, delivered the moment they pay
- Offers, badges, quantities and discount codes
- Meta and TikTok pixels, with server-side purchase events
A branded app for each client
Every client wants their own portal or tool. Start each one from the same tested base, and spend the budget on what makes theirs different.
You build
What each client's business needs.
LaunchX handles
- Their name, logo, colours and domain
- Legal pages, cookie consent and SEO settings
- Email from their own SMTP server, with templates they edit
- An admin panel they can run themselves
- The MIT licence, so you can build and sell it
Software sold to companies
Business buyers ask the same questions: can we sign in with our own accounts, do we get proper invoices, who changed what?
You build
The workflow your customers pay for.
LaunchX handles
- Sign-in through the customer's own SSO: Okta, Auth0, Keycloak or any OpenID Connect
- Passkeys for everyone, and two-step sign-in required for admins if you like
- Invoices with the company's name and tax ID, and reverse charge abroad
- An activity log of who changed what
- An API with signed webhooks for their own tools
A browser extension with a paid plan
The extension is the product, but it still needs accounts, plans, payments and a website. LaunchX comes with a starter extension that's already connected.
You build
What the extension does on the page.
LaunchX handles
- A starter Chrome side-panel extension that signs in with your site's accounts
- A check for an active plan before it opens
- A minimum version, so old copies ask to update
- Downloads that carry your branding
- The website, plans and payments behind it
A SaaS priced for Malaysia and the world
Local customers pay by FPX in ringgit. Everyone else pays by card in their own currency. Both work on day one.
You build
The product.
LaunchX handles
- FPX and Malaysian bank payments through Bayarcash
- Stripe for cards and wallets everywhere else
- Each customer's currency, set by where they sign up
- Prices you set for each currency, never a rough conversion
- SST for Malaysia, VAT or GST elsewhere, on every invoice
A paid membership
Members pay to get in, and you keep in touch with them. LaunchX runs the paying and the talking; you bring what they come for.
You build
Your lessons, videos or community.
LaunchX handles
- Monthly or yearly plans, or pay by the day
- A member dashboard with their plan and payments
- Announcements, web push and an in-app inbox
- Support tickets you answer from the admin panel
- An app members install on their phone
Your first real SaaS, understood
Tutorials stop at the login form. LaunchX shows how a whole product fits together, in plain PHP you can read without learning a framework first.
You build
Your skills, then your own product.
LaunchX shows you
- Routing, sessions and security, with nothing hidden
- How real payments, refunds and webhooks are handled
- Numbered database migrations
- 959 end-to-end tests to learn from
- AGENTS.md, so an AI assistant can explain any part
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.
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).
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.
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.
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=mson 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.
- Dashboard
- Subscription
- Team
- Support
Good morning, Aisha
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.
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/mygives that member ringgit prices - In their language: add
?lang=msto an ad and the site opens in Malay - Pixels on the home page for Meta and TikTok ads that reach new people
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
They buy
- Discount links: send
?code=SAVE20and 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
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
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
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.
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.
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.
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.
- MMaya Lindqvistmaya@studio.exampleOWNER
- TTheo Parktheo@studio.exampleACCESS
- PPriya Nairpriya@studio.exampleACCESS
Invite someone: they join with their own account.
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.
- 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.
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.
- 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.
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.
- Day 0The renewal failsThey keep access for a grace period, 7 days by default, and get an email with a link to pay.
- Days 0 to 7Stripe tries againTheir plan page says the payment didn't go through, with an Update payment button.
- Day 4A reminderA second email, about three days before the grace period ends.
- PaidBack on trackThe new period starts from the day they'd paid up to: no days lost, none given away.
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.
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.
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.
- Password typed
- None
- Two-step code
- Not needed
- If your database leaks
- Public keys only
Aisha added a passkey on her phone last week. Press the button to sign in as her.
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.failedwebhook tells your monitoring.
- Install LaunchX on a new server
- Connect the same bucket: Save and test passes
- Bring back the 14:00 backup, opened with the passphrase
- Restore: type RESTORE, and it's back
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.
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.
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.
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 { … } }
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.
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.
- YOUAdd Paddle as a payment method.
- READS
AGENTS.mdand.agents/rules/payment-gateways.md - WRITES
payments/PaddleGateway.php: one file, nothing else changes - CHECKS
php -l, then thepaymentstest group - DONEPaddle shows up in checkout and in the admin panel, with its own settings
Before you change anything, read AGENTS.md and follow the rules in /.agents/rules/*.md.
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 admin's view of the business: sign-ins, paying users, revenue and payouts, with a chart drawn without a chart library.
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, andrequires 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 asget($uri, [Controller::class, 'method'], $middleware = [])(andpost()), stored in a global$routesarray 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 likeuser/{id}orsupport/{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 forroleMiddleware('Admin')). index.php-prefix stripping The router strips a leadingindex.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 thesettingstable 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 fromviews/,extract()ing$datainto local variables (and injecting the view name as$view).url($path)/redirect($url)Build absolute URLs fromBASE_URL(passing through already-absolute links) and issue header redirects withexit.- Shared master layout
views/layout.phpis 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 withob_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-canvasbody mode that suppresses navbar/footer for full-width pages. - Per-page SEO override Store pages can pass a
$seoarray (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 plainError 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.phpregistersset_error_handlerandset_exception_handlerthat funnel everything intologSystemError(); in debug mode they render full stack traces, otherwise a clean 500.dispatch()also wraps routing in a try/catch that logsCriticalerrors. - Maintenance mode When
maintenance_enabledis 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}, defaultadmin-access), the two-step sign-in step, sign-out, and Bayarcash'ssubscription/callbackandsubscription/webhookstay reachable; other addresses send visitors to the home page, including the Stripe webhook, the store's payment addresses,/pay/{id}/notifyand/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_enabledis on) and a closing call to action, all in the theme from settings. - Home toggle If
home_enabledisn't1, 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'sCF-IPCountryheader, or (only whenipinfo_tokenis 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_enabledisn't1, 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-cronOne address runs every scheduled job: affiliate payouts (checkAndGeneratePayouts), backups (BackupController::triggerIfDue), plan expiry emails and thesubscription.expiredwebhook (SubscriptionController::checkExpirations; it doesn't take access away), and webhook retries (Webhooks::retryDue). It answers with a JSON status and logs the run. WhenCRON_SECRETis set inconfig.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) tocron_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 todatabase/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 toerror_logif the watcher is absent); the codebase rule is to always log via this.- File-flag Debug Mode A
database/debug_mode.onflag 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.inidisable_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 fromdatabase/migrations/, tracking each in amigrationstable with batch numbers (auto-creating the table on first run). The only way to change the schema. - Migration rollback
php migrate.php rollbackreverses the most recent batch via each migration'sdown()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 indatabase/seeders/, each a class withrun($pdo), to fill in system data (email templates, settings, plans). No accounts are seeded:create-admin.phpmakes the first admin. - Self-creating database (
db()) Returns a cached PDO connection; if the DB doesn't exist (error 1049) itCREATE 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_timezoneand 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 /registerasks for name, email, phone and password, then signs the person in or sends them to email verification. The phone is optional by default;signup_phonemakes 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) viacurrency_for_region(), persistingcurrency_code,currency_symbol, andcurrency_positiononto 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/registerdrops 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 byphone_e164(). - Affiliate referral attribution at signup A referral tag is read from
?i=or theaff_tagcookie into a hiddenaffiliate_tagfield; a match sets the new account'saffiliate_idto 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.
Email verification (code and link)6
- A 6-digit code and a link Sign-up emails both (
email_verificationtemplate); the database keeps only a SHA-256 hash of the link's token. Both expire after 30 minutes, and the code allows 5 tries. - One-click link verification
GET /verify/{token}stampsemail_verified_at, clears the token/OTP, logs the user in, and redirects to the dashboard. - OTP code verification
POST /verify-otpchecks the entered code, verifying and logging the user in on match. - Verification notice page
GET /verify-notice?email=...presents the OTP box, resend button, and back-to-login link (logged-in users are redirected away). - Resend verification code
POST /resend-verificationmakes a new link and code for an account that isn't verified yet (3 per address per 15 minutes). - Login blocked until verified Sign-in checks
email_verified_at; an unverified user sees a "Please verify your email" error with an inline "Verify Now" link (unless verification is globally disabled).
Sign-in, sessions and remember me6
- Email + password login
GET/POST /loginverifies credentials withpassword_verify()against the bcrypt hash and starts a session vialoginUser(). - Last-login tracking
loginUser()recordslast_login_aton 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:validatorcookie (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$secretsegment (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 toGET/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/loginanswerstwo_step_requireduntil acodeis 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_addedemail (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_atis 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_handleis 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-passwordemails a reset link (forgot_passwordtemplate) 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 whosereset_expiresis 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_urlfield; a submission that fills it is blocked with a 403. - Time-trap detection
register_start_timeis 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_enabledis on (with site + secret keys), login and registration render the Turnstile widget and validatecf-turnstile-responseserver-side viaverify_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_csrftoken (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/logoutandpay/{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
BaseModeland inlinedb()->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 asroleMiddleware('Admin'). - Role & entitlement helpers
hasRole($roles)checks roles;isPro()andhasExtension()gate pro features byexpires_at/extensionflag; whenbilling_enabledis 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_enabledandaffiliate_enabledare 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 theuser.deletedwebhook. 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 asauto:Zoneinusers.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-tokenupserts the device's FCM token intopush_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-tokenremoves 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 markeroriginal_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
BaseModelgivesUserfind($id),where($col,$op,$val),create($data), andall()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
flexiblemode (a daily-rate slider) orfixedmode (admin-defined packages), switched bypricing_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_pricecomputed 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 bydiscount_enabled, shown as "-X%" bubbles on the slider.
Fixed plans (admin)4
- Plans list dashboard
GET /admin/plansshows 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}, andPOST /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 legacyamountcolumn 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_valueoverrides 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=1and the current time is betweencampaign_startandcampaign_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=SAVE20puts it in. - In the store The checkout box has a code field.
POST /store/couponanswers with the new lines and total before paying, and a link with?code=SAVE20on 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 (gatewaycoupon), with no payment page. - Counted when paid A use is recorded in
coupon_redemptionsonce 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/trialgives the plan's access for the trial days with no card, and records a payment with statustrialand an amount of 0 (order numberTRIAL-…). It sends thetrial.startedwebhook. - 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_endingabout 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 tograce_fromcount. - 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 inmeta. 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.changedwebhook withfrom,to,credit,paid,access_untilandvia(checkoutorstripe). - 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/changemoves the subscription's item to the new plan'sstripe_price_idwithproration_behavior=always_invoiceandpayment_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.paidwith billing reasonsubscription_updaterecords 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, andcustomer.subscription.updatedfollows 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 asclient_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 fromstripe_methodsand are passed aspayment_method_types. - Success landing + verification
stripeSuccess()calls the Stripe API to confirmpayment_status === paidbefore granting access (not trusting the redirect). - Webhook with signature verification
stripeWebhook()HMAC-verifies theStripe-Signatureheader before processing, returning 400 on bad signatures and 500 (for retry) on transient errors. - Event routing Handles
checkout.session.completed(one-time subs, StoreORD-orders, recurring Payment Links),invoice.paid(renewals, and plan changes made through Stripe),invoice.payment_failed(the grace period),customer.subscription.updatedandcustomer.subscription.deleted(cancelled, resumed, ended or moved to another price in Stripe), andcharge.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 aclient_reference_idof{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 firstsubscription_createinvoice and extends access on each subsequent renewal; asubscription_updateinvoice (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 UNIQUEstripe_invoice_id/order_number; a duplicate webhook trips error 1062 and is treated as already-processed. - Race-free expiry extension Renewals extend
expires_atatomically viaDATE_ADD(GREATEST(COALESCE(expires_at,NOW()),NOW()), …). - Missing duration A recurring plan with no
duration_daysdefaults to 30 days and logs a warning. - Manual "Check my payment" fallback
POST /subscription/recheckre-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/billingmakes 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 instripe_portal_urlinstead, if one is set (https only). - Refunds and chargebacks (Stripe) On
charge.refunded(full refunds only) orcharge.dispute.created, the payment is found by its invoice (recurring plans) or by its payment intent (paid once, kept asstripe_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, andorder.refundedis sent. Refunds made through Bayarcash or an added payment method aren't followed. - Stripe campaign promo codes A plan's
stripe_promo_codeis auto-appended to the Payment Link asprefilled_promo_codeduring a live campaign, with a "PROMO AT CHECKOUT" badge. - Recurring tracking A per-plan
recurring_trackingswitch: 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_failedof a period, the member keeps access forbilling_grace_daysmore days (7 by default, 0–60, Settings › Pricing) while Stripe tries again. The date their paid access really ended is kept inusers.grace_from, and the failure inpayment_failed_at. - Emails Once per failed period,
payment_failedwith 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 sendspayment_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.paidcounts the new period fromgrace_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_renewfollows 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 thepayment.failedwebhook; 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 viabayarcash_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, replying200 OKafter 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 (forcs_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 extendsPaymentGateway(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.
Redeeming payment-link purchases4
- Redeem-by-order-number
POST /subscription/redeemlets members who bought through a Bayarcash payment link ("BCL") redeem by entering their original order number, verified against Bayarcash and granted instantly. - Anti-duplicate & ownership checks Blocks already-recorded order numbers, requires gateway status paid (3), and requires the gateway payer email to match the logged-in user.
- Portal list Only purchases from the portals listed in
bayarcash_redeem_portalscount. Redeeming shows only when portals are listed, billing and lifetime extension (extension_enabled) are on, and Bayarcash keys are set. - Redeem grants lifetime extension Sets
extension = 1, adds to LTV, and records aMYR"Extension Lifetime (Redeemed)" subscription row with the full payload inmeta.
Access, expiry and history6
- Idempotent grant with double-processing guard
updateSubscription()ignores already-paidorders; on payment it extendsexpires_at, setsplan_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 viaexpiry_notice_sent_at/expired_notice_sent_at. The warning istrial_endingduring a free trial,payment_retry_reminderafter a failed renewal, andplan_expiry_warningotherwise. 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/plansgivesseats. - 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/invitesends theteam_inviteemail 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_idis 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 withPOST /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_joinedandteam.member_left(withby:memberorowner);/api/v1/megivessubscription.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. Tablesplan_limits,plan_limit_valuesandusage_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; 402limit_reachedpast it) andsupport_tickets(the new-ticket form andPOST /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_reachedemail template (English and Malay copies included, in the member's language) and theusage.limit_reachedwebhook, 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,GETandPOST /admin/users/{id}/usage(try,add,set), andlimitson each plan inGET /plans.
What happens on every payment3
- Server-side purchase events Each paid transaction sends Meta
Purchaseand TikTokPlaceAnOrderserver-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 byaffiliate_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_enabledis 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 theinvoice.issuedwebhook. - 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=1to 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/exportdownloads 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, withtax_plansandtax_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, namedtax_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_chargeon, 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/quoteworks 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 (migration013_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 withregion,code,symbol,position,enabled, andis_default. Decoded and cached per-request byget_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 whereform.submit()wiped the saved map). - Default currency
default_currency()returns theis_defaultenabled row, else the first enabled row, else the global currency. - Global currency, the last fallback
global_currency()reads the oldercurrency_code(defaultUSD),currency_symbol($) andcurrency_position(prefix). - Currency normalization
normalize_currency()standardizes any row to uppercasecode, asymbol, and a validatedposition(anything notpostfixbecomesprefix).
Each member's currency, set at registration5
- Region-tagged signup URLs
GET|POST /register/{region}ties a new account to the region's currency viacurrency_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
userstable, 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'spricesJSON for the requested currency, falling back to the legacyamount. - 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 postsprices[CODE]values. - Per-product / per-page pricing with sale offers
StoreController::itemView()reads each product'spricesandoffersJSON 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 viaplan_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-currencyand re-renders all prices, showing each option asCODE (symbol). - Set-currency endpoint
POST /store/set-currencyvalidates 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()honorsstore_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 todefault_currency(); the chosen code is persisted on theordersrow.
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 storedcurrency_codealways 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 increateCheckoutSession(). - 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_codeusing 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
subscriptionsandordersrow 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.
Affiliate links and tags5
- Custom affiliate link / vanity tag Each member picks a referral tag (e.g.
?i=my-name) onPOST /affiliate; validated against^[a-zA-Z0-9_-]+$and checked for uniqueness, stored onusers.affiliate_tag. - Link with a copy button The dashboard renders the full referral URL (
{site}/?i={tag}) and a Copy button. - Click tracking via
?i=handleAffiliateTracking()validates the tag against real users and drops anaff_tagcookie surviving until signup. - Configurable cookie attribution window Controlled by
affiliate_cookies_enabledandaffiliate_cookie_duration(days; seeded 7, 30 if unset; cookies are seeded off); when off the cookie is session-only and cleared on visits without a tag. - Referral captured at signup Registration resolves the tag to the referrer's user ID and permanently stamps
affiliate_id.
Commission rates and earnings6
- Two commission-rate tiers Paid ("Pro") affiliates earn
affiliate_rate_pro(default 30%), free onesaffiliate_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 asource_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_idequals 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.createdfor an invoiced charge,handleStripeRefundOrDispute()revokes access and deletes the matching unpaid commission (matched viasource_invoice_id, only wherepayout_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/payoutswith 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 aprocessingpayout in that currency, snapshots bank details, links the earnings, and logs the run (guarded by alast_payout_runmonth 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) andaffiliate_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_pagesanswer at/{prefix}/{slug}; the prefix isstore_page_prefix(defaultp), and a blank prefix serves them at/{slug}. Unpublished pages give a 404. - HTML content A page's
contentis output as HTML, for sales, landing or legal pages. - Full-width pages Pages with
full_canvasdrop 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_itemsJSON) 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/checkouttakes 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/couponfor 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-######-YYMMDDnumber and a random 32-charactertokenfor its thank-you page. - Pending until confirmed Orders are saved as
pendingand becomepaidonly when the payment is confirmed.
Tax, shipping and fees4
- Tax Tax by country (see §4), while
tax_enabledandtax_storeare on: on every item on a sales page, and on products marked "Add store tax". - Payment fee When
store_fee_enabledis on,store_fee_percent% of the subtotal plus tax, plus a fixedstore_fee_fixedamount per currency, namedstore_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 (
downloadortext). 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
keystakes one unused key fromproduct_keysper sale (a single-rowUPDATE ... 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_descriptionandog_image, whichlayout.phpuses instead of the site-wide ones. - Pixels of its own Each page has its own
meta_pixel_idandtiktok_pixel_id, separate from the site-wide pixels. They load only for visitors who may be tracked. - Events
PageView, andViewContentwhen the page has a checkout;InitiateCheckoutwhen the checkout box loads and each time a quantity changes;Purchase(Meta) andCompletePayment(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
Purchaseand TikTokCompletePaymentare sent with the page'smeta_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 /storelists active products as cards (name and price in the visitor's currency), bysortthen 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 checkspayment_status=paidbefore completing the order. - Bayarcash The buyer comes back to
GET|POST /store/callback, and the server notification arrives atPOST /store/webhook; both check the signature. - Added payment methods Use
/pay/{id}/returnand/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()usesUPDATE ... WHERE status<>'paid'in a transaction, so only one caller marks the order paid, and delivery, the email, the purchase events and theorder.paidwebhook happen once. - Payment ID The payment service's ID is saved with the order.
Order confirmation email1
- Sent on payment The
order_confirmationtemplate 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/pageslists 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}, andPOST /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/previewrenders 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/orderspaginates (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/exportwith 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/settingsupserts to thesettingstable. - Store enable + currency switcher
store_enabledandstore_currency_switcher. - Custom page URL prefix
store_page_prefix(defaultp); 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-currencystore_fee_fixed. - Per-currency shipping fee
store_shipping_feeper 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 canonicalamountand 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/productswith 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/logintakes 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 inapi_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/sessionre-validates a stored token on every load (token viaAuthorization: Bearer,X-Auth-Token, or atokenquery param), bumpinglast_used_at; invalid/missing tokens return401. - Logout
POST /api/extension/logoutdeletes 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 answersOPTIONSpreflights. 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 a401JSON 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, whenusers.extension = 1(lifetime extension access), or whileexpires_atis 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 againstext_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) andversion(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 whenextension_enabledis 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) tobackground.jsandsidebar.js. - Dynamic manifest rewriting Sets the version, sets the extension name and description from settings, and appends the SaaS host to
host_permissionsso each deployment's build is unique. - Admin icon override An
ext_iconPNG upload replaces the bundledicon.pngin the build. - New builds without redeploying Admins upload a new build as a ZIP (
ext_zip), unpacked over/extensions/ext-app/.ext_versionsets the version;ext_last_updatedandext_mirror_linkare 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.localfor 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'smail(), chosen bymail_mailer(seededsmtp; PHPmail()only when the setting is missing); all emails aretext/html. - Own SMTP client (no Composer or PHPMailer) Opens a raw socket to
mail_host:mail_portand 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(tlsvia STARTTLS,sslviassl://), working with Gmail/SES/Mailgun on 587 or 465. - Optional SMTP auth Sends base64
AUTH LOGINwhenmail_usernameis set, unauthenticated when blank. - Per-call config override Accepts a
$configarray 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") andmail_from_address, with proper headers. - Errors returned Returns
trueor 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 fromemail_templates, substitutes{{placeholder}}tokens in subject + body, and sends. Slugs includeemail_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
$datakey 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) viapopen, 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
popenis disabled (common on aaPanel/shared hosting), it sends right away instead viaphp_function_enabled('popen'). - Background templated send
send_template_mail_bg()resolves template + placeholders in-request, then hands off tosend_mail_bg(). - Standalone CLI mailer worker
scripts/mailer.php(web-SAPI-refusing) loads the app, reads the message from thetmp/mail_*.jsonfile named on its command line, sends it and deletes the file.
Email log2
- Every email logged
send_mail()records every send (success/failure) intoemail_logswith recipient, subject, template slug, status, and exact error. - Admin email log viewer
GET /admin/emailslists 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_enabledis off;email_verificationwhendisable_email_verifyis 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_usernameare 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.phpis 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-throughlink(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-tokenupserts (withON DUPLICATE KEY UPDATEownership swap);POST /fcm/delete-tokenremoves one or all. - Client-side token lifecycle When
fcm_enabled+ a VAPID key are set,layout.phploads the Firebase compat SDK, initializes from admin config, callsgetToken, and POSTs the token — only re-sending when it changes or is older than 7 days. - Foreground message display
messaging.onMessageshows a nativeNotificationfor focused-tab pushes. - Stale token auto-cleanup After a broadcast, tokens returning
UNREGISTERED/INVALID_ARGUMENTare 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, elseusers.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/reachreturns 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/testemails the admin a "[Test]" copy. - Background sending Emails are queued in
broadcast_outboxand sent byscripts/broadcast.php(started withpopen, like the mailer), atbroadcast_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. Wherepopenis off, the cron job sends them, and so doesPOST /admin/notifications/progress, which the open Broadcast page calls to show progress. - The email The
broadcasttemplate (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-UnsubscribeandList-Unsubscribe-Post: List-Unsubscribe=One-Clickheaders give mail programs their unsubscribe button. - Unsubscribing
GET /unsubscribe/{token}asks first (mail scanners open links);POSTto 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 withPATCH /api/v1/me. - The sign-up box
news_signup:ticked(default),unticked(what the EU and UK ask for) oroff(no box: everyone gets news until they unsubscribe). Sign-up and SSO sign-up saveemail_newsand the country (the phone number's, else Cloudflare'sCF-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 /notificationsshows the broadcasts meant for them since they joined:all,proorfreeby their access,specificto them, orlist(picked members, innotification_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 IGNOREsnotification_reads, clearing the unread badge. - Unread badge counter
unread_notifications_count()powers the sidebar indicator. - Browser permission UX With push on, JS detects
Notification.permissionand 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.jsonserves anapplication/manifest+jsonpopulated frompwa_name,pwa_short_name,pwa_description,pwa_theme_color,pwa_bg_color,standalonedisplay, and a/dashboardstart 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.jsemits 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 currentCACHE_NAME. - Native push handling in the SW A
pushlistener 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_enabledare 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/createasks for name, email, subject and message (all four required), saved asopen. - 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 /supportshows 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}/replyappends a reply taggedis_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/ticketsshows 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}/replyappends a reply taggedis_admin = 1; if not closed, advances status toprocessing. - Manual status change
POST /admin/tickets/{id}/statussets Open/Processing/Closed. - One-click Resolve & Close A sidebar button posts
status=closeddirectly. - Customer identity panel Avatar initial, name, and email for immediate context.
- Link to full user profile If
user_idis 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
repliescolumn (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 viawhite-space: pre-wrap. - CSRF-protected actions & integer-bound pagination Every form emits
csrf_field(); list queries bindLIMIT/OFFSETasPARAM_INTwith 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/userslists 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/createadds 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}clearsplan_id,expires_atand lifetime extension access (extension), redirecting back to edit or list as appropriate. - Manually verify email
POST /admin/users/verify/{id}stampsemail_verified_atand 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-impersonatingexits 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/payoutsshows 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 behindbilling_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/transactionslists all subscription payments (20/page) joined to user name/email, filterable by free-text, status, and date range. Gated behindbilling_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/exportwith 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/activitylists, 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/exportwith 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, andadmin_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/statisticsheadline cards: logins today, active paid users, total users, today's revenue, this-month revenue, lifetime gross (revenue cards hidden whenbilling_enabledis 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/traffictracks home page visitors, with a page-path selector (auto-discovered fromtraffic_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 (fromAccept-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/errorsreadsdatabase/system_errors.sqlitenewest-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/cleardeletes all errors and runsVACUUM. - Toggle debug mode
POST /admin/errors/toggle-debugflipsdatabase/debug_mode.on, reflecting current ON/OFF state.
Cron logs4
- Execution history
GET /admin/cron-logslistscron_logsruns 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-cronURL with hourly-ping guidance. - Clear cron logs
POST /admin/cron-logs/cleartruncates 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-emailsends 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_nameplus 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_colorvia hex input, native picker, or 10 preset swatches. - Public home page toggle
home_enabledshows/hides the landing page (off redirects to login). - Documentation page toggle
docs_enabled(admins can still view when disabled). - Application timezone
app_timezonefrom 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_titleandseo_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 asog_logo_path; falls back to favicon). - Social sharing banner
sharing_banner→uploads/brand/og_banner.{ext}(stored asapp_sharing_banner), 1200×630 recommended, with live preview.
Pixels, server-side events and tracking (three audiences)6
- Facebook domain verification
meta_domain_verificationrenders 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 bymeta_pixel_paid_enabled; falls back to registered-audience pixels if disabled/empty. - Custom scripts / GTM per stage
custom_script_cold/_registered/_paidadd GTM or any other script for each audience. - IPInfo geo-location token
ipinfo_tokenlets the Traffic page find visitors' countries when the site isn't behind Cloudflare (Cloudflare'sCF-IPCountryheader comes first; with neither, no visitor address leaves the server).
Announcement and promo banners2
- Scrolling announcement banner
announcement_enabledplus text, button text/URL, and three colors for a dashboard-wide marquee. - Full-page promo modal
promo_enabledshows an image popup; uploadpromo_image(→uploads/brand/promo_banner.{ext}) with an optionalpromo_link.
Sales campaigns and discounts (with billing on)3
- Scheduled sales campaign
campaign_enabledwith 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_enabledplus per-tier percentages (discount_30_89/…/_365). - Pricing model selector
pricing_modeltoggles 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_debugsurfaces raw callback data for Stripe and Bayarcash. - Stripe gateway
gateway_stripe_enabledwith live/test key sets (stripe_pk_live/sk_live/webhook_secret_liveand_test), astripe_sandboxtoggle, allowedstripe_methods, a copyable webhook URL, and astripe_portal_urlCustomer Portal link. - Bayarcash gateway
gateway_bayarcash_enabledwith live/sandbox API token/secret/portal-key sets and abayarcash_sandboxtoggle. - 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_portalsrestricts 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_enabledpluspwa_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_enabledplus 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_enabledtoggles the page/download;app_urlis the base injected as the extension's API endpoint; set the brandext_name/ext_description, theext_version(latest) andext_min_version(gate),ext_mirror_linkandext_last_updated(saved, not used yet), and anext_iconPNG; upload a new build viaext_zip(extracts over/extensions/ext-app/, recordsext_last_upload_file/_time). Hidden whenextension_hideis 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_enabledrestricts non-admin access;maintenance_untilpowers a countdown;maintenance_secretdefines a secret/login/<secret>admin entry. System-page preview buttons open/admin/preview-page/{403|404|419|500|maintenance}.
Legal pages1
privacy_policyandterms_conditionsaccept plain text or HTML and render at/privacy-policyand/terms-and-conditions, each with a live preview link.
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/backupsshows 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/runwithtype=dborfiles) 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);0disables. - 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(defaultbackups,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/downloadstreams a chosen file andPOST /admin/backups/deleteremoves it (both guarded against path tricks); delete asks first.
How backups are made6
- mysqldump when it's there
Backups::dumpDatabase()runsmysqldump --single-transaction --routines --no-tablespaces, adding common MySQL install folders,/usr/binand/usr/local/bintoPATH. - PHP fallback When
mysqldumpis missing or fails,Backups::phpDump()writes the structure and data as.sqlover 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.logorbackups/files/error.logand to the error log, and sends thebackup.failedwebhook (kind,step,file,error). - ZIP archives Recursively zips the project, normalizes separators, and sets Unix file (0644)/dir (0755) attributes. The
backupsfolder 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.phpsends 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, andbackup.failedis 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
.partand 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) andbackup_offsite_files_keep(8); older backup files in itsdb/andfiles/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,/*! */andDELIMITERhandled), 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 asbackup.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/uploadadds a.sqlbackup, or a sealed.sql.encwith its passphrase, under a safe name that never writes over another; a file that isn't a LaunchX database backup (nousersandsettingstables) is refused.
Hosts that disable exec or popen4
- exec()/popen() detection
php_function_enabled()checks bothfunction_exists()and php.inidisable_functions;canSpawn()pickspopenon Windows vsexecelsewhere. - No crash on locked-down hosts On hosts where
exec/popenis 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()usesstart /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-managerbrowses any directory under the project root (folders-first natural sorting, sizes, dates, breadcrumb); every path isrealpath-validated to stay insideROOT_PATH. - In-browser code editor
GET/POST /admin/file-manager/editopens 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/uploadwith a modal dropzone. - File download
GET /admin/file-manager/downloadstreams 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/renamevia 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/deletemoves 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
chmodfallbacks. - 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-conflictsreturns 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/.sqlite3files 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-exploreropens any.sqlite/.db/.sqlite3by 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 insideROOT_PATHand 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/rowsreturns 50 rows/page; small DBs use numbered offset paging with exactCOUNT(*), while DBs ≥100 MB switch to keyset paging. - On-demand exact count & column sorting
GET /admin/sqlite-explorer/countcomputes 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/rowuses 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 SQLNULL; only real columns are accepted on write. - Structure tab Each table's
CREATEstatement and full column metadata. - Raw SQL console
POST /admin/sqlite-explorer/execruns 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 tocron_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/cleartruncates the table. - Run-cron address
GET /run-cron(with?key=whenCRON_SECRETis 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, oradmin(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
adminkey, 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 answer2xx. 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, bysortthen 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 inpublic/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(migration003_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
langcookie for a year).?lang=mson 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.phptolang/<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 --checkfails 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>,dirandog:localefollow the page's language. - API and webhooks
/mehaslocale;PATCH /mechanges it. The user data in webhooks haslocale. - 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
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
git pull, then php migrate.php. Settings create themselves, and uploads live outside the code.$ 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}}}
From your laptop to your own server, without paying anyone.
LaunchX is one of three free, open-source projects that fit together.
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 →LaunchX
A finished foundation: accounts, billing, invoices, a store, an admin panel and an API.
Get the code →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 →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.
Get the code
Clone it, or download the latest release as a zip.
git clone https://github.com/zaimzamzuri/ cd launch-xlaunch-x.git
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
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 task0 * * * * php /path/to/launch-x/cron.php
No account ever ships with a known password. Updating is git pull then php migrate.php. Full guide: docs/DEPLOY.md.
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.