DEV Community

Narcis Bodea for SMSTunnel

Posted on Edited on Originally published at smstunnel.io Fully Autonomous

Send Medusa order SMS from your own Android phone (Medusa v2 notification provider)

Medusa's Notification Module can send texts, but the sms channel needs a provider. Here's one that hands each text to your own Android phone: the phone sends it from its own SIM, from your own number, so customers see a number they know and can simply reply to. There's no SMS provider account and no sender registration, and SMSTunnel doesn't charge per text. The same works from Payload CMS hooks and jobs, and there are Strapi and Directus versions at the end.

What you need

  • Medusa 2 (tested with 2.22.2) and Node.js 20 or newer.
  • An Android phone with a SIM card and the free SMSTunnel app, signed in to your SMSTunnel account. It sends the texts.
  • An SMSTunnel account. The free plan has 25 texts a day.

1. Get an API key

  1. Install the SMSTunnel app from Google Play on your Android phone and sign in.
  2. In the SMSTunnel dashboard, open Apps → Add an app, pick Node.js, name it (for example "My Medusa store") and click Create the key.
  3. Copy the key right away: it's shown only once. You can stop or delete the app there anytime, and the key stops working.

Put it in your Medusa environment (.env, or your host's secret settings), never in your code:

SMSTUNNEL_API_KEY=sk_live_...
Enter fullscreen mode Exit fullscreen mode

2. Install the provider

npm install @narcisbodea/smstunnel-medusa
Enter fullscreen mode Exit fullscreen mode

It has no other dependencies.

3. Register it in medusa-config.ts

module.exports = defineConfig({
  // ...
  modules: [
    {
      resolve: "@medusajs/medusa/notification",
      options: {
        providers: [
          {
            resolve: "@narcisbodea/smstunnel-medusa",
            id: "smstunnel",
            options: {
              channels: ["sms"],
              apiKey: process.env.SMSTUNNEL_API_KEY,
              // Optional:
              defaultCountryCode: "+1", // for numbers written without + or 00
              templates: {
                "order-placed": "Thanks {{ first_name }}! Your order #{{ display_id }} is confirmed.",
              },
            },
          },
        ],
      },
    },
  ],
})
Enter fullscreen mode Exit fullscreen mode

Medusa takes one provider per channel: if another provider already handles sms, swap it for this one. Medusa won't start without an apiKey, so a missing variable shows up right away.

templates holds texts by template name, with {{ placeholders }} filled from the notification's data (dots reach inside objects: {{ customer.first_name }}). defaultCountryCode completes numbers written without + or 00, and deviceId picks the phone that sends when your account has several.

4. Text the customer when an order is placed

Add a subscriber, src/subscribers/order-placed.ts:

import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"

// Texts the customer when an order is placed, from your own phone, through SMSTunnel.
export default async function orderPlacedText({ event: { data }, container }: SubscriberArgs<{ id: string }>) {
  const query = container.resolve(ContainerRegistrationKeys.QUERY)
  const notifications = container.resolve(Modules.NOTIFICATION)

  const {
    data: [order],
  } = await query.graph({
    entity: "order",
    fields: ["id", "display_id", "shipping_address.first_name", "shipping_address.phone", "billing_address.phone"],
    filters: { id: data.id },
  })
  const phone = order?.shipping_address?.phone || order?.billing_address?.phone
  if (!phone) return // the customer left no number: nothing to send

  await notifications.createNotifications({
    to: phone,
    channel: "sms",
    template: "order-placed",
    data: { first_name: order.shipping_address?.first_name ?? "", display_id: order.display_id },
    // Medusa sends a notification only once per key, and SMSTunnel won't send the same text twice either.
    idempotency_key: `order-placed-${order.id}`,
  })
}

export const config: SubscriberConfig = { event: "order.placed" }
Enter fullscreen mode Exit fullscreen mode

With the order-placed template above, the customer gets: Thanks Ana! Your order #1042 is confirmed. The same pattern works for order.fulfillment_created, order.canceled, delivery.created and the other Medusa events.

Customers type phone numbers in many ways. Ask for the international format at checkout (+14155550123), or set defaultCountryCode for your country.

From a workflow step, an API route or a scheduled job, it's the same createNotifications call. Pass the words in content.text and they're sent as they are, without a template. One notification goes to one number: to text several people, create one notification each.

When a text doesn't go out

createNotifications throws, and Medusa stores the notification with status failure and SMSTunnel's reason:

  • 401: the key is wrong, deactivated or deleted.
  • 403: the key lacks a permission, or your plan doesn't include what was asked.
  • 429: more than 30 sends a minute for this key (Retry-After says how long to wait), or today's allowance is used up.
  • 5xx, or no answer: the text may or may not have gone out. Check the Messages page in your dashboard, or send it again with the same idempotency_key.

The provider never resends a text by itself. In a subscriber, a failure is logged by Medusa and doesn't affect the order. If the phone is offline, the text isn't lost: it waits on your account and goes out as soon as the phone is back online (for up to 3 days). Each stored notification keeps SMSTunnel's message id in external_id.

Payload CMS: a text from a collection hook

The Payload plugin gives you server-side helpers for hooks, endpoints and jobs. It works with Payload 3 (tested with 3.92.1).

npm install @narcisbodea/smstunnel-payload
Enter fullscreen mode Exit fullscreen mode

Add it to payload.config.ts:

import { buildConfig } from 'payload'
import { smsTunnelPlugin } from '@narcisbodea/smstunnel-payload'

export default buildConfig({
  // ...
  plugins: [smsTunnelPlugin()],
})
Enter fullscreen mode Exit fullscreen mode

It reads the key from process.env.SMSTUNNEL_API_KEY. It adds no collections, fields or endpoints, keeps its settings in config.custom (which Payload never sends to the admin panel) and warns at start-up when there is no key.

Then text the customer once, when an order is created. src/collections/Orders.ts:

import type { CollectionConfig } from 'payload'
import { sendText } from '@narcisbodea/smstunnel-payload'

export const Orders: CollectionConfig = {
  slug: 'orders',
  fields: [
    { name: 'customerName', type: 'text' },
    { name: 'phone', type: 'text' },
  ],
  hooks: {
    afterChange: [
      async ({ doc, operation, req }) => {
        // Text the customer once, when the order is created, from your own phone.
        if (operation !== 'create' || !doc.phone) return doc
        try {
          await sendText(req.payload, {
            to: doc.phone,
            message: `Thanks ${doc.customerName ?? ''}! We got your order #${doc.id}.`,
            // The id and the creation time keep the key unique, so a retry can't send a second text.
            idempotencyKey: `order-${doc.id}-${doc.createdAt}`,
          })
        } catch (error) {
          // A text that can't go out must not fail the save: log it.
          req.payload.logger.error(`SMSTunnel: ${(error as Error).message}`)
        }
        return doc
      },
    ],
  },
}
Enter fullscreen mode Exit fullscreen mode

Keep the phone field a text field: a number field loses the + and leading zeros.

The hook waits for SMSTunnel's answer, usually well under a second. To keep saves from waiting at all, queue the text with Payload's Jobs Queue. The README has a ready textCustomer task that reuses its key on retries. Then, from a hook or an endpoint:

await req.payload.jobs.queue({ task: 'textCustomer', input: { to: doc.phone, message: '…' } })
Enter fullscreen mode Exit fullscreen mode

sendText returns { messageId, queued, replayed }. sendCode sends sign-in codes. getSmsTunnel(payload) gives you a client with getStatus, listPhones and getUsage. On failure the helpers throw an SmsTunnelError with status, retryAfter and mayHaveSent, so you know whether a retry is safe.

Strapi and Directus, briefly

Strapi 5 gets a service for your lifecycles, controllers and cron jobs, plus a settings page in the admin panel. There you can paste the key: it's checked first, then stored encrypted. The page also shows your phones and sends a test text.

npm install @narcisbodea/smstunnel-strapi
npm run build   # rebuilds the admin panel with the plugin's settings page
Enter fullscreen mode Exit fullscreen mode
const sent = await strapi.plugin('smstunnel').service('sms').send({
  to: '+14155550123',
  message: 'Your table for 4 is ready.',
});
// sent: { messageId: '6ae9952f7f9ac207c547af90', queued: false, replayed: false }
Enter fullscreen mode Exit fullscreen mode

Directus 11 and 12 get a Send a text with SMSTunnel operation for Flows. Install it from Settings → Marketplace, where it runs in the extension sandbox. Then, for example, add an Event Hook flow on items.create for a leads collection, with:

  • To: {{ $trigger.payload.phone }}
  • Message: Thanks {{ $trigger.payload.name }}, we got your request and will call you back today.
  • Idempotency key: lead-{{ $trigger.key }}

The key stays in the environment (SMSTUNNEL_API_KEY, allowed with FLOWS_ENV_ALLOW_LIST), and Directus redacts it in the flow logs.

Good to know

  • One text goes to one number. For several people, send one each.
  • 30 send requests a minute per key; over that, a 429 with Retry-After.
  • The phone sends at Android's own pace (about 30 SMS parts a minute), and a long text counts as several parts.
  • Texts can be up to 1600 characters, and sign-in codes up to 320.
  • Phone offline? The text waits on your account and goes out when the phone is back online, for up to 3 days.
  • An idempotency key makes a retry within 24 hours return the first answer instead of sending a second text.
  • Send only texts people expect: order updates, pickup notices, reminders, sign-in codes. Unsolicited texts from a personal SIM break most carriers' terms.

Full guides, with every option and an AI prompt for each:


Disclosure: I build SMSTunnel. This post was written with AI from the official setup guides linked above.

Top comments (0)