@flink-app/sms-plugin
v0.12.1-alpha.45
Published
Flink plugin that makes it possible to send sms
Readme
SMS Plugin
A Flink plugin that provides SMS sending capabilities with support for 46elks and other SMS providers through a unified client interface.
Installation
Install the plugin to your Flink app project:
npm install @flink-app/sms-pluginConfiguration
Using 46elks
Configure the plugin with 46elks (a Swedish SMS service provider):
import { FlinkApp, FlinkContext } from "@flink-app/flink";
import { smsPlugin, sms46elksClient } from "@flink-app/sms-plugin";
function start() {
new FlinkApp<AppContext>({
name: "My app",
plugins: [
smsPlugin({
client: new sms46elksClient({
username: process.env.SMS_46ELKS_USERNAME!,
password: process.env.SMS_46ELKS_PASSWORD!
})
})
],
}).start();
}46elks Client Options:
interface sms46elksClientOptions {
username: string; // Your 46elks API username
password: string; // Your 46elks API password
}TypeScript Setup
Add the plugin context to your app's context type (usually in Ctx.ts):
import { FlinkContext } from "@flink-app/flink";
import { smsPluginContext } from "@flink-app/sms-plugin";
export interface Ctx extends FlinkContext<smsPluginContext> {
// Your other context properties
}Plugin Context Interface:
interface smsPluginContext {
smsPlugin: {
client: client; // Unified SMS client interface
};
}Usage in Handlers
Basic SMS
Send a simple SMS message:
import { Handler } from "@flink-app/flink";
import { Ctx } from "../Ctx";
const SendVerificationCode: Handler<Ctx, any, any> = async ({ ctx, req }) => {
await ctx.plugins.smsPlugin.client.send({
from: "MyApp",
to: ["+46701234567"],
message: "Your verification code is: 123456"
});
return { data: { success: true } };
};
export default SendVerificationCode;SMS to Multiple Recipients
Send the same message to multiple phone numbers:
await ctx.plugins.smsPlugin.client.send({
from: "MyCompany",
to: ["+46701234567", "+46709876543", "+46708765432"],
message: "Important notification: Service maintenance tonight at 10 PM."
});SMS with Dynamic Content
const SendOrderConfirmation: Handler<Ctx, OrderRequest, any> = async ({ ctx, req }) => {
const { phoneNumber, orderNumber, totalAmount } = req.body;
await ctx.plugins.smsPlugin.client.send({
from: "Shop",
to: [phoneNumber],
message: `Order ${orderNumber} confirmed! Total: ${totalAmount} SEK. Thank you for your purchase!`
});
return { data: { sent: true } };
};API Reference
SMS Type
interface sms {
from: string; // Sender name or phone number (max 11 alphanumeric characters or a valid phone number)
to: string[]; // Array of recipient phone numbers (E.164 format recommended, e.g., "+46701234567")
message: string; // SMS message content (max 160 characters for single SMS, longer messages will be split)
}Client Interface
All SMS clients implement this unified interface:
interface client {
send(sms: sms): Promise<boolean>;
}The send method returns:
true- SMS sent successfully to all recipientsfalse- SMS sending failed (errors are logged to console)
Complete Example
Here's a complete example of an SMS handler with error handling:
import { Handler } from "@flink-app/flink";
import { Ctx } from "../Ctx";
interface SendSMSRequest {
phoneNumber: string;
messageType: "verification" | "notification" | "alert";
data?: {
code?: string;
message?: string;
};
}
interface SendSMSResponse {
success: boolean;
error?: string;
}
const SendSMS: Handler<Ctx, SendSMSRequest, SendSMSResponse> = async ({ ctx, req }) => {
const { phoneNumber, messageType, data } = req.body;
// Validate phone number format
if (!phoneNumber.startsWith("+")) {
return {
data: {
success: false,
error: "Phone number must be in E.164 format (e.g., +46701234567)"
}
};
}
let message: string;
// Generate message based on type
switch (messageType) {
case "verification":
message = `Your verification code is: ${data?.code || "000000"}`;
break;
case "notification":
message = data?.message || "You have a new notification";
break;
case "alert":
message = `ALERT: ${data?.message || "Important system notification"}`;
break;
default:
return {
data: {
success: false,
error: "Invalid message type"
}
};
}
try {
const success = await ctx.plugins.smsPlugin.client.send({
from: "MyApp",
to: [phoneNumber],
message
});
return {
data: {
success,
error: success ? undefined : "Failed to send SMS"
}
};
} catch (error) {
console.error("SMS sending error:", error);
return {
data: {
success: false,
error: "An error occurred while sending SMS"
}
};
}
};
export default SendSMS;Error Handling
The SMS client handles errors internally and returns false on failure. Errors are logged to the console with JSON.stringify(ex). For production use, you should implement additional error handling and monitoring:
const success = await ctx.plugins.smsPlugin.client.send({
from: "MyApp",
to: ["+46701234567"],
message: "Test message"
});
if (!success) {
// Handle SMS sending failure
console.log("Failed to send SMS - check logs for details");
// You might want to:
// - Log to an error tracking service
// - Retry with exponential backoff
// - Alert administrators
// - Store for later retry
}Best Practices
Phone Number Formatting
Always use E.164 format for phone numbers:
- Include the country code (e.g., +46 for Sweden)
- Remove spaces, dashes, and parentheses
- Example:
+46701234567(not070-123 45 67)
// Good
to: ["+46701234567"]
// Bad
to: ["070-123 45 67"] // Missing country code and has formattingSender ID
The from field can be either:
- Alphanumeric: Up to 11 characters (e.g., "MyCompany")
- Numeric: A valid phone number in E.164 format
// Good
from: "MyApp" // Short, memorable, alphanumeric
from: "+46701234567" // Valid phone number
// Avoid
from: "MyVeryLongCompanyName" // Too long (>11 chars)Message Length
- Single SMS: Up to 160 characters
- Longer messages will be automatically split into multiple SMS
- Special characters (emojis, etc.) may reduce the character limit
Rate Limiting
Consider implementing rate limiting to avoid:
- API throttling
- Excessive costs
- Spam complaints
// Example: Track SMS sending per user
const recentSMS = await ctx.repos.smsLogRepo.findByUser(userId);
if (recentSMS.length >= 5) {
return { data: { success: false, error: "Too many SMS sent. Please try again later." } };
}Multiple Recipients
The plugin sends SMS to each recipient individually. Keep in mind:
- Each recipient counts as a separate SMS (costs apply per message)
- Messages are sent sequentially to each number
- Failure for one recipient doesn't stop delivery to others
const result = await ctx.plugins.smsPlugin.client.send({
from: "MyApp",
to: ["+46701111111", "+46702222222", "+46703333333"], // 3 separate SMS
message: "Meeting reminder: Tomorrow at 2 PM"
});
// Returns true only if ALL messages were sent successfullyImplementation Details
46elks Provider
The 46elks client:
- Uses Basic Authentication with username/password
- Sends to the 46elks API endpoint:
https://api.46elks.com/a1/sms - Processes each recipient individually in a loop
- Returns
falseif any recipient fails
Custom SMS Provider
You can implement your own SMS client by implementing the client interface:
import { client } from "@flink-app/sms-plugin";
import { sms } from "@flink-app/sms-plugin";
export class customSMSClient implements client {
private apiKey: string;
constructor(options: { apiKey: string }) {
this.apiKey = options.apiKey;
}
async send(sms: sms): Promise<boolean> {
try {
// Your custom SMS sending logic here
for (const recipient of sms.to) {
// Send to your provider's API
await yourSMSAPI.send({
from: sms.from,
to: recipient,
text: sms.message
});
}
return true;
} catch (error) {
console.log(JSON.stringify(error));
return false;
}
}
}Then use it with the plugin:
import { smsPlugin } from "@flink-app/sms-plugin";
import { customSMSClient } from "./customSMSClient";
smsPlugin({
client: new customSMSClient({
apiKey: process.env.CUSTOM_SMS_API_KEY!
})
})Troubleshooting
Messages Not Sending
- Check your API credentials are correct
- Verify phone numbers are in E.164 format
- Check the console logs for error details
- Ensure you have sufficient account balance with your SMS provider
- Verify the sender ID meets provider requirements
Failed Delivery
- The plugin returns
falseif sending fails - Check provider-specific error codes in console logs
- Some providers may delay delivery - check your provider's dashboard
Character Encoding
- The plugin sends messages in UTF-8 encoding
- Special characters and emojis may count as multiple characters
- Some providers may have different encoding rules
