Skip to content

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:

  1. index.php (The Router):
  2. Handles all incoming HTTP requests.
  3. Manages CORS (Cross-Origin Resource Sharing) to allow the Flutter app to communicate with the server.
  4. Uses a regex-based router to map URLs to specific endpoint files in the endpoints/ directory.

  5. firebase.php (The Bridge):

  6. A custom wrapper for the Firebase REST API.
  7. Handles OAuth2 authentication using a service-account.json file.
  8. Provides helper functions for CRUD operations on Firestore (getFirestoreDoc, updateFirestoreDoc, etc.).
  9. Implements FCM v1 (Firebase Cloud Messaging) for sending high-priority push notifications to devices and topics.

  10. config.php (Configuration):

  11. Stores the Firebase Project ID and the API_SECRET_KEY used to authenticate kiosk requests.
  12. 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

  1. Detection: Kiosk detects a bottle.
  2. Identification: User scans their QR code at the kiosk.
  3. API Call: Kiosk sends a POST request to /api/kiosk/transaction with the User ID and counts.
  4. Validation: API verifies the X-API-Key.
  5. Database Update: API fetches current user points, calculates the new total, and updates Firestore.
  6. Notification: API triggers a push notification via FCM to the user's phone: "You earned 30 points! 🎉"