Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
accountyandex.php
1<?
2
4
15
17{
18 const TYPE_CODE = 'yandex';
20
21 protected $currency;
22
28 public function getList()
29 {
30 // fake
31
32 $response = Response::create(static::TYPE_CODE);
33 $response->setData(array(array('ID' => 1)));
34
35 return $response;
36 }
37
43 public function hasAccounts()
44 {
45 return false;
46 }
47
52 public function getProfile()
53 {
54 // default_avatar_id
55 // 'https://avatars.yandex.net/get-yapic//islands-50/';
56
57 $response = $this->getRequest()->getClient()->get(
58 'https://login.yandex.ru/info?format=json&oauth_token=' .
59 $this->getAuthToken()
60 );
61
62 if ($response)
63 {
64 try
65 {
66 $response = Json::decode($response);
67 }
68 catch (\Exception $exception)
69 {
70 return null;
71 }
72
73 if (is_array($response))
74 {
75 return array(
76 'ID' => $response['id'],
77 'NAME' => $response['login'],
78 'LINK' => '',
79 'PICTURE' => 'https://avatars.mds.yandex.net/get-yapic/0/0-0/islands-50',
80 );
81 }
82 }
83
84
85 return null;
86 }
87
94 public function getExpenses($accountId = null, Date $dateFrom = null, Date $dateTo = null)
95 {
96 // https://tech.yandex.ru/direct/doc/reports/example-docpage/
97 $result = new ResponseYandex();
98 $expenses = new Expenses();
99
100 // preload currency cause we can lost it if request after report
101 $this->getCurrency();
102 $result->setData(['expenses' => $expenses]);
103
104 $dateFrom = $dateFrom ?: new Date();
105 $dateTo = $dateTo ?: new Date();
106
107 $options = [
108 'params' => [
109 'SelectionCriteria' => [
110 'DateFrom' => $dateFrom->format('Y-m-d'),
111 'DateTo' => $dateTo->format('Y-m-d'),
112 ],
113 'FieldNames' => [
114 'Impressions', 'Clicks', 'Conversions', 'Cost',
115 'AvgCpc',
116 //'AvgCpm'
117 ],
118 'ReportType' => 'ACCOUNT_PERFORMANCE_REPORT',
119 'DateRangeType' => 'CUSTOM_DATE',
120 'ReportName' => 'Account Report',
121 'Format' => 'TSV',
122 'IncludeVAT' => 'YES',
123 'IncludeDiscount' => 'YES',
124 ],
125 ];
126
127 $profile = $this->getProfile();
128 if(empty($profile['NAME']))
129 {
130 return $result->addError(new Error("Can not find user name."));
131 }
132
133 $client = $this->getClient();
134 $client->setHeader('Client-Login', $profile['NAME']);
135 $client->setHeader('returnMoneyInMicros', 'false');
136 $client->setHeader('skipReportHeader', 'true');
137 //$client->setHeader('processingMode', 'online');
138 $response = $client->post(
139 $this->getYandexServerAdress() . 'reports',
140 Json::encode($options)
141 );
142
143 if($client->getStatus() != 200)
144 {
145 return $result->addError($this->getReportErrorByHttpStatus($client->getStatus()));
146 }
147 if($response)
148 {
149 $expenses->add($this->parseReportData($response));
150 }
151 else
152 {
153 return $result->addError(new Error('Empty report data'));
154 }
155
156 return $result;
157 }
158
165 public function updateAnalyticParams($accountId, array $params, array $publicPageIds = [])
166 {
167 return Response::create('yandex');
168 }
169
170 protected function getCurrency()
171 {
172 if($this->currency)
173 {
174 return $this->currency;
175 }
176 // currency is global for an account, so we get it from the first campaign.
177 $cacheString = 'analytics_yandex_currency';
178 $cachePath = '/seo/analytics/yandex/';
179 $cacheTime = 3600;
180 $cache = Cache::createInstance();
181 $currency = null;
182 if($cache->initCache($cacheTime, $cacheString, $cachePath))
183 {
184 $currency = $cache->getVars()['currency'];
185 }
186 if(!$currency)
187 {
188 $cache->clean($cacheString, $cachePath);
189 $cache->startDataCache($cacheTime);
190
191 $response = $this->getClient()->post(
192 $this->getYandexServerAdress() . 'campaigns',
193 Json::encode([
194 'method' => 'get',
195 'params' => [
196 'SelectionCriteria' => new \stdClass(),
197 'FieldNames' => ['Currency'],
198 'Page' => [
199 'Limit' => 1,
200 ],
201 ],
202 ])
203 );
204 if($response)
205 {
206 $response = Json::decode($response);
207 if(!isset($response['error']) && isset($response['result']) && isset($response['result']['Campaigns']))
208 {
209 foreach($response['result']['Campaigns'] as $campaign)
210 {
211 $currency = $campaign['Currency'];
212 break;
213 }
214 }
215 }
216
217 if($currency)
218 {
219 $cache->endDataCache(['currency' => $currency]);
220 }
221 }
222
223 $this->currency = $currency;
224
225 return $currency;
226 }
227
232 protected function getReportErrorByHttpStatus($status)
233 {
234 // https://tech.yandex.ru/direct/doc/examples-v5/php5-curl-stat1-docpage/
235 $message = 'Unknown error';
236 $code = 0;
237
238 if($status == 400)
239 {
240 $message = 'Wrong parameters or too many reports';
241 }
242 elseif($status == 201 || $status == 202)
243 {
244 $message = 'Please try later';
245 $code = static::ERROR_CODE_REPORT_OFFLINE;
246 }
247 elseif($status == 500)
248 {
249 $message = 'Some server error. Please try later';
250 }
251 elseif($status == 502)
252 {
253 $message = 'Server could not process your request in limited time. Please change your request';
254 }
255
256 return new Error($message, $code);
257 }
258
263 protected function parseReportData($data)
264 {
265 $result = [];
266 if(!is_string($data) || empty($data))
267 {
268 return $result;
269 }
270
271 $titles = [];
272 $strings = explode("\n", $data);
273 foreach($strings as $number => $string)
274 {
275 if($number === 0)
276 {
277 $titles = explode("\t", $string);
278 }
279 elseif(!empty($string) && mb_strpos($string, 'Total') !== 0)
280 {
281 $row = array_combine($titles, explode("\t", $string));
282
283 $result = $row;
284 }
285 }
286
287 $conversions = (is_numeric($result['Conversions']) && $result['Conversions'])
288 ? $result['Conversions']
289 : 0;
290 $clicks = (is_numeric($result['Clicks']) && $result['Clicks'])
291 ? $result['Clicks']
292 : 0;
293
294 $result = [
295 'impressions' => $result['Impressions'],
296 'clicks' => $result['Clicks'],
297 'actions' => $conversions + $clicks,
298 'spend' => $result['Cost'],
299 'cpc' => $result['AvgCpc'],
300 'cpm' => $result['AvgCpm'],
301 'currency' => $this->getCurrency(),
302 ];
303
304 return $result;
305 }
306
310 protected function getYandexServerAdress()
311 {
312 $isSandbox = false;
313 //$isSandbox = true;
314
315 return 'https://api' . ($isSandbox ? '-sandbox' : '') . '.direct.yandex.com/json/v5/';
316 }
317
321 protected function getAuthToken()
322 {
323 $token = $this->getRequest()->getAuthAdapter()->getToken();
324
325 return $token;
326 }
327
331 protected function getClient()
332 {
333 $client = clone $this->getRequest()->getClient();
334 $client->setHeader('Authorization', 'Bearer ' . $this->getAuthToken());
335
336 return $client;
337 }
338}
updateAnalyticParams($accountId, array $params, array $publicPageIds=[])
getExpenses($accountId=null, Date $dateFrom=null, Date $dateTo=null)