photobooth4u

Offline Cash, Relays & NeoPixel (ESP32) · Cloudflare PayMongo

Test the Android Offline App free, connect an ESP32 over two-way Bluetooth or USB Serial for cash acceptors, 4–8 channel relay lighting, and NeoPixel LEDs, or self-host PayMongo QR Ph on Cloudflare.

Android Offline Trial ESP32 Relays, LEDs & Cash Own Cloudflare PayMongo

1. Free Offline Trial (Android, Windows, Mac & iPad)

You can test the full Android Offline App (and Windows / Mac / iPad apps) before buying:

  1. Download and install the Android APK from photobooth4u.netlify.app/downloads.
  2. Connect to Wi-Fi once and enter the free trial password shown on our About Us page.
  3. Once unlocked, you can turn Wi-Fi off and test everything offline — camera, offline printing, booth Wi-Fi sharing, vouchers, and the ESP32 controller.

2. Two-Way ESP32 Controller (Relay Module + NeoPixel + Cash Acceptor)

photobooth4u supports two-way serial communication over Bluetooth (Android Tablet Offline App BLE/Classic BT, plus Chrome/Edge Web Bluetooth) and USB Serial. The ESP32 can report coin/bill credits (c<pesos>\n) to the app and receive live booth status commands to switch a Relay Module (studio lights, camera flash/strobe, coin/bill inhibit, print sign) and drive NeoPixel (WS2812B) LED animations.

Connection modes

Booth settingBest forTwo-Way Relays & LEDs?Notes
Bluetooth serial (recommended)Android Offline App, Chrome / Edge (Windows, Mac)Yes (Two-way)Default BT_MODE 2 (BLE Nordic UART 6e400001-... RX/TX) or BT_MODE 3 (Classic Bluetooth SPP). Works alongside Bluetooth thermal printers and never hides Android’s on-screen keyboard.
USB cable, serialChrome / Edge (Windows, Mac)Yes (Two-way)115200 baud over USB cable (always active alongside Bluetooth).
Bluetooth or USB keyboardiPad Safari / LegacyNo (Credits only)ESP32 acts as a BLE HID keyboard (BT_MODE 1) typing c<pesos>. Cannot receive relay/LED commands from the app.

Two-way status commands (App → ESP32)

Sent automatically as newline-terminated lines (\n) during every booth session:

Serial commandWhen photobooth4u sends itDefault ESP32 action (Relays + NeoPixel)
session_idleIdle / welcome screenIdle rainbow NeoPixel; cash disabled (Ch 1 OFF); Studio Light Ch 2 OFF
template_selectionGuest choosing a template / layoutTemplate-selection cyan NeoPixel chase
price{50}Price selected (e.g. ₱50)Records target price (targetPesos = 50)
credit{5}Cash balance changes (on select, coin/bill pulse, payment, or idle expiry)Records current booth credit in pesos (creditPesos = 5)
cash_openCash payment screen opensEnables coin/bill acceptors (Ch 1 ON); pulsing gold NeoPixel
cash_closeLeaving cash screen or paidDisables coin/bill acceptors (Ch 1 OFF)
payment_successPayment confirmed (Cash / QR / Voucher)Green confirmation NeoPixel; cash disabled (Ch 1 OFF)
session_startCountdown / session beginsTurns Studio Light Relay Ch 2 ON; bright studio NeoPixel
countdown_33 seconds before shotRed countdown ring on NeoPixel
countdown_22 seconds before shotAmber countdown ring on NeoPixel
countdown_11 second before shotGreen countdown ring on NeoPixel
shutter_flashShutter captures photoPure white NeoPixel burst + Flash Relay Ch 3 250 ms pulse
start_printPrinting startsBlue printing wave + Print/Aux Relay Ch 4 ON
print_donePrinting finishesGreen completion flash + Print/Aux Relay Ch 4 OFF
session_endSession completed → idleStudio Light Relay Ch 2 OFF; returns to idle lighting
session_cancelCancelled or timed outAcceptors disabled; all session relays OFF → red flash → idle

Bonus test commands: ch1_on..ch8_on, ch1_off..ch8_off, all_off, ping. Cash acceptor pulses sent back from ESP32 → App use c<pesos>\n (e.g. c5\n, c100\n).

Max Relay Channels & Wiring Guide

  • How many relay channels max on an ESP32? Even with Coin Slot (GPIO 27), Bill Acceptor (GPIO 26), and NeoPixel Data (GPIO 13) connected, a standard 30-pin or 38-pin ESP32 DevKit has 8 clean, boot-glitch-free output GPIOs (GPIO 16, 17, 18, 19, 21, 22, 23, 25 — note: on ESP32-WROVER with PSRAM, swap 16/17 for 32/33). You can wire a 4-channel or 8-channel relay module directly (or 16+ channels via an I2C PCF8575 / MCP23017 expander on GPIO 21/22).
  • Default 4-Channel Relay Mapping: Ch 1 = GPIO 16 (Cash Acceptor Inhibit/Power), Ch 2 = GPIO 17 (Studio / Ring Light), Ch 3 = GPIO 18 (Strobe / Flash Trigger), Ch 4 = GPIO 19 (Print Sign / Aux Light). Set #define NUM_RELAYS 8 for an 8-channel board.
  • NeoPixel (WS2812B): WS2812B strips require 5V logic and cannot reliably run directly from an ESP32 3.3V pin. Buffer GPIO 13 through an SN74AHCT125N (3.3V → 5V buffer / level-shifter IC powered at 5V), then feed the 5V data output through a 330 Ω resistor to the first WS2812B Din. Add a 1000 µF / 16V electrolytic filter capacitor across +5V and GND on your external 5V PSU (e.g. Mean Well) with Common GND tied to the ESP32. Set #define USE_NEOPIXEL 0 if you only wired relays.
  • Cash Acceptor 3.3V safety: Power coin/bill acceptors from their own 12V DC supply with Common GND. Wire Coin to GPIO 27 and Bill to GPIO 26 (NO open-collector, or isolated via an optocoupler such as PC817 or EL816 / EL816B if active 5V/12V). Set #define REQUIRE_CASH_OPEN 0 if you want coins accepted on the idle screen without needing cash_open.

