-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsend_whatsapp_api_twilio.php
65 lines (52 loc) · 1.93 KB
/
send_whatsapp_api_twilio.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
//Connecting Twilio API
require __DIR__ . '/vendor/autoload.php';
use Twilio\Rest\Client;
// Twilio credentials
$accountSid = ''; //write account sid
$authToken = ''; //write auth token
$fromWhatsappNumber = '+14155238886';
// Create Twilio client
$client = new Client($accountSid, $authToken);
function sendWhatsappMessage($to, $message) {
global $client, $fromWhatsappNumber;
try {
$message = $client->messages
->create("whatsapp:$to", // To
[
"from" => "whatsapp:$fromWhatsappNumber", // From
"body" => $message,
]
);
echo "Message sent to $to: " . $message->sid . PHP_EOL;
} catch (Exception $e) {
echo "Error sending message to $to: " . $e->getMessage() . PHP_EOL;
}
}
// Debugging: Output received data
echo "Received POST data: " . print_r($_POST, true) . PHP_EOL;
// Process form data if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Extract form inputs
$message = $_POST['message'] ?? '';
$phoneNumbers = $_POST['phoneNumbers'] ?? '';
// Debugging: Output extracted data
echo "Extracted message: $message" . PHP_EOL;
echo "Extracted phone numbers: $phoneNumbers" . PHP_EOL;
// Validate inputs (you can add more validation as needed)
if (empty($message) || empty($phoneNumbers)) {
echo "Please provide both a message and phone numbers.";
} else {
// If there's only one phone number, send a single message
if (strpos($phoneNumbers, ',') === false) {
sendWhatsappMessage($phoneNumbers, $message);
} else {
// If there are multiple phone numbers, split and send individual messages
$phoneNumbersArray = explode(',', $phoneNumbers);
foreach ($phoneNumbersArray as $phoneNumber) {
sendWhatsappMessage(trim($phoneNumber), $message);
}
}
}
}
?>