1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace NotificationChannels\Cmsms; |
6
|
|
|
|
7
|
|
|
use GuzzleHttp\Client as GuzzleClient; |
8
|
|
|
use Illuminate\Support\Arr; |
9
|
|
|
use NotificationChannels\Cmsms\Exceptions\CouldNotSendNotification; |
10
|
|
|
use SimpleXMLElement; |
11
|
|
|
|
12
|
|
|
class CmsmsClient |
13
|
|
|
{ |
14
|
|
|
const GATEWAY_URL = 'https://sgw01.cm.nl/gateway.ashx'; |
15
|
|
|
|
16
|
|
|
/** @var GuzzleClient */ |
17
|
|
|
protected $client; |
18
|
|
|
|
19
|
|
|
/** @var string */ |
20
|
|
|
protected $productToken; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param GuzzleClient $client |
24
|
|
|
* @param string $productToken |
25
|
|
|
*/ |
26
|
4 |
|
public function __construct(GuzzleClient $client, string $productToken) |
27
|
|
|
{ |
28
|
4 |
|
$this->client = $client; |
29
|
4 |
|
$this->productToken = $productToken; |
30
|
4 |
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param CmsmsMessage $message |
34
|
|
|
* @param string $recipient |
35
|
|
|
* |
36
|
|
|
* @throws CouldNotSendNotification |
37
|
1 |
|
*/ |
38
|
|
|
public function send(CmsmsMessage $message, string $recipient) |
39
|
1 |
|
{ |
40
|
|
|
if (is_null(Arr::get($message->toXmlArray(), 'FROM'))) { |
41
|
|
|
$message->originator(config('services.cmsms.originator')); |
42
|
|
|
} |
43
|
1 |
|
|
44
|
1 |
|
$response = $this->client->request('POST', static::GATEWAY_URL, [ |
45
|
|
|
'body' => $this->buildMessageXml($message, $recipient), |
46
|
|
|
'headers' => [ |
47
|
|
|
'Content-Type' => 'application/xml', |
48
|
|
|
], |
49
|
|
|
]); |
50
|
|
|
|
51
|
|
|
// API returns an empty string on success |
52
|
1 |
|
// On failure, only the error string is passed |
53
|
1 |
|
$body = $response->getBody()->getContents(); |
54
|
1 |
|
if (!empty($body)) { |
55
|
|
|
throw CouldNotSendNotification::serviceRespondedWithAnError($body); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* @param CmsmsMessage $message |
61
|
|
|
* @param string $recipient |
62
|
|
|
* |
63
|
2 |
|
* @return string |
64
|
|
|
*/ |
65
|
2 |
|
public function buildMessageXml(CmsmsMessage $message, string $recipient): string |
66
|
|
|
{ |
67
|
2 |
|
$xml = new SimpleXMLElement('<MESSAGES/>'); |
68
|
2 |
|
|
69
|
|
|
$xml->addChild('AUTHENTICATION') |
70
|
2 |
|
->addChild('PRODUCTTOKEN', $this->productToken); |
71
|
1 |
|
|
72
|
|
|
if ($tariff = $message->getTariff()) { |
73
|
|
|
$xml->addChild('TARIFF', (string) $tariff); |
74
|
2 |
|
} |
75
|
2 |
|
|
76
|
2 |
|
$msg = $xml->addChild('MSG'); |
77
|
|
|
foreach ($message->toXmlArray() as $name => $value) { |
78
|
2 |
|
$msg->addChild($name, (string) $value); |
79
|
|
|
} |
80
|
2 |
|
$msg->addChild('TO', $recipient); |
81
|
|
|
|
82
|
|
|
return $xml->asXML(); |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|