PluginProbe
Depicter — Popup & Slider Builder / trunk
Depicter — Popup & Slider Builder vtrunk
4.8.1 trunk 1.0.0 1.1.0 1.1.2 1.1.4 1.1.6 1.1.7 1.1.8 1.1.9 1.2.0 1.3.0 1.3.1 1.3.2 1.3.3 1.3.5 1.3.8 1.5.0 1.5.1 1.5.2 1.5.5 1.6.0 1.6.1 1.6.2 1.7.0 All 76 releases
depicter / app / src / Integration / MailChimp / MailChimp.php

MailChimp.php in Depicter — Popup & Slider Builder trunk, at app/src/Integration/MailChimp/MailChimp.php

226 lines 6.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 namespace Depicter\Integration\MailChimp;
3
4
5 use Averta\Core\Utility\Arr;
6 use Averta\WordPress\Utility\JSON;
7 use Depicter\GuzzleHttp\Client;
8 use Depicter\GuzzleHttp\Exception\GuzzleException;
9
10 class MailChimp
11 {
12
13 /**
14 * Retrieves the list of audiences from provided account
15 *
16 * @param string $apiKey
17 *
18 * @return array
19 */
20 public function getAudienceList($apiKey) {
21 $region = substr($apiKey, strpos($apiKey, '-') + 1);
22 $url = "https://$region.api.mailchimp.com/3.0/lists";
23
24 try {
25 $body = $this->callApi($apiKey, $url);
26
27 return [
28 'hits' => $body['lists'] ?? []
29 ];
30 } catch (GuzzleException $e) {
31 return [
32 'hits' => [],
33 'errors' => [ $e->getMessage() ]
34 ];
35 }
36 }
37
38 /**
39 * Retrieves the list of fields from provided audience
40 *
41 * @param string $apiKey
42 * @param string|int $listId
43 *
44 * @return array
45 */
46 public function getListFields( $apiKey, $listId ) {
47 $region = substr($apiKey, strpos($apiKey, '-') + 1);
48 $url = "https://$region.api.mailchimp.com/3.0/lists/$listId/merge-fields";
49
50 try{
51 $body = $this->callApi($apiKey, $url);
52
53 $mergeFields = empty( $body['status'] ) ? [
54 [
55 "merge_id" => 0,
56 "tag" => "email_address",
57 "name" => "Email",
58 "type" => "text",
59 "required" => true,
60 "default_value" => "",
61 "public" => true,
62 "display_order" => 0,
63 "options" => [
64 "size" => 25,
65 "choices" => null
66 ]
67 ]
68 ] : [];
69
70 if ( ! empty( $body['merge_fields'] ) ) {
71 $mergeFields = Arr::merge( $mergeFields, $body['merge_fields']);
72 }
73
74 return [
75 'hits' => $mergeFields
76 ];
77 } catch (GuzzleException $e) {
78 return [
79 'hits' => [],
80 'errors' => [ $e->getMessage() ]
81 ];
82 }
83 }
84
85 public function submitToMailchimp( $leadId ): array
86 {
87 try{
88 $lead = \Depicter::leadRepository()->get( $leadId );
89 if ( empty( $lead ) ) {
90 return [
91 'success' => false,
92 'error' => __( 'Lead does not exist', 'depicter' )
93 ];
94 }
95 } catch ( \Exception $e ){
96 return [
97 'success' => false,
98 'error' => $e->getMessage()
99 ];
100 }
101
102 $config = $this->getConfig( $lead['source_id'] );
103 if ( empty( $config ) ) {
104 return [
105 'success' => false,
106 'error' => __( 'Lead form is not connected to mailchimp', 'depicter' )
107 ];
108 }
109
110 if ( empty( $config['apiKey'] ) ) {
111 return [
112 'success' => false,
113 'error' => __( 'Mailchimp API key is required', 'depicter' )
114 ];
115 }
116
117 $mappedEmailField = array_filter( $config['fieldMapping'], function ( $fieldMap ) {
118 return !empty( $fieldMap['to'] ) && $fieldMap['to'] == 'email_address';
119 });
120
121 if ( empty( $mappedEmailField ) ) {
122 return [
123 'success' => false,
124 'error' => __( 'Email is required', 'depicter' )
125 ];
126 }
127
128 try{
129 $leadFields = \Depicter::leadFieldRepository()->leadField()->where( 'lead_id', $leadId )->findAll()->get();
130 if ( $leadFields ) {
131 $leadFields = $leadFields->toArray();
132 } else {
133 return [
134 'success' => false,
135 'error' => __( 'Lead does not have any field', 'depicter' )
136 ];
137 }
138 } catch ( \Exception $e ){
139 return [
140 'success' => false,
141 'error' => $e->getMessage()
142 ];
143 }
144
145 $region = substr($config['apiKey'], strpos($config['apiKey'], '-') + 1);
146 $url = "https://" . $region . ".api.mailchimp.com/3.0/lists/" . $config['listId'] . "/members/";
147
148
149 $payload = [
150 'status' => 'subscribed',
151 ];
152 $mergeFields = [];
153 foreach ( $leadFields as $leadField ) {
154 if ( $leadField['name'] == 'email' ) {
155 $payload['email_address'] = $leadField['value'];
156 continue;
157 }
158
159 $mappedField = array_filter( $config['fieldMapping'], function ( $fieldMap ) use ( $leadField ) {
160 return !empty( $fieldMap['from'] ) && $fieldMap['from'] == 'field:' . $leadField['name'];
161 });
162
163 if ( empty( $mappedField ) ) {
164 continue;
165 }
166
167 $mergeFields[ $mappedField[0]['to'] ] = $leadField['value'];
168 }
169 $payload['merge_fields'] = $mergeFields;
170
171 $client = new Client();
172 try {
173 $response = $client->post( $url, [
174 'auth' => [
175 'myToken', $config['apiKey'],
176 ],
177 'json' => $payload
178 ]);
179
180 // todo: we have to check the final response here
181 return [
182 'success' => true,
183 'response' => JSON::decode($response->getBody()->getContents(), true)
184 ];
185 } catch ( GuzzleException $e ){
186 return [
187 'success' => false,
188 'error' => __( 'Mailchimp API error', 'depicter' )
189 ];
190 }
191 }
192
193 public function getConfig( $source_id ) {
194 $editorData = \Depicter::document()->getEditorRawData( $source_id );
195 if ( empty( $editorData ) ) {
196 return [
197 'success' => false,
198 'error' => __( 'Empty document data', 'depicter' )
199 ];
200 }
201
202 $editorData = JSON::decode( $editorData, true );
203 if ( empty( $editorData['options']['integrations']['mailchimp']['config'] ) || empty( $editorData['options']['integrations']['mailchimp']['enabled'] ) ) {
204 return [
205 'success' => false,
206 'error' => __( 'Document is not connected to mailchimp', 'depicter' )
207 ];
208 }
209
210 return $editorData['options']['integrations']['mailchimp']['config'];
211 }
212
213 protected function callApi($apiKey, $url){
214
215 $client = new Client();
216 $response = $client->get( $url, [
217 'auth' => ['anystring', $apiKey], // Mailchimp expects username:apikey format
218 'headers' => [
219 'Content-Type' => 'application/json'
220 ]
221 ]);
222
223 return JSON::decode($response->getBody()->getContents(), true);
224 }
225 }
226