Arduino IDE setup

  • Default (BT_MODE 2 — BLE Nordic UART, Android Tablet & Chrome/Edge): Uses built-in ESP32 BLE — zero extra Bluetooth libraries needed (compiles on ESP32 core 2.x & 3.x).
  • NeoPixel LEDs: If USE_NEOPIXEL 1 is enabled, install Adafruit NeoPixel in Arduino IDE → Library Manager (or set #define USE_NEOPIXEL 0 for relays only).
  • Classic Bluetooth option (BT_MODE 3): Built-in BluetoothSerial.h. Pair Photobooth4u-Cash in Android Settings → Bluetooth first, then tap Connect ESP32 in photobooth4u.

Expected Arduino Serial Monitor output (115200 baud)

Bluetooth connected
RX: session_idle
RX: template_selection
RX: price{20}
RX: credit{0}
RX: cash_open
TX: c10
RX: credit{10}
TX: c10
RX: credit{20}
RX: cash_close
RX: payment_success
RX: credit{0}
RX: session_start
RX: countdown_3
RX: countdown_2
RX: countdown_1
RX: shutter_flash
RX: start_print
RX: print_done
RX: session_end

If credit is already inserted before picking a package (e.g. ₱5 waiting when selecting a ₱50 template), the app sends price{50} and credit{5} together so your controller stays in sync; if existing credit already covers the chosen package price, cash_open is skipped and any change stays in credit{<remaining>}.

ESP32 Arduino Sketch (esp32-cash-acceptor.ino)

Download .ino
/*
 * photobooth4u — ESP32 Two-Way Controller (Cash Acceptor + Relay Module + NeoPixel LEDs)
 *
 * Works completely OFFLINE over Bluetooth Serial & USB Serial on:
 *   - Android Offline App (PB4uAndroid via native Bluetooth Bridge: BLE UART or Classic BT)
 *   - Windows / Mac / Linux Chrome & Edge (Web Bluetooth BLE UART or USB Web Serial)
 *
 * TWO-WAY SERIAL PROTOCOL (115200 baud / Bluetooth Serial, newline-terminated):
 *   1. ESP32 -> photobooth4u (Coin / Bill credits):
 *        c<pesos>\n          e.g. c5\n (P5 coin)   c100\n (P100 bill)
 *
 *   2. photobooth4u -> ESP32 (Live status commands):
 *        session_idle        Idle/welcome screen (idle NeoPixel effect; cash & studio light off)
 *        template_selection  Guest picking a template/layout (selection NeoPixel effect)
 *        price{50}           Session price in pesos (records targetPesos = 50)
 *        credit{5}           Current booth credit balance in pesos (records creditPesos = 5)
 *        cash_open           App ready for cash (enables coin/bill acceptors + Relay Ch 1 ON)
 *        cash_close          Stops accepting cash (disables acceptors + Relay Ch 1 OFF)
 *        payment_success     Payment confirmed (payment-success NeoPixel; Relay Ch 1 OFF)
 *        session_start       Photo session starts (session-start LEDs; Studio Light Relay Ch 2 ON)
 *        countdown_3         3 seconds before shot
 *        countdown_2         2 seconds before shot
 *        countdown_1         1 second before shot
 *        shutter_flash       Photo captured (white flash burst LEDs + Flash Relay Ch 3 pulse)
 *        start_print         Printing started (printing NeoPixel wave + Aux/Print Relay Ch 4 ON)
 *        print_done          Printing finished (completion NeoPixel + Aux/Print Relay Ch 4 OFF)
 *        session_end         Session finished (Studio Light Relay Ch 2 OFF; return to idle effect)
 *        session_cancel      Cancelled/failed (acceptors disabled; all session relays OFF -> idle)
 *      Bonus manual test commands: ch1_on .. ch8_on, ch1_off .. ch8_off, all_off, ping
 *
 * --------------------------------------------------------------------------
 * CHOOSE BLUETOOTH MODE BELOW (USB Serial at 115200 baud is ALWAYS active):
 *   2 = BLE Nordic UART Service (DEFAULT — two-way, works on Android Tablet App + Chrome/Edge,
 *       uses built-in ESP32 BLE library, zero extra BT libraries, compiles on core 2.x & 3.x)
 *   3 = Classic Bluetooth SPP (two-way serial via BluetoothSerial — Android Tablet App;
 *       pair ESP32 in Android Bluetooth settings, then tap Connect in photobooth4u)
 *   1 = BLE HID Keyboard (LEGACY one-way credits only — cannot receive relay/LED commands)
 *   0 = USB Serial only (two-way via USB cable on Chrome / Edge)
 * --------------------------------------------------------------------------
 */
#define BT_MODE 2

// ---- NeoPixel (WS2812B LED ring / strip) ----
// Set USE_NEOPIXEL to 1 and install "Adafruit NeoPixel" in Arduino Library Manager,
// or set to 0 if using only a Relay Module without NeoPixels.
// HARDWARE NOTE (WS2812B 5V logic): WS2812B strips require a 5V data signal and cannot
// reliably run directly from 3.3V ESP32 GPIO. Buffer GPIO 13 through an SN74AHCT125N
// (3.3V -> 5V level shifter / buffer IC powered by 5V), then feed the 5V output
// through a 330 ohm resistor to the first WS2812B Din. Place a 1000 uF / 16V filter
// capacitor across +5V and GND on the 5V PSU (e.g. Mean Well) with Common GND.
#define USE_NEOPIXEL       1
#define NEOPIXEL_PIN       13
#define NEOPIXEL_COUNT     16
#define NEOPIXEL_BRIGHT    160   // 0..255

// ---- Relay Module configuration (supports 1, 2, 4, or 8 channels directly!) ----
// Standard 5V/3.3V opto-isolated relay boards trigger on LOW (active-LOW = true).
// Change RELAY_ACTIVE_LOW to false if your relay/MOSFET module triggers on HIGH.
#define NUM_RELAYS         4     // Change up to 8 if using an 8-channel relay board
#define RELAY_ACTIVE_LOW   true
#define FLASH_PULSE_MS     250   // How long Relay Ch 3 pulses on shutter_flash

// Safe boot-glitch-free ESP32 DevKit (WROOM-32) output GPIOs for relays 1..8
// (If using an ESP32-WROVER board with PSRAM, change pins 16 & 17 to 32 & 33):
#define RELAY_CASH_PIN     16    // Ch 1: Coin & Bill Acceptor Enable / Power Relay
#define RELAY_LIGHT_PIN    17    // Ch 2: Studio / Ring Light Relay
#define RELAY_FLASH_PIN    18    // Ch 3: Strobe / Camera Flash Relay (250 ms pulse)
#define RELAY_AUX_PIN      19    // Ch 4: Print Indicator / Booth Sign / Aux Relay
#define RELAY_CH5_PIN      21    // Ch 5 (optional 8-ch)
#define RELAY_CH6_PIN      22    // Ch 6 (optional 8-ch)
#define RELAY_CH7_PIN      23    // Ch 7 (optional 8-ch)
#define RELAY_CH8_PIN      25    // Ch 8 (optional 8-ch)

const uint8_t RELAY_PINS[8] = {
  RELAY_CASH_PIN, RELAY_LIGHT_PIN, RELAY_FLASH_PIN, RELAY_AUX_PIN,
  RELAY_CH5_PIN,  RELAY_CH6_PIN,   RELAY_CH7_PIN,   RELAY_CH8_PIN
};

// ---- Cash Acceptor Pins & Calibration ----
// SAFETY: Coin/Bill acceptor signal lines must never exceed 3.3V on ESP32 GPIO.
//   - Open-collector (NO to GND): connect directly to GPIO with INPUT_PULLUP + common GND.
//   - Active 5V/12V output: isolate through an optocoupler (e.g. PC817 or EL816 / EL816B) or voltage divider.
#define COIN_PIN              27     // Coin acceptor pulse wire
#define BILL_PIN              26     // Bill acceptor pulse wire
#define TEST_BTN_PIN          0      // Built-in BOOT button on ESP32 (press to test c10)
#define LED_PIN               2      // Built-in blue LED

#define COIN_PESOS_PER_PULSE  1      // 1 pulse = PHP 1 (5 pulses = P5, 10 pulses = P10)
#define BILL_PESOS_PER_PULSE  10     // 1 pulse = PHP 10 (2 pulses = P20, 10 pulses = P100)
#define PULSE_DEBOUNCE_MS     22
#define COIN_TRAIN_GAP_MS     320
#define BILL_TRAIN_GAP_MS     420

// 1 = ignore coin/bill pulses unless cash_open was received from the app (matches idle=disabled).
// 0 = report coin/bill pulses even while idle (for welcome-screen pre-pay without inhibit relay).
#define REQUIRE_CASH_OPEN     1

#define DEVICE_NAME "Photobooth4u-Cash"

#if USE_NEOPIXEL == 1
  #include <Adafruit_NeoPixel.h>
  Adafruit_NeoPixel strip(NEOPIXEL_COUNT, NEOPIXEL_PIN, NEO_GRB + NEO_KHZ800);
#endif

// ---- Booth LED / Controller State ----
enum BoothState {
  ST_IDLE = 0,
  ST_TEMPLATE_SELECT,
  ST_CASH_OPEN,
  ST_PAYMENT_OK,
  ST_SESSION_START,
  ST_CD_3,
  ST_CD_2,
  ST_CD_1,
  ST_FLASH,
  ST_PRINTING,
  ST_PRINT_DONE,
  ST_CANCEL
};

BoothState boothState = ST_IDLE;
uint32_t stateEnteredMs = 0;
uint32_t targetPesos = 0;
uint32_t creditPesos = 0;
bool cashAccepting = false;
bool flashRelayActive = false;
uint32_t flashRelayOffAt = 0;
uint32_t lastLedUpdateMs = 0;
uint16_t animStep = 0;

String usbRxLine = "";

// ---- Bluetooth Transport ----
#if BT_MODE == 1
  #include <BleKeyboard.h>
  BleKeyboard bleKeyboard(DEVICE_NAME, "photobooth4u", 100);
#elif BT_MODE == 2
  #include <BLEDevice.h>
  #include <BLEServer.h>
  #include <BLEUtils.h>
  #include <BLE2902.h>
  #define NUS_SERVICE_UUID "6e400001-b5a3-f393-e0a9-e50e24dcca9e"
  #define NUS_RX_UUID      "6e400002-b5a3-f393-e0a9-e50e24dcca9e"
  #define NUS_TX_UUID      "6e400003-b5a3-f393-e0a9-e50e24dcca9e"
  BLECharacteristic *pTxChar = nullptr;
  volatile bool bleClientConnected = false;
  volatile bool bleNeedReAdv = false;
  volatile bool bleLogConnected = false;
  volatile bool bleLogDisconnected = false;

  // ISR/callback-safe RX queue for incoming BLE write chunks
  portMUX_TYPE bleRxMux = portMUX_INITIALIZER_UNLOCKED;
  volatile char bleRxQueue[512];
  volatile uint16_t bleRxHead = 0;
  volatile uint16_t bleRxTail = 0;

  class NusServerCallbacks : public BLEServerCallbacks {
    void onConnect(BLEServer *s) override {
      bleClientConnected = true;
      bleLogConnected = true;
    }
    void onDisconnect(BLEServer *s) override {
      bleClientConnected = false;
      bleNeedReAdv = true;
      bleLogDisconnected = true;
    }
  };

  class NusRxCallbacks : public BLECharacteristicCallbacks {
    void onWrite(BLECharacteristic *ch) override {
      const uint8_t *data = ch->getData();
      size_t len = ch->getLength();
      if (!data || len == 0) return;
      portENTER_CRITICAL(&bleRxMux);
      for (size_t i = 0; i < len; i++) {
        uint16_t next = (bleRxHead + 1) % sizeof(bleRxQueue);
        if (next != bleRxTail) {
          bleRxQueue[bleRxHead] = (char)data[i];
          bleRxHead = next;
        }
      }
      portEXIT_CRITICAL(&bleRxMux);
    }
  };
#elif BT_MODE == 3
  #include <BluetoothSerial.h>
  BluetoothSerial SerialBT;
  String btSppRxLine = "";
#endif

// ---- Pulse Interrupts ----
portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;
volatile uint32_t coinPulses = 0;
volatile uint32_t coinLastMs = 0;
volatile uint32_t billPulses = 0;
volatile uint32_t billLastMs = 0;
uint32_t testBtnLastMs = 0;

void IRAM_ATTR onCoinPulse() {
  uint32_t now = millis();
  portENTER_CRITICAL_ISR(&mux);
  if (now - coinLastMs >= PULSE_DEBOUNCE_MS) {
    coinPulses++;
    coinLastMs = now;
  }
  portEXIT_CRITICAL_ISR(&mux);
}

void IRAM_ATTR onBillPulse() {
  uint32_t now = millis();
  portENTER_CRITICAL_ISR(&mux);
  if (now - billLastMs >= PULSE_DEBOUNCE_MS) {
    billPulses++;
    billLastMs = now;
  }
  portEXIT_CRITICAL_ISR(&mux);
}

// ---- Relay Helpers ----
void setRelay(uint8_t idx, bool on) {
  if (idx >= NUM_RELAYS || idx >= 8) return;
  uint8_t level = RELAY_ACTIVE_LOW ? (on ? LOW : HIGH) : (on ? HIGH : LOW);
  digitalWrite(RELAY_PINS[idx], level);
}

void allRelaysOff() {
  for (uint8_t i = 0; i < NUM_RELAYS && i < 8; i++) {
    setRelay(i, false);
  }
  flashRelayActive = false;
}

void triggerFlashRelay() {
  if (NUM_RELAYS < 3) return;
  setRelay(2, true); // Ch 3: RELAY_FLASH_PIN
  flashRelayActive = true;
  flashRelayOffAt = millis() + FLASH_PULSE_MS;
}

// ---- Serial / Bluetooth Writers ----
void sendBtAck(const char *msg) {
#if BT_MODE == 2
  if (bleClientConnected && pTxChar != nullptr) {
    pTxChar->setValue((uint8_t *)msg, strlen(msg));
    pTxChar->notify();
  }
#elif BT_MODE == 3
  if (SerialBT.hasClient()) {
    SerialBT.print(msg);
  }
#else
  Serial.print(msg);
#endif
}

void sendLineToHost(const char *msg) {
  Serial.print(msg);
#if BT_MODE == 2
  if (bleClientConnected && pTxChar != nullptr) {
    pTxChar->setValue((uint8_t *)msg, strlen(msg));
    pTxChar->notify();
  }
#elif BT_MODE == 3
  if (SerialBT.hasClient()) {
    SerialBT.print(msg);
  }
#endif
}

void blinkLed(int times) {
  for (int i = 0; i < times; i++) {
    digitalWrite(LED_PIN, HIGH);
    delay(35);
    digitalWrite(LED_PIN, LOW);
    if (i + 1 < times) delay(35);
  }
}

void sendCredit(uint32_t pesos, bool bypassCashOpen) {
  if (pesos == 0 || pesos > 5000) return;
#if REQUIRE_CASH_OPEN == 1
  if (!bypassCashOpen && !cashAccepting) return;
#endif

  char msg[16];
  snprintf(msg, sizeof(msg), "c%lu\n", (unsigned long)pesos);
  Serial.print(msg);

#if BT_MODE == 1
  if (bleKeyboard.isConnected()) {
    char num[12];
    snprintf(num, sizeof(num), "c%lu", (unsigned long)pesos);
    bleKeyboard.print(num);
    delay(15);
    bleKeyboard.write(KEY_RETURN);
  }
#elif BT_MODE == 2
  if (bleClientConnected && pTxChar != nullptr) {
    pTxChar->setValue((uint8_t *)msg, strlen(msg));
    pTxChar->notify();
  }
#elif BT_MODE == 3
  if (SerialBT.hasClient()) {
    SerialBT.print(msg);
  }
#endif

  blinkLed(2);
}

// ---- NeoPixel Animations (Non-blocking) ----
#if USE_NEOPIXEL == 1
uint32_t wheelColor(byte pos) {
  pos = 255 - pos;
  if (pos < 85) return strip.Color(255 - pos * 3, 0, pos * 3);
  if (pos < 170) { pos -= 85; return strip.Color(0, pos * 3, 255 - pos * 3); }
  pos -= 170;
  return strip.Color(pos * 3, 255 - pos * 3, 0);
}

void fillColor(uint32_t c) {
  for (uint16_t i = 0; i < strip.numPixels(); i++) strip.setPixelColor(i, c);
  strip.show();
}

void setCountdownRing(uint8_t sec, uint8_t r, uint8_t g, uint8_t b) {
  uint16_t n = strip.numPixels();
  uint16_t lit = (sec == 3) ? n : (sec == 2) ? max((uint16_t)1, (uint16_t)((n * 2) / 3)) : max((uint16_t)1, (uint16_t)(n / 3));
  strip.clear();
  for (uint16_t i = 0; i < lit; i++) strip.setPixelColor(i, strip.Color(r, g, b));
  strip.show();
}

void updateNeoPixel(uint32_t now) {
  if (now - lastLedUpdateMs < 35) return;
  lastLedUpdateMs = now;
  animStep++;

  // Timed transitions back to default states
  uint32_t elapsed = now - stateEnteredMs;
  if (boothState == ST_FLASH && elapsed >= FLASH_PULSE_MS) {
    boothState = ST_SESSION_START;
  } else if ((boothState == ST_CANCEL || boothState == ST_PRINT_DONE) && elapsed >= 1800) {
    boothState = ST_IDLE;
  }

  switch (boothState) {
    case ST_IDLE: {
      for (uint16_t i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, wheelColor(((i * 256 / strip.numPixels()) + animStep * 2) & 255));
      }
      strip.show();
      break;
    }
    case ST_TEMPLATE_SELECT: {
      strip.clear();
      uint16_t head = animStep % strip.numPixels();
      for (uint16_t k = 0; k < 4; k++) {
        strip.setPixelColor((head + k) % strip.numPixels(), strip.Color(0, 190, 255));
      }
      strip.show();
      break;
    }
    case ST_CASH_OPEN: {
      uint8_t br = 80 + (uint8_t)(85.0 * (0.5 + 0.5 * sin(animStep * 0.25)));
      fillColor(strip.Color(br, (uint8_t)(br * 0.8), 0));
      break;
    }
    case ST_PAYMENT_OK: {
      fillColor(strip.Color(0, 255, 90));
      break;
    }
    case ST_SESSION_START: {
      // Bright neutral-warm studio fill light
      fillColor(strip.Color(255, 240, 220));
      break;
    }
    case ST_CD_3: setCountdownRing(3, 255, 45, 45); break;
    case ST_CD_2: setCountdownRing(2, 255, 175, 0); break;
    case ST_CD_1: setCountdownRing(1, 0, 255, 80); break;
    case ST_FLASH: {
      fillColor(strip.Color(255, 255, 255));
      break;
    }
    case ST_PRINTING: {
      strip.clear();
      uint16_t head = animStep % strip.numPixels();
      for (uint16_t i = 0; i < strip.numPixels(); i++) {
        uint16_t d = (i + strip.numPixels() - head) % strip.numPixels();
        strip.setPixelColor(i, d < 5 ? strip.Color(60, 130, 255) : strip.Color(15, 0, 45));
      }
      strip.show();
      break;
    }
    case ST_PRINT_DONE: {
      fillColor((animStep % 6 < 3) ? strip.Color(0, 255, 100) : strip.Color(40, 255, 180));
      break;
    }
    case ST_CANCEL: {
      fillColor((animStep % 6 < 3) ? strip.Color(255, 20, 20) : strip.Color(40, 0, 0));
      break;
    }
  }
}
#endif

