Completed
Push — master ( 05d742...440320 )
by dotzero
15:21
created

B2BFamily   A

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 2
Bugs 0 Features 1
Metric Value
wmc 16
c 2
b 0
f 1
lcom 1
cbo 2
dl 0
loc 207
ccs 59
cts 86
cp 0.686
rs 10

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

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
231
{
232
}
233