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

基于Twilio Client实现呼入通话功能求助(附呼出代码)

Twilio Client 呼入通话功能实现方案

核心步骤与代码实现

结合你已有的呼出代码,只需添加来电事件监听与处理逻辑即可实现呼入功能,以下是适配Vue环境的完整代码补充:

<script>
import { Device } from 'twilio-client';

export default {
  data() {
    return {
      muted: false,
      onPhone: false,
      connection: null,
      // 新增呼入相关状态
      hasIncomingCall: false,
      incomingConnection: null,
      incomingCaller: ''
    };
  },
  mounted() {
    // 监听来电事件
    Device.on('incoming', (connection) => {
      this.incomingConnection = connection;
      this.incomingCaller = connection.parameters.From; // 获取来电号码
      this.hasIncomingCall = true;
    });

    // 监听通话断开事件,重置状态
    Device.on('disconnect', () => {
      this.onPhone = false;
      this.hasIncomingCall = false;
      this.incomingConnection = null;
      this.$emit('hangupCall', false);
    });
  },
  methods: {
    toggleMute() {
      this.muted = !this.muted;
      Device.activeConnection()?.mute(this.muted); // 可选链避免空报错
    },

    toggleCall: function() {
      if (!this.onPhone) {
        this.muted = false;
        this.onPhone = true;
        this.connection = Device.connect({ 
          number: this.callData.ProspNumber, 
          callerID: this.user.Twilio 
        });
      } else {
        Device.disconnectAll();
        this.$emit('hangupCall', false);
      }
    },

    // 接听来电
    answerIncomingCall() {
      if (this.incomingConnection) {
        this.incomingConnection.accept();
        this.onPhone = true;
        this.hasIncomingCall = false;
        this.connection = this.incomingConnection;
      }
    },

    // 拒绝来电
    rejectIncomingCall() {
      if (this.incomingConnection) {
        this.incomingConnection.reject();
        this.hasIncomingCall = false;
        this.incomingConnection = null;
      }
    }
  }
};
</script>

关键注意事项

  • 确保你的Twilio号码已配置正确的呼入Webhook:当有来电时,Twilio会向你的后端服务发送请求,后端需返回包含<Dial><Client>你的客户端标识</Client></Dial>的TwiML,将呼叫转接到Twilio Client。
  • 状态变量hasIncomingCall和incomingCaller可用于在页面上渲染来电提示(比如显示来电号码、接听/拒绝按钮)。
  • 调用Device.activeConnection()时建议用可选链操作符,避免无活跃通话时报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 19:22:53