1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
accountyandex.php
См. документацию.
1<?php
2
3namespace Bitrix\Seo\Analytics\Services;
4
5use Bitrix\Main\Data\Cache;
6use Bitrix\Main\Error;
7use Bitrix\Main\Result;
8use Bitrix\Seo\Analytics\Internals\Expenses;
9use Bitrix\Main\Web\Json;
10use Bitrix\Main\Type\Date;
11use Bitrix\Seo\Retargeting\Response;
12use Bitrix\Seo\Retargeting\Services\ResponseYandex;
13use Bitrix\Seo\Retargeting\IRequestDirectly;
14use Bitrix\Seo\Analytics\Account;
15
16class AccountYandex extends Account implements IRequestDirectly
17{
18 const TYPE_CODE = 'yandex';
19
20 protected ?string $currency = null;
21
27 public function getList()
28 {
29 // fake
30
31 $response = Response::create(static::TYPE_CODE);
32 $response->setData(array(array('ID' => 1)));
33
34 return $response;
35 }
36
42 public function hasAccounts()
43 {
44 return false;
45 }
46
51 public function getProfile()
52 {
53 // default_avatar_id
54 // 'https://avatars.yandex.net/get-yapic//islands-50/';
55
56 $response = $this->getRequest()->getClient()->get(
57 'https://login.yandex.ru/info?format=json&oauth_token=' .
58 $this->getAuthToken()
59 );
60
61 if ($response)
62 {
63 try
64 {
65 $response = Json::decode($response);
66 }
67 catch (\Exception $exception)
68 {
69 return null;
70 }
71
72 if (is_array($response))
73 {
74 return array(
75 'ID' => $response['id'],
76 'NAME' => $response['login'],
77 'LINK' => '',
78 'PICTURE' => 'https://avatars.mds.yandex.net/get-yapic/0/0-0/islands-50',
79 );
80 }
81 }
82
83
84 return null;
85 }
86
93 public function getExpenses($accountId = null, Date $dateFrom = null, Date $dateTo = null)
94 {
95 // https://tech.yandex.ru/direct/doc/reports/example-docpage/
96 $result = new ResponseYandex();
97 $expenses = new Expenses();
98
99 // preload currency cause we can lost it if request after report
100 $this->getCurrency();
101 $result->setData(['expenses' => $expenses]);
102
103 $dateFrom = $dateFrom ?: new Date();
104 $dateTo = $dateTo ?: new Date();
105
106 $options = [
107 'params' => [
108 'SelectionCriteria' => [
109 'DateFrom' => $dateFrom->format('Y-m-d'),
110 'DateTo' => $dateTo->format('Y-m-d'),
111 ],
112 'FieldNames' => [
113 'Impressions', 'Clicks', 'Conversions', 'Cost',
114 'AvgCpc',
115 //'AvgCpm'
116 ],
117 'ReportType' => 'ACCOUNT_PERFORMANCE_REPORT',
118 'DateRangeType' => 'CUSTOM_DATE',
119 'ReportName' => 'Account Report',
120 'Format' => 'TSV',
121 'IncludeVAT' => 'YES',
122 'IncludeDiscount' => 'YES',
123 ],
124 ];
125
126 $profile = $this->getProfile();
127 if (empty($profile['NAME']))
128 {
129 return $result->addError(new Error("Can not find user name."));
130 }
131
132 $client = $this->getClient();
133 $client->setHeader('Client-Login', $profile['NAME']);
134 $client->setHeader('returnMoneyInMicros', 'false');
135 $client->setHeader('skipReportHeader', 'true');
136 //$client->setHeader('processingMode', 'online');
137 $response = $client->post(
138 $this->getYandexServerAdress() . 'reports',
139 Json::encode($options)
140 );
141
142 if ($client->getStatus() != 200)
143 {
144 return $result->addError(Helpers\Yandex\Sender::getErrorByHttpStatus($client->getStatus()));
145 }
146 if ($response)
147 {
148 $expenses->add($this->parseReportData($response));
149 }
150 else
151 {
152 return $result->addError(new Error('Empty report data'));
153 }
154
155 return $result;
156 }
157
163 public function hasDailyExpensesReport(): bool
164 {
165 return true;
166 }
167
175 public function getDailyExpensesReport(?string $accountId, ?Date $dateFrom, ?Date $dateTo): Result
176 {
177 $result = new Result();
178
179 $reportBuilder = new Helpers\Yandex\ReportBuilder(new Helpers\Yandex\Sender($this));
180 $reportBuilder->setPeriod($dateFrom, $dateTo);
181
182 $buildResult = $reportBuilder->buildDailyExpensesReport();
183 if (!$buildResult->isSuccess())
184 {
185 $errorsMsg = [];
186 foreach ($buildResult->getErrors() as $key => $value)
187 {
188 if (is_string($key))
189 {
190 $errorsMsg[] = "[{$key}] {$value}";
191 }
192 else
193 {
194 $errorsMsg[] = $value;
195 }
196 }
197
198 $errorsMessage = implode(',', $errorsMsg);
199 $errorMessage = $this->buildErrorMessage("Error occurred while load daily expenses: {$errorsMessage}");
200
201 return $result->addError(new Error($errorMessage));
202 }
203
204 $result->setData(['expenses' => $buildResult->getData()['expenses']]);
205
206 return $result;
207 }
208
215 public function updateAnalyticParams($accountId, array $params, array $publicPageIds = [])
216 {
217 return Response::create('yandex');
218 }
219
225 protected function getCurrency(): ?string
226 {
227 if ($this->currency)
228 {
229 return $this->currency;
230 }
231
232 $sender = new Helpers\Yandex\Sender($this);
233 $this->currency = $sender->getCurrency();
234
235 return $this->currency;
236 }
237
242 protected function parseReportData($data)
243 {
244 if (!is_string($data) || empty($data))
245 {
246 return [];
247 }
248
249 $titles = [];
250 $strings = explode("\n", $data);
251 foreach ($strings as $number => $string)
252 {
253 if ($number === 0)
254 {
255 $titles = explode("\t", $string);
256 }
257 elseif (!empty($string) && mb_strpos($string, 'Total') !== 0)
258 {
259 $row = array_combine($titles, explode("\t", $string));
260 }
261 }
262
263 if (empty($row))
264 {
265 return [];
266 }
267
268 return $this->formatReportData($row);
269 }
270
271 private function formatReportData(array $row): array
272 {
273 $conversions =
274 (is_numeric($row['Conversions']) && $row['Conversions'])
275 ? $row['Conversions']
276 : 0
277 ;
278
279 $clicks =
280 (is_numeric($row['Clicks']) && $row['Clicks'])
281 ? $row['Clicks']
282 : 0
283 ;
284
285 $impressions =
286 (is_numeric($row['Impressions']) && $row['Impressions'])
287 ? $row['Impressions']
288 : 0
289 ;
290
291 $cpm = 0;
292 if ($impressions > 0)
293 {
294 $cpm = round(($row['Cost'] / $impressions) * 1000, 2);
295 }
296
297 $date = !empty($row['Date']) ? new Date($row['Date'], 'Y-m-d') : null;
298
299 return [
300 'impressions' => $impressions,
301 'campaignName' => $row['CampaignName'],
302 'campaignId' => $row['CampaignId'],
303 'clicks' => $clicks,
304 'actions' => $conversions + $clicks,
305 'spend' => $row['Cost'],
306 'cpc' => $row['AvgCpc'],
307 'date' => $date,
308 'cpm' => $cpm,
309 'currency' => $this->getCurrency(),
310 ];
311 }
312
316 protected function getYandexServerAdress()
317 {
318 $isSandbox = false;
319
320 return 'https://api' . ($isSandbox ? '-sandbox' : '') . '.direct.yandex.com/json/v5/';
321 }
322
326 protected function getAuthToken()
327 {
328 $token = $this->getRequest()->getAuthAdapter()->getToken();
329
330 return $token;
331 }
332
336 protected function getClient()
337 {
338 $client = clone $this->getRequest()->getClient();
339 $client->setHeader('Authorization', 'Bearer ' . $this->getAuthToken());
340
341 return $client;
342 }
343}
Определения result.php:20
Определения error.php:15
Определения date.php:9
buildErrorMessage(string $error)
Определения account.php:194
updateAnalyticParams($accountId, array $params, array $publicPageIds=[])
Определения accountyandex.php:215
getDailyExpensesReport(?string $accountId, ?Date $dateFrom, ?Date $dateTo)
Определения accountyandex.php:175
getExpenses($accountId=null, Date $dateFrom=null, Date $dateTo=null)
Определения accountyandex.php:93
static create($type)
Определения response.php:108
$options
Определения commerceml2.php:49
$data['IS_AVAILABLE']
Определения .description.php:13
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
Определения file_new.php:804
$result
Определения get_property_values.php:14
while($arParentIBlockProperty=$dbParentIBlockProperty->Fetch()) $errorMessage
if( $daysToExpire >=0 &&$daysToExpire< 60 elseif)( $daysToExpire< 0)
Определения prolog_main_admin.php:393
if(empty($signedUserToken)) $key
Определения quickway.php:257
if($inWords) echo htmlspecialcharsbx(Number2Word_Rus(roundEx($totalVatSum $params['CURRENCY']
Определения template.php:799
$response
Определения result.php:21