Erro de transmissão de Twilio PHP que não funciona para o SMS

estou a usar o resto da API no meu php cron para Twilio. O que estou a tentar fazer é fazer um loop através de todos os registos da minha base de dados que requerem uma mensagem de texto, e depois enviar-lhes um texto.

O código funciona bem, mas se houver um erro, o script falha. Eu pensei que eu estou usando a exceção corretamente em uma tentativa/captura, mas não parece agarrar quaisquer erros e continuar o loop 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>";

            }

        }

    }
}

?>
Tenho a certeza que há outras formas de limpar este código, mas ... precisa pegar e lidar com os erros primeiro. Como você pode ver, uma vez que um texto é enviado, eu estou registrando isso em uma tabela de banco de dados para o uso do meu programa. Tudo isso funciona bem, desde que não haja erros. Neste momento, se eu me "desligar" da SMS, este cron.a página do php mostra um erro do Servidor HTTP 500, quebrando o ciclo de SMS!

ACTUALIZAÇÕES ABAIXO

no meu servidor local, tenho este erro:

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

A linha 59 é o eco 'erro:'. $e - >getStatus()."
";

Vejo que há uma página php incluída na pasta exceções da API que é esta:

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;
    }


}
Author: chris.cavage, 2019-10-03

1 answers

Parece que mudar $e->getStatus() para $e->getStatusCode() funciona no meu servidor ao vivo. No caso de alguém se deparar com isso, isso fez o truque para pegar o erro corretamente.

 0
Author: chris.cavage, 2019-10-04 14:59:50