bb_sign/app/Helpers/NotificationHelper.php
2024-06-18 09:41:09 +05:30

85 lines
2.6 KiB
PHP

<?php
// app/Helpers/NotificationHelper.php
namespace App\Helpers;
class NotificationHelper
{
protected $email;
protected $logger;
public function __construct()
{
$this->email = service('email');
$this->logger = service('logger');
}
public function sendWhatsAppMessage($number, $message, $client_login_url = '')
{
// Extract plain text message
$plainTextMessage = strip_tags($message);
// Extract URL from message
preg_match('/<a\s+(?:[^>]*?\s+)?href="([^"]*)"/i', $client_login_url, $match);
$client_login_url = isset($match[1]) ? $match[1] : '';
// Prepare the data to send
$instance_id = $_ENV['WAAI_INSTANCE'];
$access_token = $_ENV['WAAI_TOKEN'];
$url = 'https://waai.in/api/send';
// Prepare the text for WhatsApp
if($client_login_url){
$whatsappMessage = $plainTextMessage . "\n\nClick here - " . $client_login_url;
}else{
$whatsappMessage = $plainTextMessage ;
}
// Prepare JSON payload
$postdata = json_encode([
'number' => $number,
'type' => 'text',
'message' => $whatsappMessage,
'instance_id' => $instance_id,
'access_token' => $access_token
]);
// Initialize cURL session
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($postdata)
]);
// Execute cURL session
$response = curl_exec($ch);
// Check for cURL errors
if ($response === false) {
$this->logger->error('Failed to communicate with WhatsApp API: ' . curl_error($ch));
curl_close($ch);
throw new \Exception('Failed to communicate with WhatsApp API');
}
// Get HTTP response code
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Check HTTP response code for success
if ($httpCode !== 200) {
$this->logger->error('Failed to send WhatsApp message. HTTP Code: ' . $httpCode);
throw new \Exception('Failed to send WhatsApp message. HTTP Code: ' . $httpCode);
}
// Log success or handle further
$this->logger->info('WhatsApp message sent successfully to ' . $number);
return true;
}
}
?>