// ---- Incoming Command Handler ----
void setBoothState(BoothState st) {
  boothState = st;
  stateEnteredMs = millis();
  animStep = 0;
}

void handleAppCommand(String cmd) {
  cmd.trim();
  if (cmd.length() == 0) return;

  // Log incoming command cleanly to Arduino Serial Monitor ("RX: <command>")
  Serial.print("RX: ");
  Serial.println(cmd);

  if (cmd == "session_idle") {
    cashAccepting = false;
    setRelay(0, false); // Ch 1 Cash Acceptor OFF
    setRelay(1, false); // Ch 2 Studio Light OFF
    setRelay(2, false);
    setBoothState(ST_IDLE);
  } else if (cmd == "template_selection") {
    setBoothState(ST_TEMPLATE_SELECT);
  } else if (cmd.startsWith("price{") && cmd.endsWith("}")) {
    String numStr = cmd.substring(6, cmd.length() - 1);
    targetPesos = (uint32_t)numStr.toInt();
  } else if (cmd.startsWith("credit{") && cmd.endsWith("}")) {
    String numStr = cmd.substring(7, cmd.length() - 1);
    creditPesos = (uint32_t)numStr.toInt();
  } else if (cmd == "cash_open") {
    cashAccepting = true;
    setRelay(0, true);  // Ch 1 Cash Acceptor ON
    setBoothState(ST_CASH_OPEN);
  } else if (cmd == "cash_close") {
    cashAccepting = false;
    setRelay(0, false); // Ch 1 Cash Acceptor OFF
  } else if (cmd == "payment_success") {
    cashAccepting = false;
    setRelay(0, false); // Ch 1 Cash Acceptor OFF
    setBoothState(ST_PAYMENT_OK);
  } else if (cmd == "session_start") {
    setRelay(1, true);  // Ch 2 Studio Light ON
    setBoothState(ST_SESSION_START);
  } else if (cmd == "countdown_3") {
    setBoothState(ST_CD_3);
  } else if (cmd == "countdown_2") {
    setBoothState(ST_CD_2);
  } else if (cmd == "countdown_1") {
    setBoothState(ST_CD_1);
  } else if (cmd == "shutter_flash") {
    triggerFlashRelay(); // Ch 3 Strobe/Flash Relay pulse
    setBoothState(ST_FLASH);
  } else if (cmd == "start_print") {
    setRelay(3, true);  // Ch 4 Aux / Printing Light Relay ON
    setBoothState(ST_PRINTING);
  } else if (cmd == "print_done") {
    setRelay(3, false); // Ch 4 Aux / Printing Light Relay OFF
    setBoothState(ST_PRINT_DONE);
  } else if (cmd == "session_end") {
    cashAccepting = false;
    setRelay(0, false); // Cash Acceptor OFF
    setRelay(1, false); // Studio Light OFF
    setBoothState(ST_IDLE);
  } else if (cmd == "session_cancel") {
    cashAccepting = false;
    allRelaysOff();
    setBoothState(ST_CANCEL);
  } else if (cmd == "all_off") {
    cashAccepting = false;
    allRelaysOff();
    setBoothState(ST_IDLE);
  } else if (cmd == "ping") {
    sendLineToHost("pong\n");
    return;
  } else if (cmd.startsWith("ch") && cmd.length() >= 6) {
    // Manual test helpers: ch1_on .. ch8_on, ch1_off .. ch8_off
    int ch = cmd.charAt(2) - '1';
    if (ch >= 0 && ch < NUM_RELAYS) {
      if (cmd.endsWith("_on")) setRelay((uint8_t)ch, true);
      else if (cmd.endsWith("_off")) setRelay((uint8_t)ch, false);
    }
  } else {
    return;
  }

  // Acknowledge back to the app over Bluetooth TX (safe because it does not start with 'c' + digits)
  String ack = "ok:" + cmd + "\n";
  sendBtAck(ack.c_str());
  digitalWrite(LED_PIN, HIGH);
  delay(10);
  digitalWrite(LED_PIN, LOW);
}

