如何获取Twilio号码的WhatsApp语音验证码?函数捕获失败求助
问题分析与解决方案
你的代码问题
当前函数没有配置任何语音或按键(DTMF)收集逻辑,event.SpeechResult和event.Digits只有在Twilio明确收到用户输入后才会生成值,直接读取自然会返回null。
修正后的函数代码
需要在TwiML中添加<Gather>指令,告诉Twilio收集用户的语音或按键输入,示例代码如下:
exports.handler = function(context, event, callback) { const twiml = new Twilio.twiml.VoiceResponse(); // 判断是否已收集到用户输入 if (event.SpeechResult || event.Digits) { const otpCode = event.SpeechResult || event.Digits; console.log("Captured OTP:", otpCode); twiml.say("Thank you. Your verification code has been logged."); } else { // 首次触发,提示用户输入验证码并开启收集功能 const gather = twiml.gather({ speechTimeout: 'auto', // 自动识别语音输入结束 input: 'speech dtmf', // 同时支持语音和按键输入 numDigits: 6, // 按实际OTP位数调整,通常为6位 speechModel: 'phone_call' // 适配电话场景的语音识别模型 }); gather.say("Please say or enter your WhatsApp verification code."); // 用户未输入时,重定向回当前函数重新提示 twiml.redirect({ method: 'POST' }, '/'); } callback(null, twiml); };
其他获取验证码的方法
- 启用通话录音:在Twilio号码的语音设置中开启通话录音,验证通话结束后下载录音文件,通过语音转文字工具或手动提取验证码。
- 呼叫转发到可接听号码:如果有其他可正常接听的号码,在Twilio号码的语音设置里配置呼叫转发,直接接听验证电话获取验证码。
内容的提问来源于stack exchange,提问作者Aftab Baig
相关产品推荐
相关产品推荐

