59 lines
1.8 KiB
PHP
59 lines
1.8 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
function twilio_request(string $sid, string $token, string $url, string $method = 'GET', array $data = []): array {
|
|
$ch = curl_init();
|
|
$opts = [
|
|
CURLOPT_URL => $url,
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_TIMEOUT => 20,
|
|
CURLOPT_USERPWD => $sid . ':' . $token,
|
|
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
|
|
CURLOPT_CUSTOMREQUEST => strtoupper($method),
|
|
];
|
|
if (strtoupper($method) === 'POST') {
|
|
$opts[CURLOPT_POSTFIELDS] = http_build_query($data);
|
|
}
|
|
curl_setopt_array($ch, $opts);
|
|
$resp = curl_exec($ch);
|
|
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
$error = curl_error($ch);
|
|
curl_close($ch);
|
|
|
|
if ($resp === false || $code < 200 || $code >= 300) {
|
|
return [
|
|
'success' => false,
|
|
'status' => $code,
|
|
'error' => $error ?: $resp,
|
|
];
|
|
}
|
|
|
|
$decoded = json_decode($resp, true);
|
|
return [
|
|
'success' => true,
|
|
'status' => $code,
|
|
'data' => $decoded ?: $resp,
|
|
];
|
|
}
|
|
|
|
function twilio_send_sms(array $twilio, string $to, string $body): array {
|
|
$url = 'https://api.twilio.com/2010-04-01/Accounts/' . urlencode($twilio['account_sid']) . '/Messages.json';
|
|
return twilio_request(
|
|
$twilio['account_sid'],
|
|
$twilio['auth_token'],
|
|
$url,
|
|
'POST',
|
|
[
|
|
'From' => $twilio['from_number'],
|
|
'To' => $to,
|
|
'Body' => $body,
|
|
]
|
|
);
|
|
}
|
|
|
|
function twilio_fetch_sms_usage(array $twilio, string $startDate, string $endDate): array {
|
|
$url = 'https://api.twilio.com/2010-04-01/Accounts/' . urlencode($twilio['account_sid'])
|
|
. '/Usage/Records/Monthly.json?Category=sms&StartDate=' . urlencode($startDate) . '&EndDate=' . urlencode($endDate);
|
|
return twilio_request($twilio['account_sid'], $twilio['auth_token'], $url);
|
|
}
|