WP Manifestindependent plugin directory
manifest / ecommerce / twork-fcm-notify

T-Work FCM Notify

πŸ”” WordPress plugin: Firebase Cloud Messaging (FCM) + WooCommerce order push notifications for mobile commerce apps

by T-Work System Β· github.com/tworksystem/twork-fcm-notify Β· website

β˜… 0stars
0forks

Install

No release zip yet. The repository archive installs, but the folder name will carry the branch suffix and updates will not flow:

wp plugin install https://github.com/tworksystem/twork-fcm-notify/archive/refs/heads/main.zip

πŸ”” A production-ready WordPress plugin that connects Firebase Cloud Messaging (FCM) with WooCommerce to deliver real-time push notifications when order statuses change β€” built for mobile commerce apps (Flutter, React Native, native Android/iOS).


πŸ“– Table of Contents


🌟 Overview

T-Work FCM Notify bridges your WordPress/WooCommerce backend and mobile clients through Firebase Cloud Messaging. It provides:

  • πŸ” Secure device token registration via WordPress REST API
  • πŸ“¦ Automatic push notifications on WooCommerce order status transitions
  • πŸ€– Cross-platform delivery (Android & iOS) using FCM HTTP v1
  • 🧩 Stable data payload keys for mobile app routing and deep linking

Ideal for T-Work Commerce, MingalarBuy, and similar WooCommerce-powered mobile storefronts.


✨ Features

Feature Description
πŸ”Œ REST API Register, update, and manage FCM device tokens per WordPress user
πŸ›’ WooCommerce Hooks Sends notifications automatically on woocommerce_order_status_changed
πŸ“² Multi-Device Support Up to 10 tokens per user with platform-aware deduplication
πŸš€ FCM HTTP v1 Modern Firebase API with OAuth2 service-account authentication
πŸ”‘ CamelCase Payloads Preserves mobile-friendly keys (userId, orderId, currentBalance)
πŸ›‘οΈ Security Hardening Input sanitization, token validation, masked debug output
πŸ”‡ Silent Suppression Optional per-request FCM skip for admin bulk saves
πŸ› Debug Endpoints Inspect registered tokens during development (masked)

πŸ— Architecture

flowchart LR
    subgraph Mobile["πŸ“± Mobile App"]
        A[FCM SDK]
    end

    subgraph WordPress["🌐 WordPress + WooCommerce"]
        B[REST: /register-token]
        C[User Meta: twork_fcm_tokens]
        D[Order Status Hook]
        E[twork_send_fcm]
    end

    subgraph Firebase["πŸ”₯ Firebase"]
        F[OAuth2 Token]
        G[FCM HTTP v1 API]
    end

    A -->|POST token| B
    B --> C
    D -->|status change| E
    E --> F
    F --> G
    G -->|push| A

πŸ“‚ Plugin Structure

twork-fcm-notify/
β”œβ”€β”€ twork-fcm-notify.php      # Main plugin bootstrap & logic
β”œβ”€β”€ serviceAccountKey.json.example
β”œβ”€β”€ .gitignore
β”œβ”€β”€ LICENSE
└── README.md

⚠️ serviceAccountKey.json is never committed. Copy from the example file locally.


πŸ“‹ Requirements

Dependency Minimum Version
WordPress 5.0+
WooCommerce 3.0+
PHP 7.4+ (OpenSSL extension required)
Firebase Project FCM enabled + Service Account JSON

πŸ“¦ Installation

1️⃣ Clone the Repository

cd wp-content/plugins
git clone https://github.com/tworksystem/twork-fcm-notify.git
cd twork-fcm-notify

2️⃣ Configure Firebase Credentials

  1. Open Firebase Console πŸ”₯
  2. Select your project (or create one)
  3. Go to Project Settings β†’ Service accounts
  4. Click Generate new private key
  5. Save the downloaded JSON as serviceAccountKey.json in this plugin folder
