Я использую Rest API в своем php cron для Twilio. То, что я пытаюсь сделать, это перебрать все записи из моей базы данных, для которых требуется текстовое сообщение, а затем отправить им текст.
Код работает нормально, но при возникновении ошибки скрипт не работает. Я думал, что правильно использую Exception в try / catch, но, похоже, он не выхватывает никаких ошибок и продолжает цикл sms.
<?php
chdir(dirname(__FILE__)); //need this line so cron works! cron doesn't know the relative file paths otherwise.
require_once 'core/init.php';
require 'vendor/autoload.php';
// Use the REST API Client to make requests to the Twilio REST API
use Twilio\Rest\Client;
// Your Account SID and Auth Token from twilio.com/console
$sid = 'mySid';
$token = 'myToken';
$client = new Client($sid, $token);
$db = DB::getInstance();
$appts = DB::getInstance()->query("SELECT appointments.id, contacts.id AS contact_id, CONCAT(contacts.first_name, ' ', contacts.last_name) AS contact_name, contacts.cell_phone, appointments.start AS appt_time, locations.name AS location_name, locations.phone AS location_phone, locations.sms_from_number, companies.name AS company_name
FROM
appointments
LEFT JOIN contacts ON contacts.id = appointments.contact_id
LEFT JOIN locations ON locations.id = appointments.location_id
LEFT JOIN companies ON companies.id = appointments.company_id
WHERE appt_status_id IN (2,9,10) AND
(DATE(`start`) = CURDATE() + INTERVAL 1 DAY) AND locations.sms_appt_reminders = 'Y' AND contacts.cell_phone IS NOT NULL AND contacts.cell_phone <> '' AND appointments.allDay = 0");
if ($appts->error()) {
echo 'Error occurred.';
} else {
if ($appts->results()) {
foreach($appts->results() AS $result) {
$date = date_create($result->appt_time);
//remove spaces, remove parentheses, hyphen, add +1 US country code.
$formatted_cell_number = str_replace(' ', '', $result->cell_phone);
$formatted_cell_number = str_replace('(', '', $formatted_cell_number);
$formatted_cell_number = str_replace(')', '', $formatted_cell_number);
$formatted_cell_number = str_replace('-', '', $formatted_cell_number);
$formatted_cell_number = '+1' . $formatted_cell_number;
try {
// Use the client to send text messages!
$client->messages->create(
$formatted_cell_number,
array(
'from' => $result->sms_from_number,
'body' => 'You have an appointment at ' . $result->company_name . ' (' . $result->location_name . ' office) tomorrow at ' . date_format($date, 'g:i A') . '. Please respond \'C\' to confirm this appointment. Please reply \'R\' if you need to reschedule, or call us at ' . $result->location_phone
)
);
DB::getInstance()->query("INSERT INTO sms_notifications (contact_id, sms_to_number, sms_from_number, sms_message, category_id, appt_id) VALUES ('".$result->contact_id."', '".$formatted_cell_number."', '".$result->sms_from_number."', 'Contact TEXTED to confirm appoinment on: ".$result->appt_time."', '0', '".$result->id."')");
} catch(Exception $e) {
echo $e->getStatus()."<br>";
}
}
}
}
?>
Я уверен, что есть другие способы очистки этого кода, но мне нужно сначала отловить и обработать ошибки. Как видите, после отправки текста я записываю его в таблицу базы данных для использования моей программой. Все это прекрасно работает, пока нет ошибок. Прямо сейчас, если я «отписался» от SMS, эта страница cron.php показывает ошибку сервера HTTP 500, нарушающую цикл SMS!
ОБНОВЛЕНИЯ НИЖЕ
На моем локальном сервере я получаю эту ошибку:
Fatal error: Uncaught Error: Call to undefined method Twilio\Exceptions\EnvironmentException::getStatus() in C:\Users\miche\Google Drive\Server\htdocs\test\cron_sms_appt_reminders.php:59 Stack trace: #0 {main} thrown in C:\Users\me\Google Drive\Server\htdocs\test\cron_sms_appt_reminders.php on line 59
строка 59 - echo 'error:'. $ e-> getStatus (). "
";
Я заметил, что в папке «Исключения» в API есть включенная страница php:
namespace Twilio\Exceptions;
class RestException extends TwilioException {
protected $statusCode;
/**
* Construct the exception. Note: The message is NOT binary safe.
* @link http://php.net/manual/en/exception.construct.php
* @param string $message [optional] The Exception message to throw.
* @param int $code [optional] The Exception code.
* @param int $statusCode [optional] The HTTP Status code.
* @since 5.1.0
*/
public function __construct($message, $code, $statusCode) {
$this->statusCode = $statusCode;
parent::__construct($message, $code);
}
/**
* Get the HTTP Status Code of the RestException
* @return int HTTP Status Code
*/
public function getStatusCode() {
return $this->statusCode;
}
}