diff --git a/src/Utopia/Messaging/Adapter/SMS/AfricasTalking.php b/src/Utopia/Messaging/Adapter/SMS/AfricasTalking.php new file mode 100644 index 00000000..cbbea7eb --- /dev/null +++ b/src/Utopia/Messaging/Adapter/SMS/AfricasTalking.php @@ -0,0 +1,80 @@ +getType()); + + $recipients = \array_map( + fn ($to) => \ltrim($to, '+'), + $message->getTo() + ); + + $from = $this->from ?? $message->getFrom(); + + foreach ($recipients as $recipient) { + $result = $this->request( + method: 'POST', + url: self::API_URL, + headers: [ + 'Content-Type: application/x-www-form-urlencoded', + 'apiKey: ' . $this->apiKey, + ], + body: [ + 'username' => $this->username, + 'to' => $recipient, + 'message' => $message->getContent(), + 'from' => $from, + ] + ); + + if ($result['statusCode'] === 201) { + $response->incrementDeliveredTo(); + $response->addResult($recipient); + } else { + $errorMessage = 'Unknown error'; + if (isset($result['response']['errorMessage'])) { + $errorMessage = \is_string($result['response']['errorMessage']) + ? $result['response']['errorMessage'] + : \json_encode($result['response']['errorMessage']); + } elseif (isset($result['response']['message'])) { + $errorMessage = \is_string($result['response']['message']) + ? $result['response']['message'] + : \json_encode($result['response']['message']); + } + $response->addResult($recipient, $errorMessage); + } + } + + return $response->toArray(); + } +} \ No newline at end of file diff --git a/tests/Messaging/Adapter/SMS/AfricasTalkingTest.php b/tests/Messaging/Adapter/SMS/AfricasTalkingTest.php new file mode 100644 index 00000000..98edcdee --- /dev/null +++ b/tests/Messaging/Adapter/SMS/AfricasTalkingTest.php @@ -0,0 +1,56 @@ +markTestSkipped('AfricasTalking credentials are not available.'); + } + + $sender = new AfricasTalking($username, $apiKey); + + $message = new SMS( + to: [$to], + content: 'Test Content', + from: \getenv('AFRICAS_TALKING_FROM') ?: null + ); + + $response = $sender->send($message); + + $this->assertResponse($response); + } + + public function testSendSMSWithFrom(): void + { + $username = \getenv('AFRICAS_TALKING_USERNAME'); + $apiKey = \getenv('AFRICAS_TALKING_API_KEY'); + $to = \getenv('AFRICAS_TALKING_TO'); + $from = \getenv('AFRICAS_TALKING_FROM'); + + if (empty($username) || empty($apiKey) || empty($to)) { + $this->markTestSkipped('AfricasTalking credentials are not available.'); + } + + $sender = new AfricasTalking($username, $apiKey, $from ?: 'AFRICAST'); + + $message = new SMS( + to: [$to], + content: 'Test Content with custom from' + ); + + $response = $sender->send($message); + + $this->assertResponse($response); + } +} \ No newline at end of file