Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
InfobipWhatsAppProvider
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 2
30
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 send
0.00% covered (danger)
0.00%
0 / 29
0.00% covered (danger)
0.00%
0 / 1
20
1<?php
2// App/Services/Communication/Providers/WhatsApp/InfobipWhatsAppProvider.php
3
4namespace App\Services\Communication\Providers\WhatsApp;
5
6use App\Services\Communication\Contracts\WhatsAppProviderInterface;
7
8class InfobipWhatsAppProvider implements WhatsAppProviderInterface
9{
10    private string $apiUrl;
11    private string $apiKey;
12    private string $from;
13
14    public function __construct(array $credentials)
15    {
16        $this->apiKey = $credentials['api_key'] ?? '';
17        $this->from   = $credentials['from']    ?? '';
18        $this->apiUrl = $credentials['api_url'] ?? 'https://api.infobip.com/whatsapp/1/message/text';
19    }
20
21    public function send(string $to, string $message): bool
22    {
23        try {
24            $client = \Config\Services::curlrequest();
25
26            $response = $client->post($this->apiUrl, [
27                'headers' => [
28                    'Authorization' => 'App ' . $this->apiKey,
29                    'Content-Type'  => 'application/json',
30                    'Accept'        => 'application/json',
31                ],
32                'json' => [
33                    'from'    => $this->from,
34                    'to'      => $to,
35                    'content' => [
36                        'text' => $message,
37                    ],
38                ],
39            ]);
40
41            $status = $response->getStatusCode();
42
43            if ($status !== 200) {
44                log_message('error', '[InfobipWhatsAppProvider] Échec envoi — HTTP ' . $status
45                    . ' — ' . $response->getBody());
46                return false;
47            }
48
49            $body      = json_decode($response->getBody(), true);
50            $msgStatus = $body['messages'][0]['status']['groupName'] ?? '';
51
52            if (!in_array($msgStatus, ['PENDING', 'DELIVERED'])) {
53                log_message('error', '[InfobipWhatsAppProvider] Statut inattendu : ' . $msgStatus);
54                return false;
55            }
56
57            return true;
58
59        } catch (\Throwable $e) {
60            log_message('error', '[InfobipWhatsAppProvider] ' . $e->getMessage());
61            return false;
62        }
63    }
64}