使用TypeScript发送短信:API库与集成

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

使用TypeScript发送短信:API与库概览

现代Web应用和服务通常需要与短信网关集成,以发送通知、确认信息或营销消息。TypeScript作为JavaScript的超集,提供了严格的类型检查,这在处理外部API时尤其有用。本文将介绍如何使用流行的库和服务,从TypeScript应用程序中组织短信发送。



为什么选择TypeScript处理短信API?

TypeScript添加了静态类型检查,减少了运行时错误。在与短信提供商合作时,这一点至关重要,因为API请求通常包含复杂的数据结构(电话号码、文本、发送参数)。类型有助于避免字段名称拼写错误,并确保数据正确传输。



用于发送短信的主要库

市场上有几种流行的服务提供用于发送短信的HTTP API。我们来看看TypeScript最常用的两个选项。



1. Twilio(官方SDK)

Twilio是云通信领域的领导者之一。其Node.js官方SDK与TypeScript完全兼容,并附带现成的类型。

安装:

npm install twilionpm install @types/twilio --save-dev  // 类型已包含,但适用于旧版本

发送短信示例:

import { Twilio } from 'twilio';

const accountSid = '您的_ACCOUNT_SID';const authToken = '您的_AUTH_TOKEN';const client = new Twilio(accountSid, authToken);

interface SmsParams { to: string; // 接收方号码,格式为+71234567890 from: string; // 发送方号码(在Twilio购买的) body: string; // 消息文本}

async function sendSms(params: SmsParams): Promise<void> { try { const message = await client.messages.create({ body: params.body, from: params.from, to: params.to, }); console.log(`短信已发送。SID: ${message.sid}`); } catch (error) { console.error('发送错误:', error); }}

// 使用sendSms({ to: '+79001234567', from: '+15005550006', body: '你好!这是来自TypeScript的测试消息。',});


2. SMS Aero(通过fetch/axios的REST API)

SMS Aero是一家俄罗斯服务商,在本地项目中很受欢迎。没有官方的TypeScript SDK,但可以使用基于fetch或axios的类型化封装。

安装:

npm install axios

带类型化请求的示例:

import axios, { AxiosResponse } from 'axios';

interface SmsAeroResponse { status: 'success' | 'error'; id?: number; message?: string;}

interface SmsAeroParams { to: string; from?: string; text: string; sign?: string; // 发送方签名}

const API_URL = 'https://gate.smsaero.ru/v2/sms/send';const EMAIL = '您的_email@example.com';const API_KEY = '您的_密钥';

async function sendSmsAero(params: SmsAeroParams): Promise<SmsAeroResponse> { const auth = Buffer.from(`${EMAIL}:${API_KEY}`).toString('base64'); const response: AxiosResponse<SmsAeroResponse> = await axios.post( API_URL, { number: params.to, text: params.text, sign: params.sign || 'SMS Aero', }, { headers: { 'Authorization': `Basic ${auth}`, 'Content-Type': 'application/json', }, } ); return response.data;}

// 使用sendSmsAero({ to: '79001234567', text: '您的验证码:1234', sign: 'MyApp',}).then(res => console.log(res));


创建通用TypeScript封装

对于可能需要更换提供商的项目,创建一个抽象接口非常方便。

推荐