0

我想在带有 Sequelize 的 nodejs 中使用 textLOcal 在手机号码上发送 OTP。

4

1 回答 1

0

要进行 http 调用,请使用请求npm

npm 我请求 request-promise --save

创建名为“services”的文件夹并为“TextLocalSMS.js”类创建一个文件

var httprequest = require('request-promise');

module.exports = class TextLocalSMS {

constructor() {
}

async callApi(METHOD,URL,BODY){
    var options = {
        method: METHOD,
        uri: URL,
        headers:{
             'Content-Type': 'application/json',
             'Cache-Control': 'no-cache'
        },
        json:true
    };
    
    let response= await httprequest(options).then((result)=>{
        console.log(`SMS API: ${URL} RESULT =`,result);
        return result; 
    }).catch(function (err) {
        console.log(`SMS API: ${URL} ERROR =`,err.message);
        return err;
    });
    return response;
}

async sendSMS(toNumbers,rawMessage){
    let url = 'https://api.textlocal.in/send/';
    let sender = encodeURIComponent('TXTLCL');
    let encoded_message = encodeURIComponent(rawMessage);
    let body={
        apikey:'API_KEY',
        numbers:toNumbers.join(','),
        sender:sender,
        message:encoded_message
    };
    let result = await callApi('POST',url,body);
    return result;
}

}

现在当你想使用它时需要这个文件,假设在 app.js 中

var TextLocalSMS = require('./services/TextLocalSMS');

app.get('/demo',async (req,res)=>{

     // add logic for get user's phone nubmer from database here 
     // ...


     let otp = Math.floor(100000 + Math.random() * 900000);
     let text_msg = `MyWebsite.com -  OTP : ${otp} for reset your account password .`;
     let toNumbers = ['918123456789'];
     let smsService = new TextLocalSMS();
     let smsSent = await smsService.sendSMS(toNumbers,text_msg);

     // database query to store OTP with user_id in your database if otp successfully send to user 
     // ...


     return res.json(smsSent);
})
于 2021-12-25T13:35:50.783 回答