PluginProbe
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder / 2.21.13
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder v2.21.13
3.3.1 V-3.3.0 3.2.2 3.2.1 3.2.0 3.1.4 3.1.3 3.1.2 3.1.1 3.1.0 V3.0.3 V3.0.2 -3.0.1 V_3.0.0 1.1.1 1.1.8 1.2 1.3 1.4 1.4.18 1.5.2 1.9 2.0 2.10.0 2.10.1 All 138 releases
bit-form / includes / Core / Integration / MailChimp / MailChimpHandler.php

MailChimpHandler.php in Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder 2.21.13, at includes/Core/Integration/MailChimp/MailChimpHandler.php

362 lines 10.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /**
4 * MailChimp Integration
5 *
6 */
7
8 namespace BitCode\BitForm\Core\Integration\MailChimp;
9
10 if (!defined('ABSPATH')) {
11 exit;
12 }
13
14 use BitCode\BitForm\Core\Integration\IntegrationHandler;
15 use BitCode\BitForm\Core\Util\HttpHelper;
16 use BitCode\BitForm\GlobalHelper;
17 use WP_Error;
18
19 /**
20 * Provide functionality for MailChimp integration
21 */
22 class MailChimpHandler
23 {
24 private $_integrationID;
25
26 private $formId;
27
28 public function __construct($integrationID, $fromID)
29 {
30 $this->_integrationID = $integrationID;
31
32 $this->formId = $fromID;
33 }
34
35 /**
36 * MailChimp API Endpoint
37 */
38 public static function apiEndPoint($dc)
39 {
40 return "https://$dc.api.mailchimp.com/3.0";
41 }
42
43 /**
44 * Helps to register ajax function's with wp
45 *
46 * @return null
47 */
48 public static function registerAjax()
49 {
50 add_action('wp_ajax_bitforms_mChimp_generate_token', [__CLASS__, 'generateTokens']);
51 add_action('wp_ajax_bitforms_mChimp_refresh_audience', [__CLASS__, 'refreshAudienceAjaxHelper']);
52 add_action('wp_ajax_bitforms_mChimp_refresh_fields', [__CLASS__, 'refreshAudienceFields']);
53 add_action('wp_ajax_bitforms_mChimp_refresh_tags', [__CLASS__, 'refreshTagsAjaxHelper']);
54 }
55
56 /**
57 * Process ajax request for generate_token
58 *
59 * @return JSON zoho crm api response and status
60 */
61 public static function generateTokens()
62 {
63 if (isset($_REQUEST['_ajax_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_ajax_nonce'])), 'bitforms_save')) {
64 $authorizationHeader = null;
65
66
67 GlobalHelper::requirePostMethod();
68
69 try {
70 $requestsParams = GlobalHelper::formatRequestData();
71 } catch (\InvalidArgumentException $e) {
72 wp_send_json_error($e->getMessage(), 400);
73 }
74 if (
75 empty($requestsParams->clientId)
76 || empty($requestsParams->clientSecret)
77 || empty($requestsParams->redirectURI)
78 || empty($requestsParams->code)
79 ) {
80 wp_send_json_error(
81 __(
82 'Requested parameter is empty',
83 'bit-form'
84 ),
85 400
86 );
87 }
88
89 $apiEndpoint = 'https://login.mailchimp.com/oauth2/token';
90 $authorizationHeader['Content-Type'] = 'application/x-www-form-urlencoded';
91 $requestParams = [
92 'code' => $requestsParams->code,
93 'client_id' => $requestsParams->clientId,
94 'client_secret' => $requestsParams->clientSecret,
95 'redirect_uri' => $requestsParams->redirectURI,
96 'grant_type' => 'authorization_code'
97 ];
98 $apiResponse = HttpHelper::post($apiEndpoint, $requestParams, $authorizationHeader);
99
100 $metaDataEndPoint = 'https://login.mailchimp.com/oauth2/metadata';
101
102 $authorizationHeader['Authorization'] = "Bearer {$apiResponse->access_token}";
103 $metaData = HttpHelper::post($metaDataEndPoint, null, $authorizationHeader);
104
105 $apiResponse->dc = $metaData->dc;
106
107 if (is_wp_error($apiResponse) || !empty($apiResponse->error)) {
108 wp_send_json_error(
109 empty($apiResponse->error) ? 'Unknown' : $apiResponse->error,
110 400
111 );
112 }
113 $apiResponse->generates_on = \time();
114 wp_send_json_success($apiResponse, 200);
115 } else {
116 wp_send_json_error(
117 __(
118 'Token expired',
119 'bit-form'
120 ),
121 401
122 );
123 }
124 }
125
126 /**
127 * Process ajax request for refresh MailChimp Audience list
128 *
129 * @return JSON MailChimp data
130 */
131 public static function refreshAudienceAjaxHelper()
132 {
133 if (isset($_REQUEST['_ajax_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_ajax_nonce'])), 'bitforms_save')) {
134 $authorizationHeader = null;
135
136
137 GlobalHelper::requirePostMethod();
138
139 try {
140 $queryParams = GlobalHelper::formatRequestData();
141 } catch (\InvalidArgumentException $e) {
142 wp_send_json_error($e->getMessage(), 400);
143 }
144 if (
145 empty($queryParams->tokenDetails)
146 || empty($queryParams->clientId)
147 || empty($queryParams->clientSecret)
148 || empty($queryParams->tokenDetails->dc)
149 ) {
150 wp_send_json_error(
151 __(
152 'Requested parameter is empty',
153 'bit-form'
154 ),
155 400
156 );
157 }
158 $response = [];
159 $apiEndpoint = self::apiEndPoint($queryParams->tokenDetails->dc) . '/lists';
160
161 $authorizationHeader['Authorization'] = "Bearer {$queryParams->tokenDetails->access_token}";
162 $audienceResponse = HttpHelper::get($apiEndpoint, null, $authorizationHeader);
163
164 $allList = [];
165 if (!is_wp_error($audienceResponse) && empty($audienceResponse->response->error)) {
166 $audienceLists = $audienceResponse->lists;
167 // wp_send_json_success($audienceLists);
168 foreach ($audienceLists as $audienceList) {
169 $allList[$audienceList->name] = (object) [
170 'listId' => $audienceList->id,
171 'listName' => $audienceList->name
172 ];
173 }
174 uksort($allList, 'strnatcasecmp');
175
176 $response['audiencelist'] = $allList;
177 // wp_send_json_success($response, 200);
178 } else {
179 wp_send_json_error(
180 $audienceResponse->response->error->message,
181 400
182 );
183 }
184 wp_send_json_success($response, 200);
185 } else {
186 wp_send_json_error(
187 __(
188 'Token expired',
189 'bit-form'
190 ),
191 401
192 );
193 }
194 }
195
196 /**
197 * Process ajax request for refresh MailChimp Audince Fields
198 * @return JSON MailChimp Audience fields
199 */
200 public static function refreshAudienceFields()
201 {
202 $authorizationHeader = null;
203 $response = null;
204 if (isset($_REQUEST['_ajax_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_ajax_nonce'])), 'bitforms_save')) {
205
206 // wp_send_json_success($queryParams);
207 GlobalHelper::requirePostMethod();
208
209 try {
210 $queryParams = GlobalHelper::formatRequestData();
211 } catch (\InvalidArgumentException $e) {
212 wp_send_json_error($e->getMessage(), 400);
213 }
214 if (
215 empty($queryParams->tokenDetails)
216 || empty($queryParams->listId)
217 || empty($queryParams->tokenDetails->dc)
218 ) {
219 wp_send_json_error(
220 __(
221 'Requested parameter is empty',
222 'bit-form'
223 ),
224 400
225 );
226 }
227 $apiEndpoint = self::apiEndPoint($queryParams->tokenDetails->dc) . "/lists/$queryParams->listId/merge-fields";
228 $authorizationHeader['Authorization'] = "Bearer {$queryParams->tokenDetails->access_token}";
229 $mergeFieldResponse = HttpHelper::get($apiEndpoint, null, $authorizationHeader);
230 // wp_send_json_success($mergeFieldResponse);
231 $fields = [];
232 if (!is_wp_error($mergeFieldResponse)) {
233 $allFields = $mergeFieldResponse->merge_fields;
234 foreach ($allFields as $field) {
235 if ('Address' === $field->name) {
236 continue;
237 }
238 $fields[$field->name] = (object) [
239 'tag' => $field->tag,
240 'name' => $field->name
241 ];
242 }
243 $fields['Email'] = (object) ['tag' => 'email_address', 'name' => 'Email'];
244 $response['audienceField'] = $fields;
245 wp_send_json_success($response);
246 }
247 } else {
248 wp_send_json_error(
249 __(
250 'Token expired',
251 'bit-form'
252 ),
253 401
254 );
255 }
256 }
257
258 /**
259 * Process ajax request for refresh MailChimp Tags
260 * @return JSON MailChimp Tags
261 */
262 public static function refreshTagsAjaxHelper()
263 {
264 $authorizationHeader = null;
265 $response = null;
266 if (isset($_REQUEST['_ajax_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_ajax_nonce'])), 'bitforms_save')) {
267
268
269 GlobalHelper::requirePostMethod();
270
271 try {
272 $queryParams = GlobalHelper::formatRequestData();
273 } catch (\InvalidArgumentException $e) {
274 wp_send_json_error($e->getMessage(), 400);
275 }
276
277 if (
278 empty($queryParams->tokenDetails)
279 || empty($queryParams->listId)
280 || empty($queryParams->tokenDetails->dc)
281 ) {
282 wp_send_json_error(
283 __(
284 'Requested parameter is empty',
285 'bit-form'
286 ),
287 400
288 );
289 }
290 $apiEndpoint = self::apiEndPoint($queryParams->tokenDetails->dc) . "/lists/$queryParams->listId/segments?count=1000";
291 $authorizationHeader['Authorization'] = "Bearer {$queryParams->tokenDetails->access_token}";
292 $tagsList = HttpHelper::get($apiEndpoint, null, $authorizationHeader);
293 // wp_send_json_success($tagsList->segments);
294 $allList = [];
295 foreach ($tagsList->segments as $tag) {
296 $allList[$tag->name] = (object) [
297 'tagId' => $tag->id,
298 'tagName' => $tag->name
299 ];
300 }
301 uksort($allList, 'strnatcasecmp');
302 $response['audienceTags'] = $allList;
303 wp_send_json_success($response);
304 } else {
305 wp_send_json_error(
306 __(
307 'Token expired',
308 'bit-form'
309 ),
310 401
311 );
312 }
313 }
314
315 /**
316 * Save updated access_token to avoid unnecessary token generation
317 *
318 * @param Integer $fromID ID of Integration related form
319 * @param Integer $integrationID ID of Mail Chimp Integration
320 * @param Obeject $tokenDetails refreshed token info
321 *
322 * @return null
323 */
324 public function execute(IntegrationHandler $integrationHandler, $integrationData, $fieldValues, $entryID, $logID)
325 {
326 $integrationDetails = is_string($integrationData->integration_details) ? json_decode($integrationData->integration_details) : $integrationData->integration_details;
327
328 $tokenDetails = $integrationDetails->tokenDetails;
329 $listId = $integrationDetails->listId;
330 $tags = $integrationDetails->tags;
331 $fieldMap = $integrationDetails->field_map;
332 $actions = $integrationDetails->actions;
333 $defaultDataConf = $integrationDetails->default;
334 $addressFields = $integrationDetails->address_field;
335
336 if (
337 empty($tokenDetails)
338 || empty($listId)
339 || empty($fieldMap)
340 || empty($defaultDataConf)
341 ) {
342 return new WP_Error('REQ_FIELD_EMPTY', __('module, fields are required for Mail Chimp api', 'bit-form'));
343 }
344 $recordApiHelper = new RecordApiHelper($tokenDetails, $this->_integrationID, $logID, $entryID);
345 $mChimpApiResponse = $recordApiHelper->executeRecordApi(
346 $listId,
347 $tags,
348 $defaultDataConf,
349 $fieldValues,
350 $fieldMap,
351 $actions,
352 $addressFields,
353 $this->formId
354 );
355
356 if (is_wp_error($mChimpApiResponse)) {
357 return $mChimpApiResponse;
358 }
359 return $mChimpApiResponse;
360 }
361 }
362