ldc-web/app/Lib/LDC/MailjetSms.php
2022-06-13 17:40:44 +02:00

89 lines
2.2 KiB
PHP

<?php
namespace App\Lib\LDC;
use GuzzleHttp\Client;
use Illuminate\Contracts\Foundation\Application;
use Psr\Http\Message\ResponseInterface;
class MailjetSms
{
/** @var Application $app */
protected $app;
/** @var array $config */
protected $config = [];
/**
* MailjetSms
*
* @param \Illuminate\Contracts\Foundation\Application $app
*/
public function __construct(Application $app)
{
$this->app = $app;
$this->loadDefaultOptions();
}
/**
* loadDefaultOptions
*
* @return \App\Lib\LDC\MailjetSms
*/
protected function loadDefaultOptions(): \App\Lib\LDC\MailjetSms
{
$this->config = $this->app['config']->get('services.mailjet');
return $this;
}
/**
* buildHttpClient
*
* @return \GuzzleHttp\Client
*/
protected function buildHttpClient(): \GuzzleHttp\Client
{
return new Client([
'allow_redirects' => false,
'connect_timeout' => 3,
'verify' => false,
'headers' => [
'User-Agent' => 'LDCMailjetSms/1.0',
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization' => sprintf('Bearer %s', $this->config['sms_token']),
],
'timeout' => 5,
]);
}
/**
* send sms
*
* @param string $message
* @param string $to
* @param string|null $from
* @return \Psr\Http\Message\ResponseInterface
* @throws \GuzzleHttp\Exception\RequestException If Mailsms send service call failed.
*/
public function send(string $message, string $to, ?string $from = null): ResponseInterface
{
$from = $from ?? $this->config['sms_from'];
$client = $this->buildHttpClient();
try {
$response = $client->post($this->config['sms_endpoint'], [
'json' => [
'Text' => $message,
'From' => $from,
'To' => $to,
]
]);
} catch (\GuzzleHttp\Exception\RequestException $e) {
report($e);
throw $e;
}
return $response;
}
}