PluginProbe
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder / 3.3.1
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder v3.3.1
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 / ZohoMail / ZohoMailHandler.php

ZohoMailHandler.php in Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder 3.3.1, at includes/Core/Integration/ZohoMail/ZohoMailHandler.php

237 lines 7.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /**
4 * ZohoMail Integration
5 *
6 */
7
8 namespace BitCode\BitForm\Core\Integration\ZohoMail;
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\Core\Util\IpTool;
17 use BitCode\BitForm\GlobalHelper;
18 use WP_Error;
19
20 /**
21 * Provide functionality for ZohoCrm integration
22 */
23 class ZohoMailHandler
24 {
25 private $_formID;
26 private $_integrationID;
27
28 public function __construct($integrationID, $fromID)
29 {
30 $this->_formID = $fromID;
31 $this->_integrationID = $integrationID;
32 }
33
34 /**
35 * Helps to register ajax function's with wp
36 *
37 * @return null
38 */
39 public static function registerAjax()
40 {
41 add_action('wp_ajax_bitforms_zmail_generate_token', [__CLASS__, 'generateTokens']);
42 }
43
44 /**
45 * Process ajax request for generate_token
46 *
47 * @return JSON zoho crm api response and status
48 */
49 public static function generateTokens()
50 {
51 if (isset($_REQUEST['_ajax_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_ajax_nonce'])), 'bitforms_save')) {
52 $authorizationHeader = null;
53
54 GlobalHelper::requirePostMethod();
55
56 try {
57 $requestsParams = GlobalHelper::formatRequestData();
58 } catch (\InvalidArgumentException $e) {
59 wp_send_json_error($e->getMessage(), 400);
60 }
61
62 if (
63 empty($requestsParams->{'accounts-server'})
64 || empty($requestsParams->dataCenter)
65 || empty($requestsParams->clientId)
66 || empty($requestsParams->clientSecret)
67 || empty($requestsParams->redirectURI)
68 || empty($requestsParams->code)
69 ) {
70 wp_send_json_error(
71 __(
72 'Requested parameter is empty',
73 'bit-form'
74 ),
75 400
76 );
77 }
78
79 $apiEndpoint = \urldecode($requestsParams->{'accounts-server'}) . '/oauth/v2/token';
80 $requestParams = [
81 'grant_type' => 'authorization_code',
82 'client_id' => $requestsParams->clientId,
83 'client_secret' => $requestsParams->clientSecret,
84 'redirect_uri' => \urldecode($requestsParams->redirectURI),
85 'code' => $requestsParams->code
86 ];
87 $apiResponse = HttpHelper::post($apiEndpoint, $requestParams);
88
89 // Validate the token exchange before using the token: reading access_token
90 // off an error response fatals.
91 if (is_wp_error($apiResponse) || !empty($apiResponse->error) || empty($apiResponse->access_token)) {
92 wp_send_json_error(
93 empty($apiResponse->error) ? 'Unknown' : $apiResponse->error,
94 400
95 );
96 }
97
98 // https, not http: the WP HTTP API drops the Authorization header on a
99 // redirect, so an http:// call reaches Zoho as INVALID_OAUTHTOKEN.
100 $accountIdEndpoint = "https://mail.zoho.{$requestsParams->dataCenter}/api/accounts";
101 $authorizationHeader['Authorization'] = "Zoho-oauthtoken {$apiResponse->access_token}";
102 $accountResponse = HttpHelper::get($accountIdEndpoint, null, $authorizationHeader);
103
104 // On success `data` is a list of accounts; on failure it is an object
105 // ({errorCode:...}), so check the shape before reading the account.
106 $account = null;
107 if (!is_wp_error($accountResponse) && isset($accountResponse->data) && is_array($accountResponse->data)) {
108 $account = reset($accountResponse->data);
109 }
110
111 if (empty($account) || empty($account->accountId)) {
112 $reason = __('Could not read the Zoho Mail account for this token', 'bit-form');
113 if (is_wp_error($accountResponse)) {
114 $reason = $accountResponse->get_error_message();
115 } elseif (!empty($accountResponse->data->errorCode)) {
116 $reason = $accountResponse->data->errorCode;
117 } elseif (!empty($accountResponse->status->description)) {
118 $reason = $accountResponse->status->description;
119 }
120 wp_send_json_error($reason, 400);
121 }
122
123 $apiResponse->accountId = $account->accountId;
124 $apiResponse->accountEmail = isset($account->primaryEmailAddress) ? $account->primaryEmailAddress : '';
125 $apiResponse->generates_on = \time();
126 wp_send_json_success($apiResponse, 200);
127 } else {
128 wp_send_json_error(
129 __(
130 'Token expired',
131 'bit-form'
132 ),
133 401
134 );
135 }
136 }
137
138 /**
139 * Helps to refresh zoho crm access_token
140 *
141 * @param object $apiData Contains required data for refresh access token
142 * @return string|boolean $tokenDetails API token details
143 */
144 protected static function _refreshAccessToken($apiData)
145 {
146 if (
147 empty($apiData->dataCenter)
148 || empty($apiData->clientId)
149 || empty($apiData->clientSecret)
150 || empty($apiData->tokenDetails)
151 ) {
152 return false;
153 }
154 $tokenDetails = $apiData->tokenDetails;
155
156 $dataCenter = $apiData->dataCenter;
157 $apiEndpoint = "https://accounts.zoho.{$dataCenter}/oauth/v2/token";
158 $requestParams = [
159 'grant_type' => 'refresh_token',
160 'client_id' => $apiData->clientId,
161 'client_secret' => $apiData->clientSecret,
162 'refresh_token' => $tokenDetails->refresh_token,
163 ];
164
165 $apiResponse = HttpHelper::post($apiEndpoint, $requestParams);
166 if (is_wp_error($apiResponse) || !empty($apiResponse->error)) {
167 return false;
168 }
169 $tokenDetails->generates_on = \time();
170 $tokenDetails->access_token = $apiResponse->access_token;
171 return $tokenDetails;
172 }
173
174 /**
175 * Save updated access_token to avoid unnecessary token generation
176 *
177 * @param integer $fromID ID of Integration related form
178 * @param integer $integrationID ID of Zoho crm Integration
179 * @param object $tokenDetails refreshed token info
180 *
181 * @return null
182 */
183 protected static function _saveRefreshedToken($formID, $integrationID, $tokenDetails, $others = null)
184 {
185 if (empty($formID) || empty($integrationID)) {
186 return;
187 }
188
189 $integrationHandler = new IntegrationHandler($formID, IpTool::getUserDetail());
190 $zmailDetails = $integrationHandler->getAIntegration($integrationID);
191
192 if (is_wp_error($zmailDetails)) {
193 return;
194 }
195 $newDetails = json_decode($zmailDetails[0]->integration_details);
196
197 $newDetails->tokenDetails = $tokenDetails;
198
199 $integrationHandler->updateIntegration($integrationID, $zmailDetails[0]->integration_name, 'Zoho Mail', wp_json_encode($newDetails), 'form');
200 }
201
202 public function execute(IntegrationHandler $integrationHandler, $integrationData, $fieldValues, $entryID, $logID)
203 {
204 $integrationDetails = is_string($integrationData->integration_details) ? json_decode($integrationData->integration_details) : $integrationData->integration_details;
205
206 $tokenDetails = $integrationDetails->tokenDetails;
207
208 if (empty($tokenDetails)) {
209 return new WP_Error('REQ_FIELD_EMPTY', __('module, fields are required for zoho mail api', 'bit-form'));
210 }
211
212 $requiredParams = null;
213 if ((intval($tokenDetails->generates_on) + (55 * 60)) < time()) {
214 $requiredParams['clientId'] = $integrationDetails->clientId;
215 $requiredParams['clientSecret'] = $integrationDetails->clientSecret;
216 $requiredParams['dataCenter'] = $integrationDetails->dataCenter;
217 $requiredParams['tokenDetails'] = $tokenDetails;
218 $newTokenDetails = ZohoMailHandler::_refreshAccessToken((object)$requiredParams);
219 if ($newTokenDetails) {
220 ZohoMailHandler::_saveRefreshedToken($this->_formID, $this->_integrationID, $newTokenDetails);
221 $tokenDetails = $newTokenDetails;
222 }
223 }
224 // $actions = $integrationDetails->actions;
225 $recordApiHelper = new RecordApiHelper($tokenDetails, $this->_integrationID, $logID);
226
227 $zmailApiResponse = $recordApiHelper->executeRecordApi(
228 $integrationDetails,
229 $fieldValues,
230 $this->_formID,
231 $entryID
232 );
233
234 return $zmailApiResponse;
235 }
236 }
237