1 | <?php |
||
2 | |||
3 | namespace NotificationChannels\WhatsApp; |
||
4 | |||
5 | use Illuminate\Notifications\Notification; |
||
6 | use Netflie\WhatsAppCloudApi\Response; |
||
7 | use Netflie\WhatsAppCloudApi\Response\ResponseException; |
||
8 | use Netflie\WhatsAppCloudApi\WhatsAppCloudApi; |
||
9 | use NotificationChannels\WhatsApp\Exceptions\CouldNotSendNotification; |
||
10 | |||
11 | class WhatsAppChannel |
||
12 | { |
||
13 | /* |
||
14 | * HTTP WhatsApp Cloud API wrapper |
||
15 | */ |
||
16 | private WhatsAppCloudApi $whatsapp; |
||
17 | |||
18 | 4 | public function __construct(WhatsAppCloudApi $whatsapp) |
|
19 | { |
||
20 | 4 | $this->whatsapp = $whatsapp; |
|
21 | } |
||
22 | |||
23 | /** |
||
24 | * Send the given notification. |
||
25 | */ |
||
26 | 4 | public function send($notifiable, Notification $notification): ?Response |
|
27 | { |
||
28 | // @phpstan-ignore-next-line |
||
29 | 4 | $message = $notification->toWhatsApp($notifiable); |
|
0 ignored issues
–
show
introduced
by
![]() |
|||
30 | |||
31 | 4 | if (! $message->hasRecipient()) { |
|
32 | 2 | $to = $notifiable->routeNotificationFor('whatsapp', $notification) |
|
33 | 2 | ?? $notifiable->routeNotificationFor(self::class, $notification); |
|
34 | |||
35 | 2 | if (! $to) { |
|
36 | 1 | return null; |
|
37 | } |
||
38 | |||
39 | 1 | $message->to($to); |
|
40 | } |
||
41 | |||
42 | try { |
||
43 | 3 | if ($message->type() === 'text') { |
|
44 | return $this->whatsapp->sendTextMessage( |
||
45 | $message->recipient(), |
||
46 | $message->getMessage() |
||
47 | ); |
||
48 | } |
||
49 | |||
50 | 3 | return $this->whatsapp->sendTemplate( |
|
51 | 3 | $message->recipient(), |
|
52 | 3 | $message->configuredName(), |
|
53 | 3 | $message->configuredLanguage(), |
|
54 | 3 | $message->components() |
|
55 | 3 | ); |
|
56 | 1 | } catch (ResponseException $e) { |
|
57 | 1 | throw CouldNotSendNotification::serviceRespondedWithAnError($e->response()->body()); |
|
58 | } |
||
59 | } |
||
60 | } |
||
61 |