npm.io
0.0.4 • Published yesterday

medusa-notification-provider

Licence
MIT
Version
0.0.4
Deps
1
Size
45 kB
Vulns
0
Weekly
0

medusa-notification-provider

Medusa v2 notification plugin that provides FCM push and WhatsApp Cloud API provider implementations for the Notification module.

Plugin Overview

medusa-notification-provider adds two notification providers that plug into Medusa’s Notification module:

  • FCM provider (id: "fcm") for push notifications via Firebase Cloud Messaging.
  • WhatsApp provider (id: "whatsapp") for WhatsApp text delivery through Meta Graph API.

The plugin solves the need for production-ready channel providers so Medusa workflows/services can send push and WhatsApp notifications through a unified notification API.

Medusa Version

Built for Medusa v2 (uses @medusajs/framework and @medusajs/medusa 2.12.4).

Installation & Setup

1) Install
npm install medusa-notification-provider firebase-admin

or

yarn add medusa-notification-provider firebase-admin
2) Register providers in medusa-config.ts
import { defineConfig } from "@medusajs/framework/utils"

export default defineConfig({
  modules: [
    {
      resolve: "@medusajs/medusa/notification",
      options: {
        providers: [
          {
            resolve: "medusa-notification-provider/providers/fcm",
            id: "fcm",
            options: {
              channels: ["push"],
              projectId: "<firebase-project-id>",
              clientEmail: "<service-account-email>",
              privateKey: "<service-account-private-key>",
            },
          },
          {
            resolve: "medusa-notification-provider/providers/whatsapp",
            id: "whatsapp",
            options: {
              channels: ["sms"],
              enabled: true,
              accessToken: "<meta-access-token>",
              wabaId: "<whatsapp-business-account-id>",
              phoneNumberId: "<phone-number-id>",
              graphAPIVersion: "v21.0",
            },
          },
        ],
      },
    },
  ],
})
3) Database migrations

This plugin does not define custom models or migrations.
No extra migration step is required for this plugin itself.

Configuration (config.ts / plugin options)

The plugin exposes option types in src/config.ts, and runtime providers consume options passed from Notification module provider registration.

FCM Provider Options

Option Type Required Default Description
projectId string Yes - Firebase project ID used to initialize Admin SDK.
clientEmail string Yes - Service account client email for Firebase credential cert.
privateKey string Yes - Service account private key (\\n sequences are normalized to newlines).

WhatsApp Provider Options

Option Type Required Default Description
enabled boolean No true Enables/disables WhatsApp sending.
accessToken string Yes - Meta Graph API access token.
wabaId string Yes - WhatsApp Business Account ID (validated as required by provider).
phoneNumberId string Yes - WhatsApp sender phone number ID used in Graph endpoint path.
graphAPIVersion string No "v21.0" Graph API version for WhatsApp send endpoint.
Complete Example Config Block
{
  resolve: "@medusajs/medusa/notification",
  options: {
    providers: [
      {
        resolve: "medusa-notification-provider/providers/fcm",
        id: "fcm",
        options: {
          channels: ["push"],
          projectId: "my-firebase-project",
          clientEmail: "firebase-adminsdk-abc@my-firebase-project.iam.gserviceaccount.com",
          privateKey: "-----BEGIN PRIVATE KEY-----\\n...\\n-----END PRIVATE KEY-----\\n",
        },
      },
      {
        resolve: "medusa-notification-provider/providers/whatsapp",
        id: "whatsapp",
        options: {
          channels: ["sms"],
          enabled: true,
          accessToken: "EAAB....",
          wabaId: "123456789012345",
          phoneNumberId: "109876543210987",
          graphAPIVersion: "v21.0",
        },
      },
    ],
  },
}

Environment Variables

No process.env.* variables are read directly in runtime source files.

Variable Required Purpose Example
None in runtime code - Provider configuration is expected through provider options in module config. -

