7fb7f75050
Build Docker Image / build-backend (push) Successful in 18s
Co-authored-by: ISMAIL MASSERAN <topaz@Mac.dlinkrouter.local> Co-authored-by: ISMAIL MASSERAN <topaz@ISMAILs-Macbook.local> Reviewed-on: #16
101 lines
2.7 KiB
PHP
101 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Whatsapp;
|
|
|
|
use Illuminate\Support\Facades\Http;
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
class WhatsappCloudClient
|
|
{
|
|
public function isConfigured()
|
|
{
|
|
return trim((string) config('whatsapp.token')) !== ''
|
|
&& trim((string) config('whatsapp.phone_number_id')) !== '';
|
|
}
|
|
|
|
/**
|
|
* Malaysia MSISDN for Graph API, e.g. 60193450165.
|
|
*
|
|
* @return string|null
|
|
*/
|
|
public function normalizeMsisdn($raw)
|
|
{
|
|
$digits = preg_replace('/\D+/', '', (string) $raw);
|
|
if ($digits === '') {
|
|
return null;
|
|
}
|
|
|
|
if (strpos($digits, '60') === 0) {
|
|
return $digits;
|
|
}
|
|
|
|
if (strpos($digits, '0') === 0) {
|
|
return '60' . substr($digits, 1);
|
|
}
|
|
|
|
return '60' . $digits;
|
|
}
|
|
|
|
/**
|
|
* @param string $to
|
|
* @param string $templateName
|
|
* @param string $lang
|
|
* @param array<int,string> $bodyParams
|
|
* @return \Illuminate\Http\Client\Response
|
|
*/
|
|
public function sendTemplate($to, $templateName, $lang, array $bodyParams = [])
|
|
{
|
|
$payload = [
|
|
'messaging_product' => 'whatsapp',
|
|
'to' => $to,
|
|
'type' => 'template',
|
|
'template' => [
|
|
'name' => $templateName,
|
|
'language' => ['code' => $lang],
|
|
],
|
|
];
|
|
|
|
if (count($bodyParams) > 0) {
|
|
$payload['template']['components'] = [[
|
|
'type' => 'body',
|
|
'parameters' => array_map(function ($text) {
|
|
return [
|
|
'type' => 'text',
|
|
'text' => $this->sanitizeParam($text),
|
|
];
|
|
}, array_values($bodyParams)),
|
|
]];
|
|
}
|
|
|
|
$version = config('whatsapp.api_version', 'v25.0');
|
|
$phoneId = config('whatsapp.phone_number_id');
|
|
$url = 'https://graph.facebook.com/' . $version . '/' . $phoneId . '/messages';
|
|
|
|
$response = Http::withToken(config('whatsapp.token'))
|
|
->acceptJson()
|
|
->asJson()
|
|
->post($url, $payload);
|
|
|
|
if (!$response->successful()) {
|
|
Log::error('WhatsApp Cloud send failed', [
|
|
'to' => $to,
|
|
'template' => $templateName,
|
|
'status' => $response->status(),
|
|
'body' => $response->json() ?: $response->body(),
|
|
]);
|
|
}
|
|
|
|
return $response;
|
|
}
|
|
|
|
protected function sanitizeParam($text)
|
|
{
|
|
$text = trim(preg_replace('/\s+/', ' ', (string) $text));
|
|
if ($text === '') {
|
|
return '-';
|
|
}
|
|
|
|
return mb_substr($text, 0, 200);
|
|
}
|
|
}
|