我正在为我的一个客户做一个副项目,当他们收到新的实时聊天聊天时,该项目将向他们发送文本(通过Twilio)。此 webhook(此处为文档)发送有关访问者的信息,以及他们对聊天前调查的回复。我可以发送基本消息,例如"在您的网站上进行新聊天!",但不能发送任何可变数据。这是我的代码的开始:
<?php
$data = file_get_contents('php://input');
$data = json_decode($data);
// this line loads the library
require './twilio/Services/Twilio.php';
$account_sid = $sid;
$auth_token = $token;
$client = new Services_Twilio($account_sid, $auth_token);
try {
$message = $client->account->messages->create(array(
"From" => "+12677932737",
"To" => "5555555555",
"Body" => $data,
));
} catch (Services_Twilio_RestException $e) {
$error = $e->getMessage();
}
?>
谢谢!
看起来您正在尝试将整个$data
作为消息的正文发送。
根据 Twilio 的 REST 文档,Body
变量只能是 160 个字符(正常的 SMS 长度)。
在查看您为 LiveChat 网络挂钩提供的链接时,您可能会得到几个不同的数据对象:
聊天开始时的简单 Web 挂钩示例:
{
"event_type": "chat_started",
"token": "27f41c8da685c81a890f9e5f8ce48387",
"license_id": "1025707"
}
聊天从访客信息开始:
{
"event_type": "chat_started",
"token": "27f41c8da685c81a890f9e5f8ce48387",
"license_id": "1025707",
"visitor": {
"id": "S1354547427.0c151b0e1b",
"name": "John",
"email": "john.smith@gmail.com"
}
}
聊天消息的 Web 钩子:
"chat": {
"id":"MH022RD0K5",
"started_timestamp":1358937653,
"ended_timestamp":1358939109,
"messages":[
{
"user_type":"agent",
"author_name":"John Doe",
"agent_id":"john.doe@mycompany.com",
"text":"Hello",
"timestamp":1358937653
},
{
"user_type":"supervisor",
"author_name":"James Doe",
"agent_id":"james@mycompany.com",
"text":"This is whispered message.",
"timestamp":1358937658
},
{
"user_type":"visitor",
"author_name":"Mary Brown",
"text":"How are you?",
"timestamp":1358937661
},
tags:[
"sales",
"support",
"feedback"
]
]
}
除第一个外,所有字符均超过160个字符。因此,如果您要发送原始请求正文,Twilio 不会接受它。
相反,您可以做的是返回一个自定义正文,具体取决于您要发送到 Twilio 的信息。
例如,您可以执行以下操作:
$body = "Chat started with: {$data->visitor->name}";
或者,您实际上可以发送第一条消息:
$body = "Chat message: {$data->chat->messages[0]->text}";
然后,您应该做的最后一件事是将消息修剪为 160 个字符或将它们分页,这样您的信息就不会丢失。
一个简单的修剪将是:
if (strlen($body) > 160) {
$body = substr($body, 0, 156) + '...';
}
// Then send the $body off to Twilio