void feedRxChar(String &buf, char ch) {
  if (ch == '\n' || ch == '\r' || ch == ';') {
    if (buf.length() > 0) {
      String cmd = buf;
      buf = "";
      handleAppCommand(cmd);
    }
  } else if (buf.length() < 96) {
    buf += ch;
  }
}

void pollIncomingCommands() {
  while (Serial.available() > 0) {
    feedRxChar(usbRxLine, (char)Serial.read());
  }
#if BT_MODE == 2
  static String bleRxLine = "";
  for (;;) {
    char ch = 0;
    bool hasChar = false;
    portENTER_CRITICAL(&bleRxMux);
    if (bleRxTail != bleRxHead) {
      ch = bleRxQueue[bleRxTail];
      bleRxTail = (bleRxTail + 1) % sizeof(bleRxQueue);
      hasChar = true;
    }
    portEXIT_CRITICAL(&bleRxMux);
    if (!hasChar) break;
    feedRxChar(bleRxLine, ch);
  }
#elif BT_MODE == 3
  while (SerialBT.available() > 0) {
    feedRxChar(btSppRxLine, (char)SerialBT.read());
  }
#endif
}

void setup() {
  Serial.begin(115200);
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, LOW);

  for (uint8_t i = 0; i < NUM_RELAYS && i < 8; i++) {
    pinMode(RELAY_PINS[i], OUTPUT);
    setRelay(i, false);
  }

  pinMode(COIN_PIN, INPUT_PULLUP);
  pinMode(BILL_PIN, INPUT_PULLUP);
  pinMode(TEST_BTN_PIN, INPUT_PULLUP);

  attachInterrupt(digitalPinToInterrupt(COIN_PIN), onCoinPulse, FALLING);
  attachInterrupt(digitalPinToInterrupt(BILL_PIN), onBillPulse, FALLING);

