B2BFamily   A
last analyzed

Complexity

Total Complexity 16

Size/Duplication

Total Lines 207
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 68.6%

Importance

Changes 0
Metric Value
wmc 16
lcom 1
cbo 2
dl 0
loc 207
rs 10
c 0
b 0
f 0
ccs 59
cts 86
cp 0.686

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A login() 0 15 2
A subscribe() 0 11 2
A unsubscribe() 0 11 2
A mail() 0 27 3
B request() 0 39 5
A getHash() 0 9 1
1
<?php
2
3
namespace AmoCRM\Helpers;
4
5
use AmoCRM\Client;
6
use AmoCRM\Request\ParamsBag;
7
8
/**
9
 * Class B2BFamily
10
 *
11
 * Хелпер для отправки письма через B2BFamily с привязкой к сделке в amoCRM
12
 *
13
 * @package AmoCRM\Helpers
14
 * @author dotzero <[email protected]>
15
 * @link http://www.dotzero.ru/
16
 * @link https://github.com/dotzero/amocrm-php
17
 *
18
 * For the full copyright and license information, please view the LICENSE
19
 * file that was distributed with this source code.
20
 */
21
class B2BFamily
22
{
23
    /**
24
     * @const string Тип HTTP запроса GET
25
     */
26
    const METHOD_GET = 'GET';
27
28
    /**
29
     * @const string Тип HTTP запроса POST
30
     */
31
    const METHOD_POST = 'POST';
32
33
    /**
34
     * @const string Тип HTTP запроса PUT
35
     */
36
    const METHOD_PUT = 'PUT';
37
38
    /**
39
     * @const string Тип HTTP запроса DELETE
40
     */
41
    const METHOD_DELETE = 'DELETE';
42
43
    /**
44
     * @var ParamsBag|null Экземпляр ParamsBag для хранения аргументов
45
     */
46
    private $parameters = null;
47
48
    /**
49
     * @var null|string
50
     */
51
    private $apikey = null;
52
53
    /**
54
     * B2BFamily constructor.
55
     *
56
     * @param Client $client экземпляр класса Client
57
     * @param $appkey B2BFamily API appkey
58
     * @param $secret B2BFamily API secret
59
     * @param $email B2BFamily e-mail клиента
60
     * @param $password B2BFamily пароль клиента
61
     */
62 4
    public function __construct(Client $client, $appkey, $secret, $email, $password)
63
    {
64 4
        $this->parameters = $client->parameters;
65
66 4
        $this->parameters->addAuth('appkey', $appkey);
67 4
        $this->parameters->addAuth('secret', $secret);
68 4
        $this->parameters->addAuth('email', $email);
69 4
        $this->parameters->addAuth('password', $password);
70 4
        $this->parameters->addAuth('hash', $this->getHash());
71 4
    }
72
73
    /**
74
     * Авторизация в сервисе B2BFamily
75
     *
76
     * @return array
77
     */
78 4
    public function login()
79
    {
80 4
        $response = $this->request(self::METHOD_POST, '/user/login', [
81 4
            'appkey' => $this->parameters->getAuth('appkey'),
82 4
            'email' => $this->parameters->getAuth('email'),
83 4
            'password' => $this->parameters->getAuth('password'),
84 4
            'hash' => $this->parameters->getAuth('hash'),
85 4
        ]);
86
87 4
        if (isset($response['apikey'])) {
88
            $this->apikey = $response['apikey'];
89
        }
90
91 4
        return $response;
92
    }
93
94
    /**
95
     * Подписка amoCRM на получение Web Hook от B2BFamily
96
     *
97
     * @return array
98
     */
99 1
    public function subscribe()
100
    {
101 1
        if ($this->apikey === null) {
102 1
            $this->login();
103 1
        }
104
105 1
        return $this->request(self::METHOD_PUT, '/subscribers/add', [
106 1
            'apikey' => $this->apikey,
107 1
            'path' => 'http://b2bf.cloudapp.net/post/',
108 1
        ]);
109
    }
110
111
    /**
112
     * Отписка amoCRM на получение Web Hook от B2BFamily
113
     *
114
     * @param integer $id Номер подписки для отключения
115
     * @return mixed
116
     */
117 1
    public function unsubscribe($id)
118
    {
119 1
        if ($this->apikey === null) {
120 1
            $this->login();
121 1
        }
122
123 1
        return $this->request(self::METHOD_DELETE, '/subscribers/delete', [
124 1
            'apikey' => $this->apikey,
125 1
            'id' => $id,
126 1
        ]);
127
    }
128
129
    /**
130
     * Отправка письма через B2BFamily с привязкой к сделке в amoCRM
131
     *
132
     * @param integer $lead_id Номер сделки в amoCRM
133
     * @param array $params Список дополнительных параметров
134
     * @return mixed
135
     */
136 1
    public function mail($lead_id = 0, $params)
137
    {
138 1
        if ($this->apikey === null) {
139 1
            $this->login();
140 1
        }
141
142 1
        $parameters = array_merge($params, [
143 1
            'apikey' => $this->apikey,
144
            'notification_settings' => [
145 1
                'sms_enable' => false,
146 1
                'email_enable' => false,
147 1
                'webhook_enable' => true,
148
            ]
149 1
        ]);
150
151 1
        if ($lead_id !== 0) {
152 1
            $parameters['custom_data'] = [
153 1
                'userDomainAmo' => $this->parameters->getAuth('domain'),
154 1
                'userLoginAmo' => $this->parameters->getAuth('login'),
155 1
                'userHashAmo' => $this->parameters->getAuth('apikey'),
156 1
                'userTypeAmo' => 2,
157 1
                'userIdAmo' => $lead_id,
158
            ];
159 1
        }
160
161 1
        return $this->request(self::METHOD_POST, '/mail', $parameters);
162
    }
163
164
    /**
165
     * Выполнить HTTP запрос и вернуть тело ответа
166
     *
167
     * @param $method
168
     * @param string $url Запрашиваемый URL
169
     * @param array $parameters
170
     * @return mixed
171
     * @throws B2BFamilyException
172
     */
173
    protected function request($method, $url, $parameters = [])
174
    {
175
        $endpoint = 'https://api.b2bfamily.com' . $url;
176
177
        if (in_array($method, [self::METHOD_GET, self::METHOD_DELETE])) {
178
            $endpoint .= '?' . http_build_query($parameters, null, '&');
179
        }
180
181
        $ch = curl_init();
182
183
        curl_setopt($ch, CURLOPT_URL, $endpoint);
184
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
185
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
186
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
187
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
188
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
189
190
        if (in_array($method, [self::METHOD_POST, self::METHOD_PUT])) {
191
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($parameters));
192
        }
193
194
        $result = curl_exec($ch);
195
        $error = curl_error($ch);
196
        $errno = curl_errno($ch);
197
198
        curl_close($ch);
199
200
        if ($error) {
201
            throw new B2BFamilyException($error, $errno);
202
        }
203
204
        $result = json_decode($result, true);
205
206
        if (isset($result['error'])) {
207
            throw new B2BFamilyException($result['error']['message'], $result['error']['code']);
208
        }
209
210
        return $result;
211
    }
212
213
    /**
214
     * Возвращает md5 хеш параметров для авторизации
215
     *
216
     * @return string
217
     */
218 4
    private function getHash()
219
    {
220 4
        return md5(implode('&', [
221 4
            'appkey=' . $this->parameters->getAuth('appkey'),
222 4
            'secret=' . $this->parameters->getAuth('secret'),
223 4
            'email=' . $this->parameters->getAuth('email'),
224 4
            'password=' . $this->parameters->getAuth('password'),
225 4
        ]));
226
    }
227
}
228