Note: Some README/example files under src/*/README.md mention process.env, but these are documentation snippets, not runtime plugin logic.

REST APIs / Routes

The plugin includes only health-check routes.

GET /admin/plugin
  • Auth requirement: Admin route scope (typically admin-authenticated context in Medusa).
  • Request body: none
  • Query params: none
  • Response: HTTP 200 with empty body
  • Description: plugin health endpoint for admin namespace.
GET /store/plugin
  • Auth requirement: Public
  • Request body: none
  • Query params: none
  • Response: HTTP 200 with empty body
  • Description: plugin health endpoint for store namespace.
Example Requests
curl -i "http://localhost:9000/admin/plugin" \
  -H "Authorization: Bearer <admin_jwt>"
curl -i "http://localhost:9000/store/plugin"

Services

FCMNotificationProviderService

  • Location: src/providers/fcm/service.ts
  • Extends: AbstractNotificationProviderService
  • Identifier: fcm
  • What it manages:
    • validates FCM credentials from provider options
    • initializes Firebase Admin messaging client
    • builds and sends FCM message payloads
    • maps Medusa notification data into string-only FCM data payload

Key methods:

Method Signature Description
send (notification: ProviderSendNotificationDTO) => Promise<ProviderSendNotificationResultsDTO> Sends push notification using notification.to as device token.
formatDataPayload (data?: Record<string, unknown>) => Record<string, string> | undefined Converts custom data to FCM-compatible string values, excluding reserved keys.
validateOptions (options: Options) => void Validates option completeness when any FCM credential is provided.

WhatsAppNotificationProviderService

  • Location: src/providers/whatsapp/service.ts
  • Extends: AbstractNotificationProviderService
  • Identifier: whatsapp
  • What it manages:
    • validates recipient phone format (+ country-code required)
    • builds message from title/body data
    • calls WhatsApp Cloud send utility
    • surfaces provider-level Medusa errors on failures

Key methods:

Method Signature Description
send (notification: ProviderSendNotificationDTO) => Promise<ProviderSendNotificationResultsDTO> Sends WhatsApp message to notification.to phone number.
validateOptions (options: Options) => void Validates WhatsApp required options if partially supplied.

Utility functions used by providers

Function Location Description
initializeFirebaseAdmin(config) src/utils/firebase-init.ts Initializes Firebase app once using cert credentials.
getFirebaseMessaging(config) src/utils/firebase-init.ts Returns Firebase messaging instance after ensuring init.
formatWhatsAppMessage(title, body) src/utils/whatsapp-client.ts Formats text as title + blank line + body.
sendWhatsAppMessage(phoneNumber, message, config) src/utils/whatsapp-client.ts Calls Meta Graph API /messages endpoint and returns success/error result.

Workflows & Steps (Medusa v2)

No workflows (createWorkflow) or steps (createStep) are implemented in runtime plugin source code.

Subscribers / Event Hooks

No subscribers are implemented in runtime plugin source code.

Admin UI / Widgets

No admin widgets, route injections, or admin UI extensions are implemented in runtime plugin source code.

Models & Entities

No custom data models/entities are defined by this plugin.

Use Cases & Examples

  1. Order status push notifications

    • Scenario: send push updates when order state changes.
    • Use: Notification module with provider id: "fcm" and channel push.
  2. WhatsApp order confirmation

    • Scenario: send order confirmation messages to customer phone.
    • Use: Notification module with provider id: "whatsapp" and channel sms.
  3. Cross-channel fallback strategy

    • Scenario: send push when token exists and WhatsApp when phone exists.
    • Use: call notification service with one payload per channel/provider.
  4. Operational/admin alerts

    • Scenario: send WhatsApp alerts to internal team for failures/events.
    • Use: WhatsApp provider with team phone recipients.
  5. Campaign messaging

    • Scenario: run targeted promotional sends by channel preference.
    • Use: FCM for device users, WhatsApp for opted-in phone recipients.

Troubleshooting

FCM provider requires projectId, clientEmail, and privateKey options
  • Cause: Missing required FCM provider options.
  • Fix: Provide all three in provider options.
Firebase Admin SDK configuration missing...
  • Cause: Invalid/empty Firebase credentials passed to initializer.
  • Fix: Ensure valid projectId, clientEmail, and privateKey; keep escaped \\n in private key string.
Notification recipient (to) is required
  • Cause: Notification payload missing destination.
  • Fix: Set notification.to (token for FCM, phone for WhatsApp).
Phone number must include country code (e.g., +1234567890)
  • Cause: WhatsApp provider recipient format invalid.
  • Fix: Send E.164-like number with leading +.
WhatsApp is not configured or enabled
  • Cause: WhatsApp option enabled is false, or credentials are missing.
  • Fix: Set enabled: true and provide accessToken, wabaId, phoneNumberId.
Failed to send ... notification
  • Cause: Upstream provider/API failure (Firebase/Meta Graph).
  • Fix: Inspect server logs and provider credentials, verify tokens/phone IDs/access token validity.

Keywords