#if USE_NEOPIXEL == 1
  strip.begin();
  strip.setBrightness(NEOPIXEL_BRIGHT);
  strip.show();
#endif

#if BT_MODE == 1
  bleKeyboard.begin();
  Serial.println("Photobooth4u ESP32 ready (BLE Keyboard one-way + USB Serial two-way)");
#elif BT_MODE == 2
  BLEDevice::init(DEVICE_NAME);
  BLEServer *server = BLEDevice::createServer();
  server->setCallbacks(new NusServerCallbacks());
  BLEService *service = server->createService(NUS_SERVICE_UUID);
  pTxChar = service->createCharacteristic(NUS_TX_UUID, BLECharacteristic::PROPERTY_NOTIFY);
  pTxChar->addDescriptor(new BLE2902());
  BLECharacteristic *pRxChar = service->createCharacteristic(
    NUS_RX_UUID,
    BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_WRITE_NR
  );
  pRxChar->setCallbacks(new NusRxCallbacks());
  service->start();
  BLEAdvertising *adv = BLEDevice::getAdvertising();
  adv->addServiceUUID(NUS_SERVICE_UUID);
  adv->setScanResponse(true);
  BLEDevice::startAdvertising();
  Serial.println("Photobooth4u ESP32 ready (BLE Nordic UART two-way + USB Serial)");
#elif BT_MODE == 3
  SerialBT.begin(DEVICE_NAME);
  Serial.println("Photobooth4u ESP32 ready (Classic Bluetooth SPP two-way + USB Serial)");
#else
  Serial.println("Photobooth4u ESP32 ready (USB Serial two-way)");
