Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
formfacebook.php
1<?php
2
4
17
19{
20 public const TYPE_CODE = LeadAds\Service::TYPE_FACEBOOK;
21
22 public const URL_FORM_LIST = 'https://www.facebook.com/ads/manager/audiences/manage/';
23
24 public const FIELD_MAP = [
25 ['CRM_NAME' => LeadAds\Field::TYPE_COMPANY_NAME, 'ADS_NAME' => 'COMPANY_NAME'],
26 ['CRM_NAME' => LeadAds\Field::TYPE_NAME, 'ADS_NAME' => 'FIRST_NAME'],
27 ['CRM_NAME' => LeadAds\Field::TYPE_LAST_NAME, 'ADS_NAME' => 'LAST_NAME'],
28 ['CRM_NAME' => LeadAds\Field::TYPE_EMAIL, 'ADS_NAME' => 'EMAIL'],
29 ['CRM_NAME' => LeadAds\Field::TYPE_PHONE, 'ADS_NAME' => 'PHONE'],
30 ['CRM_NAME' => LeadAds\Field::TYPE_WORK_EMAIL, 'ADS_NAME' => 'WORK_EMAIL'],
31 ['CRM_NAME' => LeadAds\Field::TYPE_WORK_PHONE, 'ADS_NAME' => 'WORK_PHONE_NUMBER'],
32 ['CRM_NAME' => LeadAds\Field::TYPE_JOB_TITLE, 'ADS_NAME' => 'JOB_TITLE'],
33 ['CRM_NAME' => LeadAds\Field::TYPE_MILITARY_STATUS, 'ADS_NAME' => 'MILITARY_STATUS'],
34 ['CRM_NAME' => LeadAds\Field::TYPE_MARITIAL_STATUS, 'ADS_NAME' => 'MARITIAL_STATUS'],
35 ['CRM_NAME' => LeadAds\Field::TYPE_GENDER, 'ADS_NAME' => 'GENDER'],
36 ['CRM_NAME' => LeadAds\Field::TYPE_BIRTHDAY, 'ADS_NAME' => 'DOB'],
37 ['CRM_NAME' => LeadAds\Field::TYPE_LOCATION_COUNTRY, 'ADS_NAME' => 'COUNTRY'],
38 ['CRM_NAME' => LeadAds\Field::TYPE_LOCATION_STATE, 'ADS_NAME' => 'STATE'],
39 ['CRM_NAME' => LeadAds\Field::TYPE_LOCATION_CITY, 'ADS_NAME' => 'CITY'],
40 ['CRM_NAME' => LeadAds\Field::TYPE_LOCATION_STREET_ADDRESS, 'ADS_NAME' => 'STREET_ADDRESS'],
41 ['CRM_NAME' => LeadAds\Field::TYPE_FULL_NAME, 'ADS_NAME' => 'FULL_NAME'],
42 ['CRM_NAME' => LeadAds\Field::TYPE_LOCATION_ZIP, 'ADS_NAME' => 'ZIP'],
43 ['CRM_NAME' => LeadAds\Field::TYPE_RELATIONSHIP_STATUS, 'ADS_NAME' => 'RELATIONSHIP_STATUS'],
44 ['CRM_NAME' => LeadAds\Field::TYPE_CPF, 'ADS_NAME' => 'ID_CPF'],
45 ['CRM_NAME' => LeadAds\Field::TYPE_DNI_ARGENTINA, 'ADS_NAME' => 'ID_AR_DNI'],
46 ['CRM_NAME' => LeadAds\Field::TYPE_DNI_PERU, 'ADS_NAME' => 'ID_PE_DNI'],
47 ['CRM_NAME' => LeadAds\Field::TYPE_RUT, 'ADS_NAME' => 'ID_CL_RUT'],
48 ['CRM_NAME' => LeadAds\Field::TYPE_CC, 'ADS_NAME' => 'ID_CO_CC'],
49 ['CRM_NAME' => LeadAds\Field::TYPE_CI, 'ADS_NAME' => 'ID_EC_CI'],
50 ['CRM_NAME' => LeadAds\Field::TYPE_DATE_TIME, 'ADS_NAME' => 'DATE_TIME'],
51 ];
52
53 protected static $listRowMap = array(
54 'ID' => 'ID',
55 'NAME' => 'NAME',
56 'LOCALE' => 'LOCALE',
57 );
58
59 protected function getLocaleByLanguageId($languageId = null): string
60 {
61 switch ($languageId = $languageId ?? Context::getCurrent()->getLanguage())
62 {
63 case 'ru':
64 case 'kz':
65 case 'ua':
66 case 'by':
67 return 'ru_RU';
68 case 'pl':
69 case 'fr':
70 case 'it':
71 case 'tr':
72 case 'de':
73 case 'es':
74 return mb_strtolower($languageId).'_'.mb_strtoupper($languageId);
75 case 'la':
76 return 'es_LA';
77 case 'br': // Brazilian
78 return 'pt_BR';
79 case 'sc': // simplified Chinese
80 return 'zh_CN';
81 case 'tc': // traditional Chinese
82 return 'zh_TW';
83 default:
84 return'en_US';
85 }
86 }
87
94 public static function convertField(LeadAds\Field $field) : array
95 {
96 $mapper = static::getFieldMapper();
97
98 if ($adsName = $mapper->getAdsName($field->getName()))
99 {
100 return ['type' => $adsName, 'key' => $field->getKey()];
101 }
102
103 $item = [
104 'type' => 'CUSTOM',
105 'label' => $field->getLabel(),
106 'key' => $field->getKey()
107 ];
108 if (!empty($field->getOptions()))
109 {
110 $item['options'] = array_map(
111 static function ($option)
112 {
113 return [
114 'value' => $option['label'],
115 'key' => $option['key']
116 ];
117 },
118 $field->getOptions()
119 );
120 }
121
122 return $item;
123 }
124
131 public function add(array $data) : Response
132 {
133 // https://developers.facebook.com/docs/marketing-api/guides/lead-ads/create/v2.9#create-forms
134 $locale = $data['LOCALE'] ?? $this->getLocaleByLanguageId();
135 $questions = static::convertFields($data['FIELDS']);
136 $privacyPolicy = array(
137 'url' => $data['PRIVACY_POLICY_URL']
138 );
139
140 $privacyPolicy['url'] = self::getPrivacyPolicyUrl();
141 $contextCard = [
142 'style' => 'PARAGRAPH_STYLE',
143 'content' => [' '],
144 'button_text' => $data['BUTTON_CAPTION']
145 ];
146 if ($data['TITLE'])
147 {
148 $contextCard['title'] = $data['TITLE'];
149 }
150 if ($data['DESCRIPTION'])
151 {
152 $contextCard['content'] = [$data['DESCRIPTION']];
153 }
154 elseif ($data['TITLE'])
155 {
156 $contextCard['content'] = [$data['TITLE']];
157 }
158
159 $response = $this->getRequest()->send([
160 'methodName' => 'leadads.form.create',
161 'parameters' => [
162 'page_id'=> $this->accountId,
163 'params' => [
164 'name' => $data['NAME'],
165 'privacy_policy' => $privacyPolicy,
166 'follow_up_action_url' => $data['SUCCESS_URL'],
167 'locale' => mb_strtoupper($locale),
168 'context_card' => $contextCard,
169 'questions' => $questions
170 ]
171 ]
172 ]);
173
174 if (!$response->isSuccess() || !$formId = $response->getData()["id"] ?? null)
175 {
176 return $response;
177 }
178 $response->setId($formId);
179
180 $subscribeResult = $this->subscribeAppToPageEvents();
181 if (!$subscribeResult->isSuccess())
182 {
183 $response->addError(new Error('Can not subscribe App to Page events.'));
184 return $response;
185 }
186
187 if(!$this->registerFormWebHook($formId))
188 {
189 $response->addError(new Error('Can not register Form web hook.'));
190 return $response;
191 }
192
193 return $response;
194 }
195
203 public function unlink(string $id) : bool
204 {
205 return $this->removeFormWebHook($id);
206 }
207
208 protected function subscribeAppToPageEvents(): Retargeting\Services\ResponseFacebook
209 {
210 return $this->getRequest()->send(array(
211 'methodName' => 'leadads.event.subscribe',
212 'parameters' => [
213 'page_id' => $this->accountId,
214 'params' => [
215 'subscribed_fields' => ['leadgen'],
216 ]
217 ]
218 ));
219 }
220
221
222 public function getList() : LeadAds\Response\FormResponse
223 {
224 $paginator = new Paginator(
225 $this->getRequest(),
226 array(
227 'methodName' => 'leadads.form.list',
228 'parameters' => [
229 'page_id' => $this->accountId,
230 'fields' => [
231 'privacy_policy_url',
232 'id',
233 'context_card',
234 'name',
235 'status',
236 'thank_you_page',
237 'follow_up_action_url',
238 'tracking_parameters',
239 'questions'
240 ],
241 'params' => [
242 'limit' => 50
243 ]
244 ]
245 )
246 );
247
248 return new FormResponse(
249 new FacebookFormBuilder($this::getFieldMapper()),
250 ...iterator_to_array($paginator)
251 );
252 }
253
260 public function getResult(WebHook\Payload\LeadItem $item) : LeadAds\Result
261 {
262 $result = new LeadAds\Result();
263
264 // https://developers.facebook.com/docs/marketing-api/guides/lead-ads/create/v2.9#readingforms
265 $response = $this->getRequest()->send(array(
266 'methodName' => 'leadads.lead.get',
267 'parameters' => [
268 'lead_id' => $item->getLeadId()
269 ]
270 ));
271
272 if (!$response->isSuccess())
273 {
274 foreach ($response->getErrors() as $error)
275 {
276 $result->addError(new Error('Can not retrieve result. ' . $error->getMessage()));
277 }
278
279 return $result;
280 }
281
282 if (!$responseData = $response->getData())
283 {
284 $result->addError(new Error('Can not retrieve result. Empty data.'));
285
286 return $result;
287 }
288
289 if (!isset($responseData['id']) || !$responseData['id'])
290 {
291 $result->addError(new Error('Can not retrieve result. Empty `id`.'));
292
293 return $result;
294 }
295
296 if (!isset($responseData['field_data']) || !is_array($responseData['field_data']) || !$responseData['field_data'])
297 {
298 $result->addError(new Error('Can not retrieve result. Empty `field_data`.'));
299
300 return $result;
301 }
302
303 $result->setId($item->getLeadId());
304 foreach ($responseData['field_data'] as $field)
305 {
306 if (!isset($field['name']) || !$field['name'])
307 {
308 continue;
309 }
310
311 if (!isset($field['values']) || !$field['values'])
312 {
313 continue;
314 }
315
316 if (!is_array($field['values']))
317 {
318 $field['values'] = array($field['values']);
319 }
320
321 $result->addFieldValues($field['name'], $field['values']);
322 }
323
324 return $result;
325 }
326
327
335 public function getForm($formId) : LeadAds\Response\FormResponse
336 {
338 $response = $this->getRequest()->send([
339 'methodName' => 'leadads.form.get',
340 'parameters' => [
341 'page_id' => $this->accountId,
342 'form_id' => $formId,
343 'fields' => [
344 'privacy_policy_url',
345 'id',
346 'context_card',
347 'name',
348 'status',
349 'thank_you_page',
350 'follow_up_action_url',
351 'tracking_parameters',
352 'questions'
353 ],
354 ]
355 ]);
356
357 return new FormResponse(
358 new FacebookFormBuilder($this::getFieldMapper()),
359 $response
360 );
361 }
362
368 public function register($formId): Retargeting\Response
369 {
370 if (!isset($formId))
371 {
372 return (new Retargeting\Services\ResponseFacebook())
373 ->addError(new Error('Facebook lead ads form register: Empty formId.'))
374 ;
375 }
376 if (!isset($this->accountId))
377 {
378 return (new Retargeting\Services\ResponseFacebook())
379 ->addError(new Error('Facebook lead ads form register: Empty accountId.'))
380 ;
381 }
382
383 $subscribeResult = $this->subscribeAppToPageEvents();
384 if (!$subscribeResult->isSuccess())
385 {
386 return $subscribeResult;
387 }
388
390 if (!$this->registerFormWebHook($formId))
391 {
392 $result->addError(new Error('Can not register Form web hook.'));
393 }
394
395 return $result;
396 }
397}
static getCurrent()
Definition context.php:241
registerFormWebHook($adsFormId, array $parameters=[])
Definition form.php:285
static getPrivacyPolicyUrl()
Definition form.php:268
removeFormWebHook($adsFormId)
Definition form.php:308
getResult(WebHook\Payload\LeadItem $item)
static convertField(LeadAds\Field $field)