cp serviceAccountKey.json.example serviceAccountKey.json
# Edit serviceAccountKey.json with your real Firebase credentials
chmod 600 serviceAccountKey.json

3️⃣ Set Firebase Project ID

Edit twork-fcm-notify.php:

define('TWORK_FCM_PROJECT_ID', 'your-firebase-project-id');

4️⃣ Activate in WordPress

  1. Go to WordPress Admin β†’ Plugins
  2. Find T-Work FCM Notify
  3. Click Activate βœ…

βš™οΈ Configuration

Constant Description Default
TWORK_FCM_PROJECT_ID Firebase project ID Must be set manually
TWORK_FCM_SERVICE_ACCOUNT_JSON Path to service account JSON __DIR__ . '/serviceAccountKey.json'

πŸ”‡ Suppress FCM for a Single Request

When saving admin forms (e.g. Engagement Hub bulk updates), POST:

twork_skip_fcm_notify=1

This prevents notification storms during backend edits.


πŸ“‘ REST API Reference

Base URL: https://your-site.com/wp-json/twork/v1

πŸ” Register / Update FCM Token

POST /register-token

Registers or refreshes a device token for a WordPress user.

Request Body

{
  "userId": "123",
  "fcmToken": "dP0X4xGxR5y3z8vW2mN6kL9hJ...",
  "platform": "android"
}
Field Type Required Notes
userId string/int βœ… Valid WordPress user ID
fcmToken string βœ… FCM registration token (min 10 chars)
platform string ❌ android or ios (default: android)

Success β€” 200 OK

{
  "success": true,
  "tokenCount": 2,
  "platform": "android"
}

Error β€” 400 Bad Request

{
  "success": false,
  "error": "userId and fcmToken required"
}

cURL Example

curl -X POST "https://your-site.com/wp-json/twork/v1/register-token" \
  -H "Content-Type: application/json" \
  -d '{"userId":"123","fcmToken":"YOUR_FCM_TOKEN","platform":"ios"}'

πŸ› Debug: List User Tokens

GET /debug/tokens/{user_id}

Returns masked tokens for development. Restrict or disable in production.

Success β€” 200 OK

{
  "userId": 123,
  "tokenCount": 1,
  "tokens": [
    {
      "token": "dP0X4xGxR5y3z8vW2mN6kL9hJ...",
      "platform": "android",
      "updated_at": 1716508800
    }
  ]
}

πŸ”” Notification Behavior

Triggered on WooCommerce order status changes for logged-in customers with registered tokens.

Status Notification Title Pattern
pending Order #123 is being processed
processing Order #123 is being prepared
on-hold Order #123 is on hold
completed Order #123 has been completed
cancelled Order #123 has been cancelled
refunded Order #123 has been refunded
failed Order #123 payment failed
shipped Order #123 has been shipped

πŸ“¦ Data Payload

Every notification includes a data map (all values are strings per FCM spec):

{
  "orderId": "123",
  "status": "completed",
  "total": "99.99",
  "currency": "USD",
  "type": "order_status_update",
  "userId": "456",
  "user_id": "456"
}

Mobile apps should route on type and status for deep linking (e.g. open Order Details screen).


πŸ“± Mobile App Integration

Recommended Flow

  1. πŸ“² Obtain FCM token in the mobile app after login
  2. πŸ”— POST /register-token with WordPress user ID
  3. πŸ”” Handle foreground/background notification callbacks
  4. 🧭 Parse data.type and navigate accordingly

Flutter Example (pseudo-code)

final token = await FirebaseMessaging.instance.getToken();
await http.post(
  Uri.parse('$baseUrl/wp-json/twork/v1/register-token'),
  headers: {'Content-Type': 'application/json'},
  body: jsonEncode({
    'userId': userId.toString(),
    'fcmToken': token,
    'platform': Platform.isIOS ? 'ios' : 'android',
  }),
);

πŸ’‘ Re-register the token on app launch and whenever Firebase refreshes it.


πŸ›‘ Security