#endif

  setBoothState(ST_IDLE);
  blinkLed(3);
}

void loop() {
#if BT_MODE == 2
  if (bleLogConnected) {
    bleLogConnected = false;
    Serial.println("Bluetooth connected");
  }
  if (bleLogDisconnected) {
    bleLogDisconnected = false;
    Serial.println("Bluetooth disconnected");
  }
  if (bleNeedReAdv) {
    bleNeedReAdv = false;
    delay(150);
    BLEDevice::startAdvertising();
  }
#elif BT_MODE == 3
  static bool btSppWasConnected = false;
  bool btSppNow = SerialBT.hasClient();
  if (btSppNow != btSppWasConnected) {
    btSppWasConnected = btSppNow;
    Serial.println(btSppNow ? "Bluetooth connected" : "Bluetooth disconnected");
  }
#endif

  pollIncomingCommands();

  uint32_t now = millis();

  // Turn off momentary Flash/Strobe Relay pulse when done
  if (flashRelayActive && (int32_t)(now - flashRelayOffAt) >= 0) {
    setRelay(2, false);
    flashRelayActive = false;
  }

  // Count completed coin/bill pulse trains
  uint32_t cCount = 0;
  uint32_t bCount = 0;
  portENTER_CRITICAL(&mux);
  if (coinPulses > 0 && (now - coinLastMs) >= COIN_TRAIN_GAP_MS) {
    cCount = coinPulses;
    coinPulses = 0;
  }
  if (billPulses > 0 && (now - billLastMs) >= BILL_TRAIN_GAP_MS) {
    bCount = billPulses;
    billPulses = 0;
  }
  portEXIT_CRITICAL(&mux);

  if (cCount > 0) sendCredit(cCount * COIN_PESOS_PER_PULSE, false);
  if (bCount > 0) sendCredit(bCount * BILL_PESOS_PER_PULSE, false);

  // Hardware test button (BOOT button on ESP32 -> credits PHP 10)
  if (digitalRead(TEST_BTN_PIN) == LOW && (now - testBtnLastMs) > 600) {
    testBtnLastMs = now;
    sendCredit(10, true);
  }

#if USE_NEOPIXEL == 1
  updateNeoPixel(now);
#endif

  delay(8);
}

Turn it on in photobooth4u

  1. For Cash Acceptor + Relays / NeoPixels: Open Setup → 7 Session → Payment & vouchers, switch on Cash acceptor (coins / bills, ESP32), pick Bluetooth serial (or USB cable, serial), and tap Connect ESP32 to choose Photobooth4u-Cash. (Use Free for coins/bills only, or pair with QR payment / Vouchers.)
  2. Multiple pricing tiers, prints & printer routing: Enable Multiple payment options (e.g. Option 1 / Option 2) to create custom-labeled tiers (e.g. Option 1–4, Classic Strip), set prices, included prints (1–5 prints or No print: softcopy only), layout filters (Thermal / Receipt, Normal / Coloured, or Any layout), and optional dedicated printers per option. Selecting a tier displays it cleanly as Template Price and shows live ✓ Covered by ₱X credit or ₱X more needed badges when coin/bill balance is waiting.
  3. Idle credit expiry & welcome banner controls: Keep Expire unused credit when idle enabled (10 minutes default, adjustable 1–60 min) to clear leftover coin/bill credit back to ₱0 and send credit{0} when idle, or switch it off to keep waiting balances indefinitely. Toggle Hide price & options banner on welcome screen if you want a cleaner attract screen (the pill already hides outside the live Photo Session welcome view).
  4. For Relays / NeoPixels only (free events): Open Setup → 7 Session → Sound & lighting, switch on ESP32 Relay Lighting & NeoPixels, pick Bluetooth serial (or USB), and tap Connect ESP32.
  5. Use the built-in Test Light ON / Test Flash / Test Cash Open / Test Idle buttons (and Test: add ₱10 or the ESP32 BOOT button) to verify your relays, LEDs, and coin/bill credits before switching to Photo Session.

Android & Huawei Tablet note (v1.2.26+): Because the ESP32 uses its own dedicated Bluetooth bridge (window.__Esp32Bridge) inside the Android Offline App, you can stay connected to your ESP32 controller and a Bluetooth thermal printer at the exact same time. Nearby Devices permission prompts auto-resume discovery, and Huawei/EMUI tablets (including MatePad models) discover Photobooth4u-Cash reliably with fast two-way serial writes.

3. PayMongo QR Ph: Default Server vs Your Own Cloudflare Account

How PayMongo works by default (plug-and-play)

Out of the box, you do not need any third-party site or Cloudflare account. Connect your PayMongo secret key once in My Events → Guest payments:

  • photobooth4u’s own Netlify backend talks directly to api.paymongo.com and automatically configures the PayMongo webhook on your account.
  • Your secret key is encrypted at rest (AES-256-GCM), write-only, and never sent to the booth tablet.
  • 100% of guest payments go straight to your own PayMongo account (minus PayMongo’s standard 1.5% QR Ph fee).

Optional: Host PayMongo API & Webhook on YOUR OWN Cloudflare Account

If you want zero-trust control where your PayMongo secret key and webhook signing secret never leave your own Cloudflare account, deploy our single-file Worker below.

Option A — Cloudflare Dashboard (No CLI · 2 minutes in your browser)

  1. Log in at dash.cloudflare.com → Workers & Pages → Create → Create Worker (name it e.g. photobooth4u-paymongo) → Deploy.
  2. Click Edit code, replace the starter code with worker.js below (use Copy worker.js), and click Deploy.
  3. Go to your Worker’s Settings → Variables and Secrets → Add:
    • Secret PAYMONGO_SECRET_KEY = your sk_live_... (or sk_test_... to test first).
    • Secret BOOTH_TOKEN (recommended) = any random password you invent (only your booths will know it).
  4. Copy your Worker’s root URL, e.g. https://photobooth4u-paymongo.yourname.workers.dev (do not append /api/pay).

Option B — Wrangler CLI (for developers)

  1. Download worker.js and wrangler.toml into an empty folder.
  2. Run:
    npx wrangler login
    npx wrangler deploy
    npx wrangler secret put PAYMONGO_SECRET_KEY
    npx wrangler secret put BOOTH_TOKEN

Optional: Instant Webhook Confirmation (KV + PayMongo Webhook)

You can skip this step to start! Even with no KV and no webhook, your Worker polls PayMongo directly every 2.5 seconds and confirms QR Ph payments automatically.

