|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Sineld\OneSignalMail; |
| 4 | + |
| 5 | +use Exception; |
| 6 | +use Illuminate\Support\Facades\Http; |
| 7 | +use Illuminate\Support\Str; |
| 8 | +use Symfony\Component\Mime\Email; |
| 9 | +use Symfony\Component\Mailer\SentMessage; |
| 10 | +use Symfony\Component\Mime\MessageConverter; |
| 11 | +use Symfony\Component\Mailer\Transport\AbstractTransport; |
| 12 | + |
| 13 | +class OneSignalTransport extends AbstractTransport |
| 14 | +{ |
| 15 | + protected string $apiUrl; |
| 16 | + |
| 17 | + protected string $apiKey; |
| 18 | + |
| 19 | + protected string $appId; |
| 20 | + |
| 21 | + public function __construct(string $apiUrl, string $apiKey, string $appId) |
| 22 | + { |
| 23 | + parent::__construct(); |
| 24 | + |
| 25 | + $this->apiUrl = $apiUrl; |
| 26 | + |
| 27 | + $this->apiKey = $apiKey; |
| 28 | + |
| 29 | + $this->appId = $appId; |
| 30 | + } |
| 31 | + |
| 32 | + public function __toString(): string |
| 33 | + { |
| 34 | + return 'onesignal-mail'; |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * @throws Exception |
| 39 | + */ |
| 40 | + public function doSend(SentMessage $message): void |
| 41 | + { |
| 42 | + $email = MessageConverter::toEmail($message->getOriginalMessage()); |
| 43 | + |
| 44 | + $response = Http::withHeaders([ |
| 45 | + 'Content-Type' => 'application/json;charset=utf-8', |
| 46 | + 'Authorization' => 'Basic '.$this->apiKey, |
| 47 | + ])->post($this->apiUrl, [ |
| 48 | + 'app_id' => $this->appId, |
| 49 | + 'email_subject' => $email->getSubject(), |
| 50 | + 'email_body' => $email->getHtmlBody(), |
| 51 | + 'email_from_name' => $email->getFrom()[0]->getName(), |
| 52 | + 'email_from_address' => $email->getFrom()[0]->getAddress(), |
| 53 | + 'email_reply_to_address' => $this->getEmailAddresses($email, 'getReplyTo'), |
| 54 | + 'email_preheader' => Str::limit($email->getTextBody(), 64), |
| 55 | + 'include_email_tokens' => [$this->getEmailAddresses($email)], |
| 56 | + 'include_unsubscribed' => true, |
| 57 | + ]); |
| 58 | + |
| 59 | + if($response->failed()){ |
| 60 | + throw new Exception('OneSignal Email failed. Error: '. $response->body()); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + protected function getEmailAddresses(Email $email, string $method = 'getTo'): string |
| 65 | + { |
| 66 | + $data = call_user_func([$email, $method]); |
| 67 | + |
| 68 | + $addresses = []; |
| 69 | + if (is_array($data)) { |
| 70 | + foreach ($data as $address) { |
| 71 | + $addresses[] = $address->getAddress(); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + return implode(',', $addresses); |
| 76 | + } |
| 77 | +} |
0 commit comments