如何解决 Twiml 和 TwiML 之间的混淆 - 'Invalid Content-Type' 或 'retrieval failure'

How to fix confusion between Twiml and TwiML - 'Invalid Content-Type' or 'retrieval failure'

我想为 WordPress 写一个插件,它说 'Hello World' 来电到我的 Twillio phone-号码。 我在 Twilio 管理员上为来电设置了 POST webhook:https://myWPsite.com/wp-json/callcenter/incoming。 我在它的文件夹中创建了一个带有 following code (found in Twilio Docs), and placed the Twilio PHP helper lib 的 WP 插件:

<?php
require_once( plugin_dir_path( __FILE__ ) . 'twilio-php-master/Twilio/autoload.php');
use Twilio\TwiML;

defined( 'ABSPATH' ) or die( 'Nope!' );

function respond_incoming( $data ) {
  $response = new TwiML;
  $response->say("hello world!", array('voice' => 'alice'));
  echo $response;
}

add_action( 'rest_api_init', function () {
  register_rest_route( 'callcenter', '/incoming/', array(
    'methods' => array('POST'),
    'callback' => 'respond_incoming',
  ) );
} );

如果我对我的 Twillio 号码进行 phone 调用,我会在 Twilio-Debugger 中看到以下错误:Invalid Content-Type,并且我会在响应正文中看到以下内容:

Warning: require(/wp-content/plugins/twilio-for-DNH/twilio-php-master/Twilio/TwiML.php): failed to open stream: No such file or directory in /wp-content/plugins/twilio-for-DNH/twilio-php-master/Twilio/autoload.php on line 140

Fatal error: require(): Failed opening required '/wp-content/plugins/twilio-for-DNH/twilio-php-master/Twilio/TwiML.php' (include_path='.:/opt/alt/php73/usr/share/pear') in /wp-content/plugins/twilio-for-DNH/twilio-php-master/Twilio/autoload.php on line 140

为了解决这个错误,我把use Twilio\TwiML;改成use Twilio\Twiml;,虽然我读到Twimldepracted,但我不能让它以另一种方式工作。

之后我仍然得到 Invalid Content-Type 错误,我在调试器中看到内容类型是:Content-Type application/json; charset=UTF-8。 所以我在我的函数中添加了以下行:header('content-type: text/xml');.

现在我收到 Document parse failure 错误,我的响应正文如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say voice="alice">hello world!</Say>
</Response>
null

为了解决这个问题,我在我的函数末尾添加了 die() 函数。 现在终于可以用了。 完整的工作代码是:

<?php
require_once( plugin_dir_path( __FILE__ ) . 'twilio-php-master/Twilio/autoload.php');
use Twilio\Twiml;

defined( 'ABSPATH' ) or die( 'Nope!' );

function respond_incoming( $data ) {
  $response = new TwiML;
  $response->say("hello world!", array('voice' => 'alice'));
  header('content-type: text/xml');
  echo $response;
  die();
}

add_action( 'rest_api_init', function () {
  register_rest_route( 'callcenter', '/incoming/', array(
    'methods' => array('POST'),
    'callback' => 'respond_incoming',
  ) );
} );