API & Backend Overview 🌐
The REward Backend is a lightweight PHP-based REST API designed to bridge the gap between the ESP32 hardware and the Firebase Firestore database.
🏗️ Architecture
The API follows a simple, modular structure to ensure it can run on standard shared hosting (like Hostinger) while still utilizing modern Firebase features.
Key Components:
index.php(The Router):- Handles all incoming HTTP requests.
- Manages CORS (Cross-Origin Resource Sharing) to allow the Flutter app to communicate with the server.
-
Uses a regex-based router to map URLs to specific endpoint files in the
endpoints/directory. -
firebase.php(The Bridge): - A custom wrapper for the Firebase REST API.
- Handles OAuth2 authentication using a
service-account.jsonfile. - Provides helper functions for CRUD operations on Firestore (
getFirestoreDoc,updateFirestoreDoc, etc.). -
Implements FCM v1 (Firebase Cloud Messaging) for sending high-priority push notifications to devices and topics.
-
config.php(Configuration): - Stores the Firebase Project ID and the
API_SECRET_KEYused to authenticate kiosk requests. - Defines global constants like
POINTS_PER_PLASTIC.
🔐 Security
The API uses a dual-layer security model:
- Kiosk Authentication: Every request from an ESP32 machine must include an X-API-Key header. This key is stored securely in the PHP config and hardcoded (or flashed) into the kiosk firmware.
- Service Account: Communication with Firebase is secured using a Google Service Account, ensuring that only the API has the authority to update points and send global notifications.
🛠️ Typical Workflow: Recycling Transaction
- Detection: Kiosk detects a bottle.
- Identification: User scans their QR code at the kiosk.
- API Call: Kiosk sends a
POSTrequest to/api/kiosk/transactionwith the User ID and counts. - Validation: API verifies the
X-API-Key. - Database Update: API fetches current user points, calculates the new total, and updates Firestore.
- Notification: API triggers a push notification via FCM to the user's phone: "You earned 30 points! 🎉"