To add instant webhook push notifications too:

  1. In Cloudflare Dashboard → Storage & Databases → KV → create a namespace → bind it to your Worker as variable name PAY_KV.
  2. Register the webhook on your PayMongo account (PayMongo creates webhooks via API; replace sk_live_YOUR_KEY and your Worker URL):
    curl https://api.paymongo.com/v1/webhooks \
      -u sk_live_YOUR_KEY: \
      -H "Content-Type: application/json" \
      -d '{"data":{"attributes":{"url":"https://photobooth4u-paymongo.yourname.workers.dev/webhook","events":["payment.paid"]}}}'
  3. Copy the secret_key (whsk_...) from PayMongo’s JSON response and add it as Cloudflare Worker Secret PAYMONGO_WEBHOOK_SECRET.

Connect your Cloudflare Worker inside photobooth4u

  1. Open photobooth4u (Web, Android Offline App, or Windows/Mac App) → Setup → 7 Session → Payment & vouchers.
  2. Expand Self-hosted PayMongo (your own Cloudflare Worker · optional).
  3. Paste your Worker root URL (and BOOTH_TOKEN if set), tap Test connection, then tap Save Worker.
  4. Select QR payment (or QR + vouchers). Your Worker URL and token are stored only on that device — photobooth4u’s servers never receive your PayMongo key.
View / Copy Cloudflare Worker code (worker.js)
Zero dependencies · Web Crypto HMAC-SHA256 · KV optional
// Self-hosted PayMongo QR Ph API & Webhook Worker for photobooth4u.
// Deploy this to YOUR OWN Cloudflare account so your PayMongo secret key and
// webhook signing secret never leave Cloudflare.
//
// Required Worker secret:
//   PAYMONGO_SECRET_KEY      sk_live_... or sk_test_...
// Optional Worker secrets:
//   PAYMONGO_WEBHOOK_SECRET  whsk_... (from PayMongo -> Developers -> Webhooks)
//   BOOTH_TOKEN              shared secret pasted into the booth's Setup panel
// Optional KV binding (for instant webhook confirmation):
//   PAY_KV                   Cloudflare KV namespace
// Optional plain env vars:
//   ALLOWED_ORIGIN           default "*" (or "https://photobooth4u.netlify.app")
//   PAYMONGO_API_BASE        default "https://api.paymongo.com/v1"

const QR_SECONDS = 300;
const PRICE_MIN = 20;
const PRICE_MAX = 20000;
const PI_RE = /^pi_[A-Za-z0-9]{6,60}$/;

function corsHeaders(env) {
  return {
    'access-control-allow-origin': (env && env.ALLOWED_ORIGIN) || '*',
    'access-control-allow-methods': 'POST, OPTIONS',
    'access-control-allow-headers': 'content-type, authorization',
    'access-control-max-age': '86400'
  };
}

function json(data, status, env) {
  return new Response(JSON.stringify(data), {
    status: status || 200,
    headers: {
      'content-type': 'application/json',
      'cache-control': 'no-store',
      ...corsHeaders(env)
    }
  });
}

function timingSafeEqualStr(a, b) {
  const ea = new TextEncoder().encode(String(a || ''));
  const eb = new TextEncoder().encode(String(b || ''));
  if (ea.length !== eb.length) return false;
  let diff = 0;
  for (let i = 0; i < ea.length; i++) diff |= ea[i] ^ eb[i];
  return diff === 0;
}

async function hmacSha256Hex(secret, message) {
  const enc = new TextEncoder();
  const key = await crypto.subtle.importKey(
    'raw',
    enc.encode(secret),
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['sign']
  );
  const sig = await crypto.subtle.sign('HMAC', key, enc.encode(message));
  return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, '0')).join('');
}

// PayMongo-Signature: t=<ts>,te=<test sig>,li=<live sig>; HMAC-SHA256 of "<t>.<raw body>".
export async function signatureOk(header, raw, secret, live) {
  if (!secret || !header) return false;
  const parts = Object.fromEntries(
    String(header).split(',').map((s) => s.trim().split('=')).filter((x) => x.length === 2)
  );
  const want = live ? parts.li : parts.te;
  if (!parts.t || !want) return false;
  const ts = Number(parts.t);
  if (!Number.isFinite(ts) || Math.abs(Date.now() / 1000 - ts) >= 3 * 86400) return false;
  const mine = await hmacSha256Hex(secret, parts.t + '.' + raw);
  return timingSafeEqualStr(mine, want);
}

async function pm(env, method, path, body) {
  const base = ((env && env.PAYMONGO_API_BASE) || 'https://api.paymongo.com/v1').replace(/\/+$/, '');
  const key = String((env && env.PAYMONGO_SECRET_KEY) || '').trim();
  const r = await fetch(base + path, {
    method,
    headers: {
      authorization: 'Basic ' + btoa(key + ':'),
      'content-type': 'application/json',
      accept: 'application/json'
    },
    body: body ? JSON.stringify(body) : undefined
  });
  const j = await r.json().catch(() => ({}));
  if (!r.ok) {
    const e0 = (j && j.errors && j.errors[0]) || {};
    const err = new Error(String(e0.detail || e0.code || ('PayMongo error ' + r.status)).slice(0, 200));
    err.status = r.status;
    throw err;
  }
  return j;
}

async function createQr(env, { amount, description }) {
  const pi = await pm(env, 'POST', '/payment_intents', {
    data: {
      attributes: {
        amount: Math.round(amount * 100),
        currency: 'PHP',
        payment_method_allowed: ['qrph'],
        capture_type: 'automatic',
        description: String(description || 'Photo booth session').slice(0, 120),
        metadata: { booth: 'photobooth4u', self_hosted: 'cloudflare' }
      }
    }
  });
  let method = null;
  for (const extra of [{}, { billing: { name: 'Photo booth guest', email: 'guest@photobooth4u.app' } }]) {
    try {
      method = await pm(env, 'POST', '/payment_methods', {
        data: { attributes: { type: 'qrph', expiry_seconds: QR_SECONDS, ...extra } }
      });
      break;
    } catch (e) {
      if (Object.keys(extra).length) throw e;
    }
  }
  const at = await pm(env, 'POST', '/payment_intents/' + pi.data.id + '/attach', {
    data: {
      attributes: {
        payment_method: method.data.id,
        client_key: pi.data.attributes.client_key
      }
    }
  });
  const code = at && at.data && at.data.attributes && at.data.attributes.next_action && at.data.attributes.next_action.code;
  const image = code && (code.image_url || code.image);
  if (!image) throw new Error('PayMongo did not return a QR code. Is QR Ph enabled on your PayMongo account?');
  return {
    id: pi.data.id,
    image: /^data:image\//.test(image) ? image : 'data:image/png;base64,' + image
  };
}

async function kvGet(env, key) {
  if (!env || !env.PAY_KV) return null;
  const raw = await env.PAY_KV.get(key);
  if (!raw) return null;
  try { return JSON.parse(raw); } catch { return null; }
}

