Couples Goals ships with a lightweight PHP/MySQL REST API. You can run it on a shared web host, a VPS, or a home server: anything with Apache, PHP, and MySQL.
| Component | Minimum | Recommended |
|---|---|---|
| Operating System | Any Linux distro | Ubuntu 22.04 LTS |
| Web Server | Apache 2.4 | Apache 2.4 with mod_ssl |
| PHP | 7.4 | 8.2+ |
| Database | MySQL 5.7 / MariaDB 10.3 | MariaDB 10.6+ |
| PHP Extensions | pdo_mysql, openssl, json | |
| Apache Modules | mod_rewrite, mod_ssl. Disable MultiViews: it interferes with clean URL routing. | |
| TLS Certificate | Required in production (Let's Encrypt is free) | |
Copy the entire server/api/ folder to your web root, accessible at a URL like https://api.yourdomain.com/. Also upload server/feedback.php, server/delete-account.php, and server/.htaccess to the root if you want the public feedback page, the account-deletion request page, and this docs site. The account-deletion page is required if you plan to publish an app that uses your server on Google Play, per Play's Account Deletion Requirement (see the Privacy Policy).
mysql -u root -p
CREATE DATABASE coupleschallenge CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; CREATE USER 'cc_user'@'localhost' IDENTIFIED BY 'STRONG_PASSWORD_HERE'; GRANT ALL PRIVILEGES ON coupleschallenge.* TO 'cc_user'@'localhost'; FLUSH PRIVILEGES; EXIT;
Import the schema. This single file is the complete, current schema for a fresh install; every table (including the admin panel, vault, premium, and account-deletion tables) is already merged in, so do not run any of the individual migration_*.sql files listed later in this file's own header comment on a brand-new database; those are for upgrading an existing, already-deployed database only, one at a time, in the order they were introduced:
mysql -u cc_user -p coupleschallenge < /path/to/server/api/schema.sql
The server ships api/config.php.example (so updates never overwrite your settings). Copy it once, then edit the copy:
cp api/config.php.example api/config.php
define('DB_HOST', 'localhost');
define('DB_NAME', 'coupleschallenge');
define('DB_USER', 'cc_user');
define('DB_PASS', 'STRONG_PASSWORD_HERE');
define('JWT_SECRET', 'CHANGE_ME_64_HEX_CHARS');
define('APP_ENV', 'production');
Generate a secure JWT secret:
php -r "echo bin2hex(random_bytes(32)) . PHP_EOL;"
define('OPENAI_API_KEY', 'sk-...');
define('SPARKY_ENABLED', true);
define('SPARKY_DAILY_LIMIT', 20);
Leave SPARKY_ENABLED false (or the key unset) to disable the fallback entirely; the app falls back further, to a static localized line, exactly like it does when the on-device model itself is unavailable.
FCM_SERVICE_ACCOUNT_FILE at it, and run migration_push_tokens.sql. Step-by-step: DEPLOYMENT.md §7.7. This only works with app builds that use the same Firebase project.
REVENUECAT_WEBHOOK_SECRET authenticates RevenueCat's webhook; REVENUECAT_SECRET_API_KEY (a v2 secret key with Purchases: Read and Products: Read) plus REVENUECAT_PROJECT_ID let the server confirm XP bundle purchases. See RevenueCat_Setup_Guide.md §5 and §7.
<Directory /var/www/html>
Options -MultiViews
AllowOverride All
Require all granted
</Directory>
a2enmod rewrite && systemctl restart apache2
/feedback before mod_rewrite can handle them, causing 404 errors. Always set Options -MultiViews.
apt install certbot python3-certbot-apache -y certbot --apache -d api.yourdomain.com
Upload server/admin/ to a directory on your server. Generate an Argon2id password hash:
php -r "echo password_hash('YourPassword', PASSWORD_ARGON2ID);"
Edit admin/admin_config.php and replace ADMIN_PASSWORD_HASH and ADMIN_SESSION_SECRET. Restrict access by IP allowlist.
In the app, go to Settings → Custom server URL and enter:
https://api.yourdomain.com/
The trailing slash is required. Tap Save, then Sync Now: a green status confirms the connection.
| Table | Purpose |
|---|---|
users | Accounts; display name, email, bcrypt password, partner_id, XP balances, badges and their earned dates, premium tier |
partner_links | 6-character invite codes; 24-hour TTL |
challenges | All challenges; status, visibility, category, sort_order |
progress_entries | All logged activity; entry_type stores YES/NO/SKIP/COUNT/WEIGHT/FREEZE/RECOVERY (FREEZE/RECOVERY are legacy values; see streak_protection_log below for the current account-wide mechanism) |
sync_queue | Per-user last push/pull timestamps |
deleted_challenge_tombstones | Hard-deleted challenge UUIDs; prevents resurrection on reinstall |
xp_ledger | Append-only XP earn/spend audit log; ADMIN_ADJUSTMENT source type |
streak_protection_log | Account-wide Streak Freeze/Recovery rows: one streak per account, not per challenge |
custom_vouchers | Partner reward vouchers (PENDING_APPROVAL → AVAILABLE → REDEEMED → FULFILLED) |
challenge_modifiers | Sabotage text modifiers applied to challenges |
progress_comments | Text comments on progress entries; soft-delete |
progress_reactions | Emoji reactions on entries; unique per user per entry |
vault_reward_content | Couple-scoped vault milestone content (bucket list items, letters, planner fields, etc.); is_revealed is server-authoritative |
vault_contributions | Per-user XP contribution history into the shared vault wallet |
vault_media | Vault photo metadata (Memory Box); files stored outside the web root, served exclusively via an authenticated endpoint |
vault_milestone_unlocks | Permanent record of which vault milestones a couple has redeemed; the store model's single source of ownership truth |
vault_celebrations | Per-user record of which milestone-unlock celebrations have already played, so they don't repeat across devices |
premium_licenses | License key hashes for Couple Pro activation; propagates to the linked partner automatically |
announcements / announcement_dismissals | Admin-authored dashboard banners with optional targeting (rollout %, tier, app version, specific users) and per-user dismissal tracking |
account_deletion_requests | Queue behind the public /delete-account web form (Google Play's Account Deletion Requirement web-link path); reviewed by an admin before the account is actually removed |
install_pings | Anonymous, account-independent install/open telemetry: a random per-install ID, app version, and locale; never linked to any user account |
user_feedback | Public feedback form submissions; managed via admin/feedback.php |
admin_users / admin_sessions / admin_backup_codes | DB-backed admin accounts with Argon2id password hashing, TOTP MFA, and single-use backup recovery codes; sessions are revocable server-side |
admin_audit_log | Append-only log of every admin panel action |
admin_login_attempts | Failed admin logins for brute-force rate limiting |
sparky_generation_log | Server-side Sparky AI Coach fallback call log: trigger type, model, token counts, duration; never the prompt content or generated message text. Used for rate limiting and the admin usage stats panel |
sparky_settings | Admin-configured OpenAI model for the Sparky fallback (falls back to a hardcoded default if this table is empty or unmigrated) |
sparky_local_generation_log | Content-free ping recorded when the app's on-device (Gemini Nano) Sparky generation succeeds: trigger type only, never the message text. Lets the admin panel compute an on-device-vs-cloud generation ratio |
sparky_quota_breach_log | One row per Sparky request rejected for exceeding SPARKY_DAILY_LIMIT: user ID and timestamp only |
analytics_events | First-party onboarding funnel & conversion events (no Firebase, no third-party SDK), anonymous and install_id-scoped, user_id attached once known. See the Privacy Policy for exactly what's collected |
push_tokens | Firebase Cloud Messaging device tokens, one per signed-in device; removed on sign-out, account deletion, or when Google reports them invalid |
couple_gifts | Gift Shop gifts between partners (type, message, chosen option, Pep Talk text, active window, state); deleted when the couple unlinks or either account is deleted |
xp_purchases | XP bundles bought with real money: one row per store transaction (the unique key that stops a purchase being credited twice), XP amount, test-purchase flag, and refund state |
pushover_settings | Admin Pushover alert settings: encrypted credentials, priority, sound, and which events alert (new user, upgrade, feedback, log upload, deletion request, account deleted, XP purchase) |
All endpoints return application/json. Endpoints marked with a lock () require an Authorization: Bearer <token> header.
| Method | Path | Auth | Description |
|---|---|---|---|
| POST | auth/register | Create account, returns JWT | |
| POST | auth/login | Authenticate; returns JWT with token_version claim | |
| GET | challenges | List own + partner's shared challenges | |
| POST | challenges/create | Create a new challenge | |
| PUT | challenges/update | Update challenge metadata and visibility | |
| DELETE | challenges/delete | Hard-delete a challenge; writes tombstone | |
| POST | progress/add | Add or update a progress entry (upsert). Supports entry_type: YES/NO/SKIP/COUNT/WEIGHT/FREEZE/RECOVERY | |
| GET | progress/history | Get entries for a challenge | |
| POST | partner/generate-code | Generate a 6-character invite code (24 h expiry) | |
| POST | partner/link | Link two accounts using an invite code; both partner_id fields updated atomically | |
| GET | partner/status | Check partner link status and partner name | |
| POST | social/comment | Add / edit / soft-delete a text comment on an entry | |
| POST | social/react | Insert / toggle / replace an emoji reaction | |
| POST | sync/push | Push pending batch (challenges, entries, XP, vouchers, comments, reactions, streak protections, deleted IDs) | |
| GET | sync/pull?since=<ms> | Pull all data since timestamp. Returns: challenges, entries, XP, vouchers, social, streak protections, tombstones, display_name, server_partner_id, server_partner_name | |
| POST | vouchers/create | Create a custom voucher (starts as PENDING_APPROVAL) | |
| POST | vouchers/redeem | Redeem an available voucher (deducts XP) | |
| GET | vouchers/status | Check the status of a specific voucher | |
| POST | gamification/execute-sabotage | Execute a Sabotage Shop action: modifier (free), or taxman / mega_drain / shield (Couple Pro, tier-checked server-side) | |
| POST | premium/activate | Redeem a license key; grants Couple Pro to the account and its linked partner | |
| GET | premium/status | Check the account's current premium tier and expiry | |
| POST | vault/contribute | Move XP from the caller's personal balance into the couple's shared vault wallet | |
| POST | vault/redeem | Redeem a vault milestone once the wallet covers its cost (and any dependency is already owned); re-validates everything server-side regardless of client state | |
| POST | vault/media/upload.php | Upload a Memory Box photo (multipart/form-data); re-validates the image server-side, stores it outside the web root under a random filename | |
| GET | vault/media/serve.php?id=<uuid> | Stream a vault photo; checks couple ownership and reveal state before returning bytes | |
| DELETE | vault/media/delete.php | Delete your own vault photo (file + DB row) | |
| POST | account/delete.php | Self-service account deletion. Requires, in addition to the JWT, the account's current password in the request body (or, for an account created with Google Sign-In and no password, an exact confirmation phrase); permanently deletes the account and everything it owns, unlinks the partner, never touches the partner's own data | |
| POST | sparky/generate | Sparky AI Coach server/OpenAI fallback. Couple Pro only, server-side daily rate limit; requires OPENAI_API_KEY configured (see Step 3 above). Returns generated commentary text and a mascot expression key | |
| POST | sparky/log_local_success.php | Content-free telemetry ping recorded when the app's on-device Sparky generation succeeds (trigger type only); feeds the admin on-device-vs-cloud ratio | |
| POST | sparky/streak-loss-coaching.php | Streak Loss Diagnostic full-AI coaching reply. Couple Pro only, shares SPARKY_DAILY_LIMIT with sparky/generate (logged as a distinct STREAK_LOST_COACHING trigger). Validates a custom free-text reason and/or generates a validate-then-recommend-then-encourage coaching reply, optionally naming one of the caller's own active challenges by a scaled-down version of it | |
| POST | telemetry/track_event.php | Onboarding funnel / conversion event ping, anonymous and install_id-scoped, same no-auth shape as telemetry/install_ping.php; user_id included in the body once an account exists | |
| POST | push/register_token.php | Store this device's Firebase push token for the signed-in account | |
| POST | push/unregister_token.php | Remove the device's push token (called on sign-out) | |
| POST | gifts/purchase.php | Buy a Gift Shop gift for the linked partner. The server checks and deducts the XP; a retry with the same client_request_id is never charged twice | |
| POST | gifts/respond.php | Recipient collects a Love Bomb or dismisses a Love Note / Pep Talk | |
| POST | xp/claim-purchases.php | Credit any XP bundle the account bought that isn't credited yet. Takes no input: the server asks RevenueCat what was bought. Returns the XP added and the new balance | |
| POST | premium/revenuecat-webhook.php | RevenueCat server-to-server events: Couple Pro grants and expiry, XP bundle purchases and refunds. Authenticated by REVENUECAT_WEBHOOK_SECRET |
server_partner_id and server_partner_name for the requesting user. The Android client uses these to detect admin-initiated unlinks (server returns empty string when partner_id is NULL) and to recover lost partner state after events like app reinstall or a false-unlink scenario.
Access at https://yourdomain.com/admin/ with your configured admin credentials.
| Page | Features |
|---|---|
| Dashboard | 6 stat tiles (users, challenges, entries, XP, vouchers, sync health), recent activity |
| All Users | Searchable user list; email, name, XP, partner status, join date |
| User Detail | Enable/disable account, force-logout (token_version bump), reset password, unlink partner, edit display name, view challenges and XP ledger, gift lifetime Couple Pro premium (cascades to the linked partner automatically), view vault balance/media, Danger Zone: delete account and all of its data (uses the same cascade as the in-app self-service path; see Deletion Requests below) |
| Deletion Requests | Review queue for the public /delete-account web form (Google Play's Account Deletion Requirement web-link path). “Delete Account Now” looks up the submitted email and runs the same deletion cascade as User Detail's Danger Zone and the in-app path: one shared implementation, three entry points |
| Modify XP | Add/subtract/set individual or shared vault XP; writes ADMIN_ADJUSTMENT ledger row; live ledger view |
| Vouchers | Browse and cancel/delete vouchers by status |
| Challenges | Browse all challenges; archive or hard-delete (tombstone written) |
| Feedback | Inbox / Starred / Archived views; mark read/unread; star; archive; delete; admin notes; unread badge in nav |
| Audit Log | Paginated log of every admin action (LOGIN, UNLINK_PARTNER, FEEDBACK_READ, MODIFY_XP, etc.) |
| Sync Status | Users with oldest pull timestamps; users who have never synced |
| Server Logs | View/search/filter daily API log files; level/keyword/user/IP filters; JSON context expand; raw download |
| DB Health | Table row counts and sizes; orphan detection; server info |
| Announcements | Create/edit targeted dashboard banners (rollout percent, tier, app version, or specific users), with optional image and action link |
| Install Analytics | Aggregate install/adoption trends from the anonymous install ping table; bot traffic (Play pre-launch report, Firebase Test Lab) is filtered out |
| Funnel Analytics | Onboarding step-by-step drop-off, sign-up conversion, estimated paywall conversion, and 24h activation rate from the first-party analytics_events table |
| Notifications | Pushover alerts to the admin's phone for selected events: new user, Couple Pro upgrade, feedback, log upload, deletion request, account deleted, and XP bundle purchased (names the bundle, flags test purchases) |
| Sparky AI Coach | Pick/refresh which OpenAI model powers the server fallback; usage stats (calls, success rate, latency, tokens by trigger/model); average generations per active user, on-device-vs-cloud ratio, daily quota-breach rate, and a live "Quota Exceeded Users" table with a one-click per-user Reset action |
| Troubleshooting | Reference page: every server endpoint by area, with what each of this API's specific error codes actually means, for support-ticket triage |
| Security | Admin's own TOTP MFA enrollment/management and single-use backup recovery codes |
users table), with Argon2id password hashing, mandatory-capable TOTP multi-factor authentication with backup codes, CSRF-protected forms, revocable server-side sessions, brute-force rate limiting, and an optional IP allowlist. None of this is reachable through the regular app API.
| Symptom | What to check |
|---|---|
| 500 on every request | config.php DB credentials; PHP error log |
| 404 on all routes | mod_rewrite enabled; AllowOverride All in Apache config |
| 404 on /feedback clean URL | Options -MultiViews set in .htaccess or Apache vhost config; RewriteRule ^feedback/?$ /feedback.php [L] present |
| 401 on every request | Token expired or wrong JWT_SECRET; log in again in the app |
| "Session invalidated" error | Admin panel force-logout was triggered; log in again |
| "Account disabled" error | Admin has disabled the account; contact your server admin |
| "Database connection failed" | DB user permissions; confirm DB service is running |
| App shows HTTPS error | TLS certificate valid; APP_ENV = 'production' in config.php |
| Partner code "invalid" | Code expired (24 h TTL); generate a fresh code |
| Deleted challenge reappears | Run migration_tombstone.sql on your server; sync again |
| Every sync fails right after updating the server files | Run migration_badge_earned_at.sql. The current sync endpoints read and write the users.badge_earned_at column it adds; run it before uploading the new PHP files |
| Sync or gifts fail after the Gift Shop / Get XP update | Run the migrations in DEPLOYMENT.md §6.1 order (migration_push_tokens.sql, migration_gift_shop.sql, the progress-entry dedup scripts, migration_xp_purchases.sql, migration_pushover_xp_purchase.sql) before uploading the new PHP files |
| XP bundle bought but never credited | Check the server log for RevenueCat request failed: it includes RevenueCat's reason. Usually a key without the Purchases/Products read permissions, or a v2 key with no REVENUECAT_PROJECT_ID. Fix the config, then open Get XP in the app: stuck purchases are credited on open |
| Partner challenges not showing after link | Device A: tap Refresh on Partner screen. If still missing: check in-app logs for pull errors; verify server_partner_id is returned in pull response (requires updated pull.php) |
| Partner still shows after admin unlink | Tap Sync Now on the affected device. The pull response's server_partner_id field triggers local cleanup automatically. |
| Display name change not reflected in app | Tap Sync Now. The pull response returns the server-authoritative display name and updates prefs immediately. |
| Feedback page 404 at /feedback | MultiViews must be disabled. Add Options -MultiViews to the vhost <Directory> block or in root .htaccess. |
| Sparky AI Coach always shows the same canned line | A missing server/api/.htaccess rewrite rule causes every sparky/generate request to 404 silently before PHP ever runs (no entry in the PHP or Apache error log, since a rewrite non-match isn't logged as an error). Confirm your .htaccess includes the sparky/ rewrite rules shown in this file's own header comment, then check the admin panel's Sparky AI Coach usage table for real call attempts |
password_hash().token_version claim to support admin force-logout.config.php and .sql files are blocked from direct HTTP access by .htaccess rules.X-Content-Type-Options, X-Frame-Options, Referrer-Policy.