@1table/sms-client
v1.0.0
Published
HTTP 客户端 SDK,用于调用短信微服务(发送模板短信、批量发送、按网关发送)
Downloads
17
Maintainers
Readme
@1table/sms-client
短信微服务的 HTTP 客户端 SDK,供其他项目集成调用已部署的短信服务,无需手写 HTTP 请求。
快速示例(在 sdk 目录内运行)
cd sms-microservice/sdk
# 确保微服务已启动(如 cd .. && npm start)
node example.js
# 只测健康检查、不真实发短信:
SMS_SKIP_SEND=1 node example.js
# 指定微服务地址与租户:
SMS_SERVICE_URL=http://localhost:8091 SMS_TENANT_ID=YQD node example.js详见 example.js。
安装
在需要调用短信服务的项目中:
npm install @1table/sms-client
# 或从本地/私有源安装
npm install file:../sms-microservice/sdk配置
| 选项 | 必填 | 说明 |
|------|------|------|
| baseUrl | 是 | 短信微服务根地址,如 http://localhost:8091 |
| tenantId | 是 | 租户 ID,对应请求头 X-Tenant-ID |
| apiKey | 否 | 可选,当前服务不参与鉴权,保留用于兼容 |
| timeout | 否 | 请求超时毫秒数,默认 10000 |
使用示例
发送模板短信(单条)
const { SmsClient } = require('@1table/sms-client');
const client = new SmsClient({
baseUrl: process.env.SMS_SERVICE_URL || 'http://localhost:8091',
tenantId: process.env.SMS_TENANT_ID || 'YQD',
});
// 使用模板 key(在微服务租户里配置的 key,如 REGISTER)
const res = await client.sendTemplate('13800138000', 'REGISTER', { code: '123456' });
console.log(res.data?.requestId);
// 或直接使用阿里云模板 code
await client.sendTemplate('13800138000', 'SMS_123456789', { code: '123456' });批量发送
const res = await client.sendBatch(
['13800138000', '13900139000'],
'REGISTER',
{ code: '123456' }
);
console.log(res.data?.success, res.data?.failed, res.data?.details);按网关发送(不依赖租户模板)
适用于 Btom 等无模板网关,或临时指定网关配置:
await client.sendByGateway('13800138000', {
content: '您的验证码是 123456,5 分钟内有效。',
gatewayType: 'btom',
});健康检查
const ok = await client.health();
console.log(ok.status);错误处理
SDK 使用 axios,请求失败(4xx/5xx 或网络错误)会抛出异常,建议业务侧 try/catch 并处理 error.response?.status 与 error.response?.data。
try {
await client.sendTemplate(mobile, 'LOGIN', { code });
} catch (err) {
if (err.response?.status === 401) {
// 缺少或无效的 X-Tenant-ID
}
if (err.response?.data?.error) {
console.error(err.response.data.error);
}
throw err;
}发布为 npm 包(可选)
- 若使用私有 npm 或公司 registry:在
sdk/下执行npm publish --access restricted(或public)。 - 若仅内网使用:可在业务项目中通过
package.json的dependency引用本地路径,例如:"@1table/sms-client": "file:../sms-microservice/sdk"。
