This repository has been archived by the owner on Jan 18, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
WebhookGateway.php
109 lines (96 loc) · 2.62 KB
/
WebhookGateway.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
/*
* This file is part of NotifyMe.
*
* (c) Alt Three Services Limited
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace NotifyMeHQ\Adapters\Webhook;
use GuzzleHttp\Client;
use NotifyMeHQ\Contracts\GatewayInterface;
use NotifyMeHQ\Http\GatewayTrait;
use NotifyMeHQ\Http\Response;
class WebhookGateway implements GatewayInterface
{
use GatewayTrait;
/**
* Create a new webhook gateway instance.
*
* @param \GuzzleHttp\Client $client
* @param string[] $config
*
* @return void
*/
public function __construct(Client $client, array $config)
{
$this->client = $client;
$this->config = $config;
}
/**
* Send a notification.
*
* @param string $to
* @param string $message
*
* @return \NotifyMeHQ\Contracts\ResponseInterface
*/
public function notify($to, $message)
{
return $this->send($this->buildUrlFromString(), ['to' => $to, 'message' => $message]);
}
/**
* Send the notification over the wire.
*
* @param string $url
* @param string[] $params
*
* @return \NotifyMeHQ\Contracts\ResponseInterface
*/
protected function send($url, array $params)
{
$success = false;
$rawResponse = $this->client->post($url, [
'exceptions' => false,
'timeout' => '80',
'connect_timeout' => '30',
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
],
'json' => $params,
]);
$response = [];
if (substr((string) $rawResponse->getStatusCode(), 0, 1) === '2') {
$success = true;
} else {
$response['error'] = 'Webhook delivery failed with status code '.$rawResponse->getStatusCode();
}
return $this->mapResponse($success, $response);
}
/**
* Map the raw response to our response object.
*
* @param bool $success
* @param array $response
*
* @return \NotifyMeHQ\Contracts\ResponseInterface
*/
protected function mapResponse($success, array $response)
{
return (new Response())->setRaw($response)->map([
'success' => $success,
'message' => $success ? 'Message sent' : $response['error'],
]);
}
/**
* Get the request url.
*
* @return string
*/
protected function getRequestUrl()
{
return $this->config['endpoint'];
}
}