fitlien-services/functions/src/sms/sendSMS.ts

77 lines
2.3 KiB
TypeScript

import { onRequest } from "firebase-functions/v2/https";
import { Request } from "firebase-functions/v2/https";
import { getCorsHandler } from "../shared/middleware";
import { getLogger } from "../shared/config";
import twilio from 'twilio';
const corsHandler = getCorsHandler();
const logger = getLogger();
// Initialize Twilio client
const twilioClient = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
interface SMSRequest {
to: string;
body: string;
}
export const sendSMSMessage = onRequest({
region: '#{SERVICES_RGN}#'
}, async (request: Request, response) => {
return corsHandler(request, response, async () => {
try {
const { to, body } = request.body as SMSRequest;
// Input validation
if (!to || !body) {
logger.error('Missing required SMS parameters');
response.status(400).json({
success: false,
error: 'Both "to" and "body" parameters are required'
});
return;
}
// Validate phone number format (basic check)
if (!/^\+?[1-9]\d{1,14}$/.test(to)) {
logger.error('Invalid phone number format', { to });
response.status(400).json({
success: false,
error: 'Invalid phone number format'
});
return;
}
// Send SMS
const message = await twilioClient.messages.create({
body: body,
from: process.env.TWILIO_PHONE_NUMBER,
to: to
});
logger.info('SMS sent successfully', {
messageId: message.sid,
to: to,
length: body.length
});
response.json({
success: true,
messageId: message.sid,
timestamp: message.dateCreated
});
} catch (error: any) {
logger.error('Error sending SMS:', error);
const statusCode = error.status === 401 ? 401 : 500;
response.status(statusCode).json({
success: false,
error: error.message,
code: error.code,
moreInfo: error.moreInfo
});
}
});
});