You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Twilio函数播放自定义语音后返回Studio Flow?

Twilio函数播放自定义语音后返回Studio Flow的解决方法

问题背景

需要在Twilio函数播放自定义语音消息后,回到原Studio Flow继续执行后续流程,但遇到以下问题:

  • 原代码播放语音后直接挂断通话,无法回到Flow
  • 添加twiml.redirect调用Flow URL后,日志显示URL被调用两次,第二次请求体为空,通话直接终止
  • 因需动态生成TwiML,无法使用静态TwiML Redirect

原代码:

if(calledNumber == "+11234567890")
{
 twiml.say("Biden is closed.");
}
return callback(null, twiml)

添加Redirect后的代码:

if(calledNumber == "+11234567890")
{
 twiml.say("Biden is closed.");
 twiml.redirect({method: 'POST'},'https://webhooks.twilio.com/v1/Accounts/<accountSID>/Flows/<flowSID>')
}
return callback(null, twiml)

解决方法

核心是调用Studio Flow的专属返回端点,而非直接重定向到Flow的主URL,这样能正确携带通话上下文,避免重复调用和空请求体问题:

  1. 获取并拼接返回URL:从Twilio函数的请求参数中提取EngagementSid,拼接成返回Flow的专属URL,格式为:
    https://webhooks.twilio.com/v1/Accounts/{AccountSID}/Flows/{FlowSID}/Engagements/{EngagementSid}/Actions/Return
    
  2. 使用POST方法重定向:确保Redirect使用POST方法,保证上下文参数正确传递
  3. 环境变量配置敏感信息:将AccountSID和FlowSID存入函数环境变量,避免硬编码

修正后代码

exports.handler = function(context, event, callback) {
  const twiml = new Twilio.twiml.VoiceResponse();
  const calledNumber = event.Called;
  const engagementSid = event.EngagementSid;
  // 从环境变量读取账号和Flow信息,拼接返回URL
  const returnFlowUrl = `https://webhooks.twilio.com/v1/Accounts/${context.ACCOUNT_SID}/Flows/${context.FLOW_SID}/Engagements/${engagementSid}/Actions/Return`;

  if(calledNumber === "+11234567890") {
    twiml.say("Biden is closed.");
  }
  // 无论是否播放语音,最后都重定向回Flow
  twiml.redirect({ method: 'POST' }, returnFlowUrl);

  callback(null, twiml);
};

注意事项

  • 在Twilio函数的「环境变量」中添加ACCOUNT_SID和FLOW_SID,值填写对应账号和Flow的SID
  • 确认Studio Flow中调用该函数的节点,已自动传递EngagementSid参数(Twilio默认会携带)
  • 检查函数的权限设置,确保能正常访问Studio Flow的返回端点

内容的提问来源于stack exchange,提问作者Highdel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 21:53:21