Skip to content

Custom providers ​

A provider is an object that implements IProviderGateway. The credential shape and the HTTP request belong to that object. sms-bridge selects a provider, records the attempt, and calls send().

Custom providers are a library feature. The self-hosted server does not load a class that exists only in an application. See Run a custom provider.

Interface ​

ts
interface GatewaySendContext {
  recipient: string;
  body: string;
  senderId: string;
  metadata?: Record<string, unknown>;
}

interface IProviderGateway {
  readonly type: string;
  send(ctx: GatewaySendContext): Promise<SendResult>;
  checkBalance(): Promise<number>;
}

SendResult is { success: boolean, messageId?: string, error?: string }. send() parses the vendor response and returns that object. Fields that belong only to the vendor are placed in metadata. sms-bridge does not read them.

The library copies metadata onto the BullMQ job when delivery is queued, and passes it to send() when the job runs. The HTTP API does not accept metadata.

Register an instance ​

Set gateway to a constructed object. apiKey and baseUrl are not required for that entry.

ts
import {
  SMSBridge,
  type GatewaySendContext,
  type IProviderGateway,
} from "sms-bridge";

class TwilioGateway implements IProviderGateway {
  readonly type = "twilio";

  constructor(
    private readonly account: {
      accountSid: string;
      authToken: string;
      from: string;
    },
  ) {}

  async send(ctx: GatewaySendContext) {
    // POST /2010-04-01/Accounts/{AccountSid}/Messages.json
    // Read this.account, ctx.recipient, ctx.body, ctx.senderId, and ctx.metadata.
    return { success: true, messageId: "SM123" };
  }

  async checkBalance() {
    return 0;
  }
}

const sms = new SMSBridge({
  providers: {
    twilio: {
      type: "twilio",
      senderIds: ["+15551212"],
      gateway: new TwilioGateway({
        accountSid: process.env.TWILIO_ACCOUNT_SID ?? "",
        authToken: process.env.TWILIO_AUTH_TOKEN ?? "",
        from: "+15551212",
      }),
    },
  },
  database: { type: "memory" },
});

await sms.init();

await sms.send({
  recipient: "01700000000",
  body: "Hello",
  metadata: { campaign: "otp" },
});

Register a factory ​

Use config when one class serves more than one account. config is not inspected. gateways maps a provider type to (entry) => gateway. The factory is called once for each provider id. entry is { id, type, senderIds, config }.

ts
class OnnoRokomGateway implements IProviderGateway {
  readonly type = "onnorokom";

  constructor(
    private readonly account: { userName: string; userPassword: string },
  ) {}

  async send(_ctx: GatewaySendContext) {
    return { success: true, messageId: "ok-1" };
  }

  async checkBalance() {
    return 0;
  }
}

const sms = new SMSBridge({
  providers: {
    onnorokom: {
      type: "onnorokom",
      senderIds: ["BRAND"],
      config: {
        userName: process.env.OR_USER ?? "",
        userPassword: process.env.OR_PASSWORD ?? "",
      },
    },
  },
  gateways: {
    onnorokom: (entry) =>
      new OnnoRokomGateway(
        entry.config as { userName: string; userPassword: string },
      ),
  },
  database: { type: "memory" },
});

Resolution ​

For each provider id, during init():

  1. When gateway is set, that instance is used.
  2. Otherwise, when gateways[type] is set, the factory is called with config.
  3. Otherwise, when type is bulksmsbd, greenweb, or sandbox, the built-in factory is used. bulksmsbd and greenweb require apiKey. baseUrl uses the default documented in Library when it is omitted.
  4. Otherwise, init() throws Unknown provider type: <type> (provider "<id>").

A factory whose key is bulksmsbd, greenweb, or sandbox replaces that built-in for every entry of that type.

routingHint on send() selects a candidate whose id, name, or type is equal to the hint. senderIds is the sender ID passed to send() when the profile does not set one.

Run a custom provider ​

bun run dev, bun run worker, and the container call createContainer() with no library configuration. A class that is not part of this repository is not constructed.

Construct SMSBridge in the application process, call startWorker() when redis.useQueue is true, and expose the HTTP route that should call sms.send(). Mount the UI with createDashboard(sms). Both calls are shown in Library.

A provider that has to be available from the server image is added in this repository. The steps are in Contributing. The server then reads that provider from environment variables or from configs.yaml.

Balance ​

bun run pulse calls checkBalance() on each active built-in gateway and writes the number to SQLite and Redis. It does not construct gateways that were registered on an SMSBridge instance. Call checkBalance() on the instance the application constructed.