async function kvPut(env, key, val) {
  if (!env || !env.PAY_KV) return;
  await env.PAY_KV.put(key, JSON.stringify(val), { expirationTtl: 1800 });
}

async function handleWebhook(req, env) {
  if (req.method !== 'POST') return new Response('ok');
  const raw = await req.text();
  if (!env.PAYMONGO_WEBHOOK_SECRET) return new Response('webhook secret not configured', { status: 503 });
  let ev;
  try { ev = JSON.parse(raw); } catch { return new Response('bad json', { status: 400 }); }
  const attrs = ev && ev.data && ev.data.attributes;
  const live = !!(attrs && attrs.livemode);
  const ok = await signatureOk(req.headers.get('paymongo-signature'), raw, env.PAYMONGO_WEBHOOK_SECRET, live);
  if (!ok) return new Response('bad signature', { status: 401 });

  if (attrs && attrs.type === 'payment.paid') {
    const pay = attrs.data || {};
    const pa = pay.attributes || {};
    const piId = pa.payment_intent_id;
    if (piId && PI_RE.test(piId) && env.PAY_KV) {
      const k = 'pi:' + piId;
      const prev = await kvGet(env, k);
      if (prev) {
        if (prev.status !== 'paid' && Math.round(prev.amount * 100) === Number(pa.amount)) {
          prev.status = 'paid';
          prev.paidAt = Date.now();
          prev.payId = pay.id || null;
          prev.hook = true;
          await kvPut(env, k, prev);
        }
      } else {
        await kvPut(env, k, {
          id: piId,
          amount: Math.round(Number(pa.amount) || 0) / 100,
          status: 'paid',
          paidAt: Date.now(),
          payId: pay.id || null,
          hook: true
        });
      }
    }
  }
  return new Response('ok');
}

function authOk(req, env) {
  const want = String((env && env.BOOTH_TOKEN) || '').trim();
  if (!want) return true;
  const got = String(req.headers.get('authorization') || '');
  if (!got.startsWith('Bearer ')) return false;
  return timingSafeEqualStr(got.slice(7).trim(), want);
}

export default {
  async fetch(req, env) {
    const url = new URL(req.url);
    const path = url.pathname.replace(/\/+$/, '') || '/';

    if (req.method === 'OPTIONS') {
      return new Response(null, { status: 204, headers: corsHeaders(env) });
    }
    if (path === '/webhook' || path === '/api/pay/hook') {
      return handleWebhook(req, env);
    }
    if (req.method !== 'POST') {
      return json({ ok: true, service: 'photobooth4u-paymongo-worker' }, 200, env);
    }
    if (!authOk(req, env)) {
      return json({ error: 'Unauthorized: check your Booth access token.' }, 401, env);
    }

    const key = String((env && env.PAYMONGO_SECRET_KEY) || '').trim();
    if (!/^sk_(test|live)_[A-Za-z0-9]{10,100}$/.test(key)) {
      return json({ error: 'PAYMONGO_SECRET_KEY secret is not configured on this Cloudflare Worker.' }, 503, env);
    }
    const isLive = key.startsWith('sk_live_');

    let b;
    try { b = await req.json(); } catch { return json({ error: 'Bad request' }, 400, env); }
    if (!b || typeof b.action !== 'string') return json({ error: 'Bad request' }, 400, env);

    if (b.action === 'config') {
      return json({
        ok: true,
        acct: {
          connected: true,
          mode: isLive ? 'live' : 'test',
          last4: key.slice(-4),
          webhook: !!env.PAYMONGO_WEBHOOK_SECRET,
          kv: !!env.PAY_KV,
          selfHosted: true
        }
      }, 200, env);
    }

    if (b.action === 'qr') {
      const amount = Math.floor(Number(b.amount) || 0);
      if (amount < PRICE_MIN || amount > PRICE_MAX) {
        return json({ error: 'Amount must be between ₱' + PRICE_MIN + ' and ₱' + PRICE_MAX + '.' }, 400, env);
      }
      const prints = Math.max(0, Math.min(10, Math.floor(Number(b.prints) || 0)));
      const tier = (b.tier === 'receipt' || b.tier === 'photo') ? b.tier : 'all';
      const now = Date.now();
      const exp = now + QR_SECONDS * 1000;
      try {
        const qr = await createQr(env, {
          amount,
          description: (String(b.label || '').slice(0, 60) || 'Photo booth') + ' · photo session'
        });
        await kvPut(env, 'pi:' + qr.id, { id: qr.id, amount, prints, tier, status: 'awaiting', at: now, exp, live: isLive });
        return json({ ok: true, id: qr.id, image: qr.image, expiresAt: exp, tier, test: !isLive }, 200, env);
      } catch (e) {
        return json({ error: 'PayMongo: ' + e.message }, 502, env);
      }
    }

    if (b.action === 'simulate') {
      if (isLive) return json({ error: 'Simulate only works with a PayMongo sk_test_ key.' }, 403, env);
      const id = String(b.id || '');
      if (!PI_RE.test(id)) return json({ error: 'Bad id' }, 400, env);
      const prev = (await kvGet(env, 'pi:' + id)) || { id, prints: 0, tier: 'all' };
      prev.status = 'paid';
      prev.paidAt = Date.now();
      prev.sim = true;
      await kvPut(env, 'pi:' + id, prev);
      return json({ ok: true, status: 'paid', prints: prev.prints || 0, tier: prev.tier || 'all' }, 200, env);
    }

    if (b.action === 'status') {
      const id = String(b.id || '');
      if (!PI_RE.test(id)) return json({ error: 'Bad id' }, 400, env);
      const prev = await kvGet(env, 'pi:' + id);
      if (prev && prev.status === 'paid') {
        return json({ ok: true, status: 'paid', prints: prev.prints || 0, tier: prev.tier || 'all' }, 200, env);
      }
      // Check PayMongo directly (works both as backup to the webhook and when KV is not bound).
      try {
        const pi = await pm(env, 'GET', '/payment_intents/' + id);
        const a = pi && pi.data && pi.data.attributes;
        if (a && a.status === 'succeeded') {
          if (prev) {
            prev.status = 'paid';
            prev.paidAt = Date.now();
            await kvPut(env, 'pi:' + id, prev);
          }
          return json({ ok: true, status: 'paid', prints: (prev && prev.prints) || 0, tier: (prev && prev.tier) || 'all' }, 200, env);
        }
      } catch { /* keep waiting */ }
      const expired = prev && prev.exp && Date.now() > prev.exp + 15000;
      return json({ ok: true, status: expired ? 'expired' : 'awaiting', prints: (prev && prev.prints) || 0, tier: (prev && prev.tier) || 'all' }, 200, env);
    }

    return json({ error: 'Unknown action.' }, 400, env);
  }
};