如何3分钟内快速用NodeJs取短信验证码
要用NodeJs获取短信验证码,通常需要连接到一个短信服务提供商的API,并通过该API发送请求来获取验证码。由于不同的短信服务提供商可能具有不同的API和授权方式,我将以一个简单的示例介绍如何使用NodeJs语言来获取短信验证码。
在这个示例中,我们将使用中昱维信作为短信服务提供商。
1.注册账号并获取API密钥
注册并登录你的短信平台,然后获取AppID和AppKey,注册地址在代码里

2.创建验证码模版
创建验证码模版,获取验证码模版id

3.调用短信服务接口,这里给出常用的4种方式
3.1 axios
// 平台注册地址 vip.veesing.com
const axios = require('axios');
// 替换示例代码中的"YOUR_APP_ID"、"YOUR_APP_KEY"、"YOUR_TEMPLATE_ID"、"YOUR_PHONE"、"YOUR_CODE"为你在中昱维信账号中获得的实际值
let config = {
method: 'get',
maxBodyLength: Infinity,
url: 'https://vip.veesing.com/smsApi/
verifyCode?appId=YOUR_APP_ID&appKey=YOUR_APP_KEY&templateId=YOUR_TEMPLATE_ID&phone=YOUR_PHONE&variables=YOUR_CODE',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
axios.request(config)
.then((response) => {
console.log(JSON.stringify(response.data));
})
.catch((error) => {
console.log(error);
});
3.2 native
// 平台注册地址 vip.veesing.com
var https = require('follow-redirects').https;
var fs = require('fs');
// 替换示例代码中的"YOUR_APP_ID"、"YOUR_APP_KEY"、"YOUR_TEMPLATE_ID"、"YOUR_PHONE"、"YOUR_CODE"为你在中昱维信账号中获得的实际值
var options = {
'method': 'GET',
'hostname': 'vip.veesing.com',
'path': '/smsApi/verifyCode?appId=YOUR_APP_ID&appKey=YOUR_APP_KEY&templateId=YOUR_TEMPLATE_ID&phone=YOUR_PHONE&variables=YOUR_CODE',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded'
},
'maxRedirects': 20
};
var req = https.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function (chunk) {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
res.on("error", function (error) {
console.error(error);
});
});
req.end();
3.3 Request
// 平台注册地址 vip.veesing.com
var request = require('request');
var options = {
'method': 'GET',
'url': 'https://vip.veesing.com/smsApi/verifyCode?appId=YOUR_APP_ID&appKey=YOUR_APP_KEY&templateId=YOUR_TEMPLATE_ID&phone=YOUR_PHONE&variables=YOUR_CODE',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
// 替换示例代码中的"YOUR_APP_ID"、"YOUR_APP_KEY"、"YOUR_TEMPLATE_ID"、"YOUR_PHONE"、"YOUR_CODE"为你在中昱维信账号中获得的实际值
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
3.4 Unirest
// 平台注册地址 vip.veesing.com
var unirest = require('unirest');
// 替换示例代码中的"YOUR_APP_ID"、"YOUR_APP_KEY"、"YOUR_TEMPLATE_ID"、"YOUR_PHONE"、"YOUR_CODE"为你在中昱维信账号中获得的实际值
var req = unirest('GET', 'https://vip.veesing.com/smsApi/verifyCode?appId=YOUR_APP_ID&appKey=YOUR_APP_KEY&templateId=YOUR_TEMPLATE_ID&phone=YOUR_PHONE&variables=YOUR_CODE')
.headers({
'Content-Type': 'application/x-www-form-urlencoded'
})
.end(function (res) {
if (res.error) throw new Error(res.error);
console.log(res.raw_body);
});
上述代码仅供演示,实际使用时需要替换成你的API密钥以及其他必要的参数
本文详细介绍了如何使用Node.js通过中昱维信短信服务提供商的API在3分钟内获取短信验证码,提供了axios、native、Request和Unirest四种方式的代码示例。
7822

被折叠的 条评论
为什么被折叠?



