PluginProbe
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder / 3.1.3
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder v3.1.3
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 2.10.2 All 137 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 3.1.3, at includes/Core/Integration/MailChimp/MailChimpHandler.php

357 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 GlobalHelper::requirePostMethod();
67
68 try {
69 $requestsParams = GlobalHelper::formatRequestData();
70 } catch (\InvalidArgumentException $e) {
71 wp_send_json_error($e->getMessage(), 400);
72 }
73 if (
74 empty($requestsParams->clientId)
75 || empty($requestsParams->clientSecret)
76 || empty($requestsParams->redirectURI)
77 || empty($requestsParams->code)
78 ) {
79 wp_send_json_error(
80 __(
81 'Requested parameter is empty',
82 'bit-form'
83 ),
84 400
85 );
86 }
87
88 $apiEndpoint = 'https://login.mailchimp.com/oauth2/token';
89 $authorizationHeader['Content-Type'] = 'application/x-www-form-urlencoded';
90 $requestParams = [
91 'code' => $requestsParams->code,
92 'client_id' => $requestsParams->clientId,
93 'client_secret' => $requestsParams->clientSecret,
94 'redirect_uri' => $requestsParams->redirectURI,
95 'grant_type' => 'authorization_code'
96 ];
97 $apiResponse = HttpHelper::post($apiEndpoint, $requestParams, $authorizationHeader);
98
99 $metaDataEndPoint = 'https://login.mailchimp.com/oauth2/metadata';
100
101 $authorizationHeader['Authorization'] = "Bearer {$apiResponse->access_token}";
102 $metaData = HttpHelper::post($metaDataEndPoint, null, $authorizationHeader);
103
104 $apiResponse->dc = $metaData->dc;
105
106 if (is_wp_error($apiResponse) || !empty($apiResponse->error)) {
107 wp_send_json_error(
108 empty($apiResponse->error) ? 'Unknown' : $apiResponse->error,
109 400
110 );
111 }
112 $apiResponse->generates_on = \time();
113 wp_send_json_success($apiResponse, 200);
114 } else {
115 wp_send_json_error(
116 __(
117 'Token expired',
118 'bit-form'
119 ),
120 401
121 );
122 }
123 }
124
125 /**
126 * Process ajax request for refresh MailChimp Audience list
127 *
128 * @return JSON MailChimp data
129 */
130 public static function refreshAudienceAjaxHelper()
131 {
132 if (isset($_REQUEST['_ajax_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_ajax_nonce'])), 'bitforms_save')) {
133 $authorizationHeader = null;
134
135 GlobalHelper::requirePostMethod();
136
137 try {
138 $queryParams = GlobalHelper::formatRequestData();
139 } catch (\InvalidArgumentException $e) {
140 wp_send_json_error($e->getMessage(), 400);
141 }
142 if (
143 empty($queryParams->tokenDetails)
144 || empty($queryParams->clientId)
145 || empty($queryParams->clientSecret)
146 || empty($queryParams->tokenDetails->dc)
147 ) {
148 wp_send_json_error(
149 __(
150 'Requested parameter is empty',
151 'bit-form'
152 ),
153 400
154 );
155 }
156 $response = [];
157 $apiEndpoint = self::apiEndPoint($queryParams->tokenDetails->dc) . '/lists';
158
159 $authorizationHeader['Authorization'] = "Bearer {$queryParams->tokenDetails->access_token}";
160 $audienceResponse = HttpHelper::get($apiEndpoint, null, $authorizationHeader);
161
162 $allList = [];
163 if (!is_wp_error($audienceResponse) && empty($audienceResponse->response->error)) {
164 $audienceLists = $audienceResponse->lists;
165 // wp_send_json_success($audienceLists);
166 foreach ($audienceLists as $audienceList) {
167 $allList[$audienceList->name] = (object) [
168 'listId' => $audienceList->id,
169 'listName' => $audienceList->name
170 ];
171 }
172 uksort($allList, 'strnatcasecmp');
173
174 $response['audiencelist'] = $allList;
175 // wp_send_json_success($response, 200);
176 } else {
177 wp_send_json_error(
178 $audienceResponse->response->error->message,
179 400
180 );
181 }
182 wp_send_json_success($response, 200);
183 } else {
184 wp_send_json_error(
185 __(
186 'Token expired',
187 'bit-form'
188 ),
189 401
190 );
191 }
192 }
193
194 /**
195 * Process ajax request for refresh MailChimp Audince Fields
196 * @return JSON MailChimp Audience fields
197 */
198 public static function refreshAudienceFields()
199 {
200 $authorizationHeader = null;
201 $response = null;
202 if (isset($_REQUEST['_ajax_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_ajax_nonce'])), 'bitforms_save')) {
203 // wp_send_json_success($queryParams);
204 GlobalHelper::requirePostMethod();
205
206 try {
207 $queryParams = GlobalHelper::formatRequestData();
208 } catch (\InvalidArgumentException $e) {
209 wp_send_json_error($e->getMessage(), 400);
210 }
211 if (
212 empty($queryParams->tokenDetails)
213 || empty($queryParams->listId)
214 || empty($queryParams->tokenDetails->dc)
215 ) {
216 wp_send_json_error(
217 __(
218 'Requested parameter is empty',
219 'bit-form'
220 ),
221 400
222 );
223 }
224 $apiEndpoint = self::apiEndPoint($queryParams->tokenDetails->dc) . "/lists/$queryParams->listId/merge-fields";
225 $authorizationHeader['Authorization'] = "Bearer {$queryParams->tokenDetails->access_token}";
226 $mergeFieldResponse = HttpHelper::get($apiEndpoint, null, $authorizationHeader);
227 // wp_send_json_success($mergeFieldResponse);
228 $fields = [];
229 if (!is_wp_error($mergeFieldResponse)) {
230 $allFields = $mergeFieldResponse->merge_fields;
231 foreach ($allFields as $field) {
232 if ('Address' === $field->name) {
233 continue;
234 }
235 $fields[$field->name] = (object) [
236 'tag' => $field->tag,
237 'name' => $field->name
238 ];
239 }
240 $fields['Email'] = (object) ['tag' => 'email_address', 'name' => 'Email'];
241 $response['audienceField'] = $fields;
242 wp_send_json_success($response);
243 }
244 } else {
245 wp_send_json_error(
246 __(
247 'Token expired',
248 'bit-form'
249 ),
250 401
251 );
252 }
253 }
254
255 /**
256 * Process ajax request for refresh MailChimp Tags
257 * @return JSON MailChimp Tags
258 */
259 public static function refreshTagsAjaxHelper()
260 {
261 $authorizationHeader = null;
262 $response = null;
263 if (isset($_REQUEST['_ajax_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_ajax_nonce'])), 'bitforms_save')) {
264 GlobalHelper::requirePostMethod();
265
266 try {
267 $queryParams = GlobalHelper::formatRequestData();
268 } catch (\InvalidArgumentException $e) {
269 wp_send_json_error($e->getMessage(), 400);
270 }
271
272 if (
273 empty($queryParams->tokenDetails)
274 || empty($queryParams->listId)
275 || empty($queryParams->tokenDetails->dc)
276 ) {
277 wp_send_json_error(
278 __(
279 'Requested parameter is empty',
280 'bit-form'
281 ),
282 400
283 );
284 }
285 $apiEndpoint = self::apiEndPoint($queryParams->tokenDetails->dc) . "/lists/$queryParams->listId/segments?count=1000";
286 $authorizationHeader['Authorization'] = "Bearer {$queryParams->tokenDetails->access_token}";
287 $tagsList = HttpHelper::get($apiEndpoint, null, $authorizationHeader);
288 // wp_send_json_success($tagsList->segments);
289 $allList = [];
290 foreach ($tagsList->segments as $tag) {
291 $allList[$tag->name] = (object) [
292 'tagId' => $tag->id,
293 'tagName' => $tag->name
294 ];
295 }
296 uksort($allList, 'strnatcasecmp');
297 $response['audienceTags'] = $allList;
298 wp_send_json_success($response);
299 } else {
300 wp_send_json_error(
301 __(
302 'Token expired',
303 'bit-form'
304 ),
305 401
306 );
307 }
308 }
309
310 /**
311 * Save updated access_token to avoid unnecessary token generation
312 *
313 * @param Integer $fromID ID of Integration related form
314 * @param Integer $integrationID ID of Mail Chimp Integration
315 * @param Obeject $tokenDetails refreshed token info
316 *
317 * @return null
318 */
319 public function execute(IntegrationHandler $integrationHandler, $integrationData, $fieldValues, $entryID, $logID)
320 {
321 $integrationDetails = is_string($integrationData->integration_details) ? json_decode($integrationData->integration_details) : $integrationData->integration_details;
322
323 $tokenDetails = $integrationDetails->tokenDetails;
324 $listId = $integrationDetails->listId;
325 $tags = $integrationDetails->tags;
326 $fieldMap = $integrationDetails->field_map;
327 $actions = $integrationDetails->actions;
328 $defaultDataConf = $integrationDetails->default;
329 $addressFields = $integrationDetails->address_field;
330
331 if (
332 empty($tokenDetails)
333 || empty($listId)
334 || empty($fieldMap)
335 || empty($defaultDataConf)
336 ) {
337 return new WP_Error('REQ_FIELD_EMPTY', __('module, fields are required for Mail Chimp api', 'bit-form'));
338 }
339 $recordApiHelper = new RecordApiHelper($tokenDetails, $this->_integrationID, $logID, $entryID);
340 $mChimpApiResponse = $recordApiHelper->executeRecordApi(
341 $listId,
342 $tags,
343 $defaultDataConf,
344 $fieldValues,
345 $fieldMap,
346 $actions,
347 $addressFields,
348 $this->formId
349 );
350
351 if (is_wp_error($mChimpApiResponse)) {
352 return $mChimpApiResponse;
353 }
354 return $mChimpApiResponse;
355 }
356 }
357