βœ… Built-In Protections

  • WordPress sanitization on all REST inputs
  • User existence validation before token storage
  • Platform whitelist (android / ios)
  • Token deduplication and 10-token cap per user
  • Service account file permission warnings in logs
  • Masked tokens in debug responses

⚠️ Critical Practices

Rule Why
🚫 Never commit serviceAccountKey.json Contains private Firebase credentials
πŸ”’ chmod 600 serviceAccountKey.json Prevents world-readable secrets
πŸ”„ Rotate keys if ever exposed Invalidate compromised service accounts
πŸ›‘ Disable debug routes in production Prevents token enumeration
πŸ” Add auth to REST routes in production Current routes use open callbacks β€” wrap with JWT/app auth

Credential Rotation

If a key was leaked:

  1. Firebase Console β†’ Service Accounts β†’ delete old key
  2. Generate a new private key
  3. Replace serviceAccountKey.json
  4. Test push delivery end-to-end

πŸ› Debugging & Troubleshooting

Enable WordPress Debug Logging

Add to wp-config.php:

define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);

Logs: wp-content/debug.log β€” search for [T-Work FCM].

Common Issues

Symptom Likely Cause Fix
πŸ“΅ No push received Missing/invalid service account Verify JSON path & project ID
πŸ”΄ HTTP 401 from FCM Bad private key or clock skew Regenerate key; check server time
πŸ’Ύ Tokens not saved Invalid userId Confirm user exists in WP
πŸ“± App ignores data Key casing broken This plugin preserves camelCase keys
πŸ”• Admin save floods devices Bulk meta updates Use twork_skip_fcm_notify=1

πŸ§‘β€πŸ’» Development

Key Functions

Function Purpose
twork_register_fcm_token() REST handler for token registration
twork_send_fcm() Sends FCM v1 message to a device token
twork_get_access_token_from_sa() OAuth2 JWT exchange with Google
twork_status_message() Maps WooCommerce status to user-facing text

WordPress Hooks

  • rest_api_init β€” registers REST routes
  • woocommerce_order_status_changed β€” triggers order notifications

🀝 Contributing

Contributions are welcome! πŸŽ‰ See CONTRIBUTING.md for setup, code standards, and PR guidelines.

  1. 🍴 Fork the repository
  2. 🌿 Create a feature branch: git checkout -b feat/your-feature
  3. βœ… Commit with the convention below
  4. πŸ“€ Push and open a Pull Request

πŸ“ Commit Message Convention

<type>: 24052026 - <professional description in imperative mood>
Type When to Use
feat ✨ New feature or enhancement
fix πŸ› Bug fix
docs πŸ“š Documentation only
style πŸ’„ Formatting, no logic change
refactor ♻️ Code restructure, same behavior
perf ⚑ Performance improvement
test βœ… Tests added or updated
chore πŸ”§ Tooling, deps, maintenance
ci πŸ‘· CI/CD changes

Examples

feat: 24052026 - add FCM token registration REST endpoint
fix: 24052026 - preserve camelCase keys in FCM data payload
docs: 24052026 - expand mobile integration guide in README

πŸ“œ Changelog

πŸ—“ 24 May 2026

  • ✨ Published repository under tworksystem/twork-fcm-notify
  • πŸ“š Comprehensive README with architecture, API, and security guides
  • πŸ› FCM data payload preserves camelCase keys for Flutter/mobile clients
  • πŸ”‡ Added silent FCM suppression flag for admin bulk operations

πŸ—“ Earlier Releases

  • πŸ›’ WooCommerce order status push notifications
  • πŸ” Service-account based FCM HTTP v1 authentication
  • πŸ“² Multi-platform token storage with deduplication

πŸ“„ License

MIT License β€” see LICENSE.

Copyright (c) 2025–2026 T-Work System & contributors.


πŸ’¬ Support


Version: 1.0.0  Β·  Last Updated: 24 May 2026  Β·  Made with ❀️ for mobile commerce