Files

138 lines
4.0 KiB
PHP
Raw Permalink Normal View History

<?php
/**
* Twilio SMS Provider
*
* SMS provider implementation for Twilio
*/
class TWP_SMS_Provider_Twilio implements TWP_SMS_Provider {
private $client;
private $default_from_number;
/**
* Constructor
*/
public function __construct() {
$account_sid = get_option('twp_account_sid');
$auth_token = get_option('twp_auth_token');
$this->default_from_number = get_option('twp_sms_from_number');
if (!empty($account_sid) && !empty($auth_token)) {
$this->client = new Twilio\Rest\Client($account_sid, $auth_token);
}
}
/**
* Send an SMS message
*
* @param string $to_number Recipient phone number (E.164 format)
* @param string $message Message body
* @param string $from_number Sender phone number (E.164 format)
* @return array Response array with 'success' and 'data' or 'error'
*/
public function send_sms($to_number, $message, $from_number = null) {
try {
if (!$this->client) {
return [
'success' => false,
'error' => 'Twilio client not initialized. Check API credentials.'
];
}
// Determine the from number
$from = $from_number ?: $this->default_from_number;
// Validate we have a from number
if (empty($from)) {
error_log('TWP SMS Error: No from number available. Please configure SMS notification number in settings.');
return [
'success' => false,
'error' => 'No SMS from number configured. Please set SMS notification number in plugin settings.'
];
}
$sms = $this->client->messages->create(
$to_number,
[
'from' => $from,
'body' => $message
]
);
return [
'success' => true,
'provider' => 'twilio',
'data' => [
'sid' => $sms->sid,
'status' => $sms->status,
'from' => $sms->from,
'to' => $sms->to,
'body' => $sms->body,
'price' => $sms->price,
'priceUnit' => $sms->priceUnit
]
];
} catch (\Twilio\Exceptions\TwilioException $e) {
return [
'success' => false,
'provider' => 'twilio',
'error' => $e->getMessage(),
'code' => $e->getCode()
];
}
}
/**
* Get provider name
*
* @return string Provider name
*/
public function get_provider_name() {
return 'Twilio';
}
/**
* Validate provider configuration
*
* @return array Response array with 'success' and 'message' or 'error'
*/
public function validate_configuration() {
$account_sid = get_option('twp_account_sid');
$auth_token = get_option('twp_auth_token');
$from_number = get_option('twp_sms_from_number');
if (empty($account_sid)) {
return [
'success' => false,
'error' => 'Twilio Account SID is not configured'
];
}
if (empty($auth_token)) {
return [
'success' => false,
'error' => 'Twilio Auth Token is not configured'
];
}
if (empty($from_number)) {
return [
'success' => false,
'error' => 'SMS from number is not configured'
];
}
if (!$this->client) {
return [
'success' => false,
'error' => 'Failed to initialize Twilio client'
];
}
return [
'success' => true,
'message' => 'Twilio SMS provider is properly configured'
];
}
}