class-aw-woocommerce-integration.php
25.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
<?php
/**
*
*
* @package WC_Active Woo Integration
* @category Integration
* @author Jason Kadlec http://crazyeffective.com
*/
if ( ! class_exists( 'WC_Integration_Active_Woo' ) ) :
class WC_Integration_Active_Woo extends WC_Integration {
// Background sync to AC
protected $sync_orders;
/**
* Init and hook in the integration.
*/
public function __construct() {
global $woocommerce;
$this->id = 'active-woo';
$this->method_title = __( 'Active Campaign WooCommerce', 'woocommerce-active-woo' );
$this->method_description = __( 'Sends purchaser info from WooCommerce into Active Campaign', 'woocommerce-active-woo' );
// Load the settings.
$this->init_form_fields();
$this->init_settings();
$this->recover_cart();
// Load the Background task manager.
$this->sync_orders = new AW_Background_Sync();
// Define user set variables.
$this->aw_license = $this->get_option( 'aw_license');
$this->api_url = $this->get_option( 'api_url' );
$this->api_key = $this->get_option( 'api_key' );
$this->default_tag = $this->get_option( 'default_tag' );
$this->customer_revenue = $this->get_option( 'customer_revenue');
$this->cart_recover = $this->get_option( 'cart_recover');
// Actions.
add_action( 'woocommerce_update_options_integration_' . $this->id, array( $this, 'process_admin_options' ) );
add_action('wp_ajax_aw_get_results', array( $this, 'aw_process_ajax' ));
// Filters.
add_filter( 'woocommerce_settings_api_sanitized_fields_' . $this->id, array( $this, 'sanitize_settings' ) );
define('AW_LICENSE_KEY_REQ', '56ae9e95354717.75128259');
define('AW_LICENSE_KEY_URL', 'http://activewoo.com');
define('AW_PRODUCT_SKU', 'ActiveWoo');
}
/**
* Initialize integration settings form fields.
*
* @return void
*/
public function init_form_fields() {
$this->sync_orders = new AW_Background_Sync();
// Exit if not Woo Settings and Integration Tab
if ( ( isset($_GET['page']) && $_GET['page'] !== 'wc-settings') && ( isset($_GET['tab']) && $_GET['tab'] !== 'integration') ) {
return;
}
$awlicense_key = get_option('aw_license');
if (!empty($awlicense_key)) {
$url = 'http://activewoo.com/?secret_key=56ae9e95354717.75128259&slm_action=slm_check&license_key=' . $awlicense_key . '®istered_domain=' . get_bloginfo('url').'&item_reference=ActiveWoo';
$response = wp_remote_get($url, array('timeout' => 20, 'sslverify' => false));
if(is_array($response)){
$json = $response['body']; // use the content
$json = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', utf8_encode($json));
$license_data = json_decode($json);
}
}
if( isset($license_data) && $license_data->result == 'success'){
$this->form_fields = array(
'api_url' => array(
'title' => __( 'API URL', 'woocommerce-active-woo' ),
'type' => 'text',
'description' => __( 'Enter with your API URL. You can find this in the "My Settings" drop-down of Active Campaign(top right corner) > Click the API Button, Then paste in API URL.', 'woocommerce-active-woo' ),
'desc_tip' => false,
'id' => 'aw_api_url',
'default' => ''
),
'api_key' => array(
'title' => __( 'API Key', 'woocommerce-active-woo' ),
'type' => 'text',
'description' => __( 'You can find this in the "My Settings" drop-down of Active Campaign(top right corner) > Click the API Button, copy the API Key, then paste it here.', 'woocommerce-active-woo' ),
'desc_tip' => false,
'default' => ''
),
'default_tag' => array(
'title' => __( 'Default Tag (optional)', 'woocommerce-active-woo' ),
'type' => 'text',
'description' => __( 'Enter the name of a tag that will be applied on every purchase, regardless of what product(s) are purchased', 'woocommerce-active-woo' ),
'desc_tip' => false,
'default' => ''
),
'sync_cat' => array(
'title' => __( 'Sync the WooCommerce Product Category', 'woocommerce-active-woo' ),
'type' => 'checkbox',
'description' => __( 'Leave this CHECKED if you want to add the WooCommerce product category(ies) as tags, in addition to the SKU.', 'woocommerce-active-woo' ),
'desc_tip' => false,
'default' => ''
),
'sync_tag' => array(
'title' => __( 'Sync the WooCommerce Product Tag', 'woocommerce-active-woo' ),
'type' => 'checkbox',
'description' => __( 'Leave this CHECKED if you want to add the WooCommerce product tag(s) as tags, in addition to the SKU.', 'woocommerce-active-woo' ),
'desc_tip' => false,
'default' => ''
),
'sync_coupon' => array(
'title' => __( 'Sync Coupons', 'woocommerce-active-woo' ),
'type' => 'checkbox',
'description' => __( 'Leave this CHECKED if you want to add the any Coupon(s) used by the customer at checkout as tags, in addition to the SKU.', 'woocommerce-active-woo' ),
'desc_tip' => false,
'default' => ''
),
'sync_billing' => array(
'title' => __( 'Adds custom fields for billing info, and syncs most recent order info into those fields.', 'woocommerce-active-woo' ),
'type' => 'checkbox',
'description' => __( 'Billing mailing address, country and postal code', 'woocommerce-active-woo' ),
'desc_tip' => false,
'default' => '0'
),
'customer_revenue' => array(
'title' => __( 'Customer Revenue Field (optional)', 'woocommerce-active-woo' ),
'type' => 'text',
'description' => __( 'Enter the custom field name you would like to use to track total spend, leave empty if you do not wish to track this', 'woocommerce-active-woo' ),
'desc_tip' => false,
'default' => ''
),
'last_order_date' => array(
'title' => __( 'Enter custom field name you would like to use save the date of the order being synced, leave empty if you do not wish to track this', 'woocommerce-active-woo' ),
'type' => 'text',
'description' => __( 'If a customer has multipe orders, this field will always show the most recent order only.', 'woocommerce-active-woo' ),
'desc_tip' => false,
'default' => ''
),
'cart_recover' => array(
'title' => __( 'Enable Cart Recovery <a href="http://activewoo.com/recover-cart">Important Instructions Here</a>', 'woocommerce-active-woo' ),
'type' => 'checkbox',
'description' => __( 'NOTE: You MUST do some setup in ActiveCampaign BEFORE you enable this option!', 'woocommerce-active-woo' ),
'desc_tip' => false,
'default' => '0'
),
'rc_prefix' => array(
'title' => __( 'Default Recover Cart Tag & Tag Prefix (Required)', 'woocommerce-active-woo' ),
'type' => 'text',
'description' => __( 'Make this short - it will prefix any SKU, Product Category or Product Tag so you can differentiate that from the purchased tag. EG: AW_RC-SKU. AW_RC is the prefix you are adding here, SKU would be the product sku, and the - is added automatically between the prefix and SKU', 'woocommerce-active-woo' ),
'desc_tip' => false,
'default' => 'AW_RC'
),
'rc_sku' => array(
'title' => __( 'Use the SKU + the prefix above when using the Recover Cart', 'woocommerce-active-woo' ),
'type' => 'checkbox',
'description' => __( 'Leave this CHECKED if you want to be able to see what products were in the cart when abandoned.', 'woocommerce-active-woo' ),
'desc_tip' => false,
'default' => ''
),
'rc_cat' => array(
'title' => __( 'Use the Product Category + the prefix above when using the Recover Cart', 'woocommerce-active-woo' ),
'type' => 'checkbox',
'description' => __( 'Leave this CHECKED if you want to be able to see what product category(s) were in the cart when abandoned.', 'woocommerce-active-woo' ),
'desc_tip' => false,
'default' => ''
),
'rc_tag' => array(
'title' => __( 'Use the Product Tag + the prefix above when using the Recover Cart', 'woocommerce-active-woo' ),
'type' => 'checkbox',
'description' => __( 'Leave this CHECKED if you want to be able to see what product tag(s) were in the cart when abandoned.', 'woocommerce-active-woo' ),
'desc_tip' => false,
'default' => ''
),
'cancel_sync' => array(
'title' => __( 'Cancel Syncing Orders', 'aw_sync_all' ),
'type' => 'button_cancel',
'id' => 'cancel-sync-button',
'description' => __( 'Click this button, and ActiveWoo will cancel syncing the orders in queue.', 'aw_sync_all' ),
'desc_tip' => false,
)
);
// Add a new field if WC Subscriptions is active
if ( aw_is_checkout_editor_active() ) {
$this->form_fields['wc_checkout_sync'] = array(
'title' => __( 'Have ActiveWoo sync custom Checkout Field', 'woocommerce-active-woo' ),
'type' => 'checkbox',
'id' => 'checkout-fields-sync-chbox',
'description' => __( 'Leave this CHECKED if you want to sync custom Checkout Fields created by Checkout Field Editor Plugin.', 'woocommerce-active-woo' ),
'desc_tip' => false,
'default' => 'yes'
);
}
// Add a new field if WC Subscriptions is active
if ( class_exists( 'WC_Subscriptions' ) ) {
$this->form_fields['wc_subs_sync'] = array(
'title' => __( 'Have ActiveWoo sync subscription events', 'woocommerce-active-woo' ),
'type' => 'checkbox',
'id' => 'subs-sync-chbox',
'description' => __( 'When a subscriber cancels a subscription, an skuCANC tag will be added to that contact. For example, if your product sku was GoldMembership, then the tag that will be added will be GoldMembershipCANC.', 'woocommerce-active-woo' ),
'desc_tip' => false,
'default' => 'yes'
);
}
$this->form_fields['customize_button'] = array(
'title' => __( 'Sync All Orders', 'aw_sync_all' ),
'type' => 'button',
//'custom_attributes' => array(
//'onclick' => "aw_do_sync",
//),
'description' => __( 'Click this button, and ActiveWoo will search for any orders not yet synced, and will sync them.<br> To test how many orders have been synced, you can refresh the page and check the total orders synced status on the left.', 'aw_sync_all' ),
'desc_tip' => false,
);
} else {
$this->form_fields = array(
'aw_license' => array(
'title' => __( 'ActiveWoo License Key', 'woocommerce-active-woo' ),
'type' => 'text',
'description' => __( 'This license key was shown on your confirmation page, and was also emailed to you. Please be sure you check your spam folder!', 'woocommerce-active-woo' ),
'desc_tip' => false,
'id' => 'aw_license',
'default' => ''
)
);
}
// Change the "Sync All Order" button description and disable it when sync quee isn't empty"
if ( ! $this->sync_orders->is_empty() && isset( $this->form_fields['customize_button'] ) ) {
$this->form_fields['customize_button']['custom_attributes'] = array( 'disabled' => true );
$this->form_fields['customize_button']['description'] = __( 'Orders are being synced. Refresh this page to see the progress.', 'aw_sync_all' );
}
}
/**
* Santize our settings
* @see process_admin_options()
*/
public function sanitize_settings( $settings ) {
if ( isset( $settings['aw_license'] )) {
$awlicense_key = $settings['aw_license'];
}
if ( isset( $settings ) && isset( $settings['api_key'] ) ) { //test API key works when it gets submitted.
$ac = new aw_ActiveCampaign($settings['api_url'], $settings['api_key']);
if (!(int)$ac->credentials_test()) { //it failed
echo '<div class="error"><p>ERROR - ACTIVE CAMPAIGN NOT CONNECTED!! The API URL and API Key entered are not working. Please check and try again.</p></div>';
} else {
$field = $settings['customer_revenue'];
$pers = preg_replace("/[^a-zA-Z]+/", "_", $field);
$perstag = strtoupper($pers);
$addfield = array(
'title' => $field,
'type' => 1,
'req' => '0',
'perstag' => $perstag,
'p[0]' => '0'
);
$ac_custom_fields = $ac->api("list/field_add", $addfield);
if ($settings['sync_billing']) {
$addfield = array(
'title' => 'Billing Address',
'type' => 1,
'req' => '0',
'perstag' => 'BILLING_ADDRESS',
'p[0]' => '0'
);
$ac_custom_fields = $ac->api("list/field_add", $addfield);
$addfield = array(
'title' => 'Billing Address 2',
'type' => 1,
'req' => '0',
'perstag' => 'BILLING_ADDRESS_2',
'p[0]' => '0'
);
$ac_custom_fields = $ac->api("list/field_add", $addfield);
$addfield = array(
'title' => 'Billing City',
'type' => 1,
'req' => '0',
'perstag' => 'BILLING_CITY',
'p[0]' => '0'
);
$ac_custom_fields = $ac->api("list/field_add", $addfield);
$addfield = array(
'title' => 'Billing State',
'type' => 1,
'req' => '0',
'perstag' => 'BILLING_STATE',
'p[0]' => '0'
);
$ac_custom_fields = $ac->api("list/field_add", $addfield);
$addfield = array(
'title' => 'Billing Country',
'type' => 1,
'req' => '0',
'perstag' => 'BILLING_COUNTRY',
'p[0]' => '0'
);
$ac_custom_fields = $ac->api("list/field_add", $addfield);
$addfield = array(
'title' => 'Billing Postcode',
'type' => 1,
'req' => '0',
'perstag' => 'BILLING_POSTCODE',
'p[0]' => '0'
);
$ac_custom_fields = $ac->api("list/field_add", $addfield);
}
if ($settings['last_order_date']){
$field = $settings['last_order_date'];
$pers = preg_replace("/[^a-zA-Z]+/", "_", $field);
$perstag = strtoupper($pers);
$addfield = array(
'title' => $field,
'type' => 9,
'req' => '0',
'perstag' => $perstag,
'p[0]' => '0'
);
$ac_custom_fields = $ac->api("list/field_add", $addfield);
}
if ( $settings['wc_checkout_sync'] == 'yes' && aw_is_checkout_editor_active() ){
$custom_ch_fields = aw_get_custom_checkout_fields();
foreach ($custom_ch_fields as $field) {
$pers = preg_replace("/[^a-zA-Z]+/", "_", $field);
$perstag = strtoupper($pers);
$addfield = array(
'title' => $field,
'type' => 1,
'req' => '0',
'perstag' => $perstag,
'p[0]' => '0'
);
$ac_custom_fields = $ac->api("list/field_add", $addfield);
}
}
echo '<div id="message" class="updated"><p>Success! Active Campaign is now connected</p></div>';
}
} else {
if ( isset( $settings ) && isset( $settings['aw_license'] ) ) { //test API key works when it gets submitted.
$awlicense_key = $settings['aw_license'];
$url = AW_LICENSE_KEY_URL . '/?secret_key=' . AW_LICENSE_KEY_REQ . '&slm_action=slm_activate&license_key=' . $awlicense_key . '®istered_domain=' . get_bloginfo('siteurl').'&item_reference=ActiveWoo';
$response = wp_remote_get($url, array('timeout' => 20, 'sslverify' => false));
if(is_array($response)){
$json = $response['body']; // use the content
$json = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', utf8_encode($json));
$license_data = json_decode($json);
}
if($license_data->result == 'success'){
update_option( 'aw_license', $awlicense_key);
echo '<div id="message" class="updated"><p>Your license activated successfuly</p><p>Please <a class="button-primary" href="javascript:window.location.reload(true)">Click Here</a> to load in the settings.</p></div>';
}else{
echo '<div class="error"><p>' . $license_data->message . $awlicense_key.'</p></div>';
}
} else {
echo '<div class="error"><p>ERROR-Please enter a valid ActiveWoo License Key</p>';
}
}
return $settings;
}
public function recover_cart() {
if ($this->get_option( 'cart_recover') == 'yes') {
if ( !function_exists('activewoo_plugin_path') ) {
function activewoo_plugin_path() {
// gets the absolute path to this plugin directory
return untrailingslashit( plugin_dir_path( __FILE__ ) );
}
}
add_filter( 'woocommerce_locate_template', 'myplugin_woocommerce_locate_template', 10, 3 );
if ( !function_exists('myplugin_woocommerce_locate_template') ) {
function myplugin_woocommerce_locate_template( $template, $template_name, $template_path ) {
global $woocommerce;
$_template = $template;
if ( ! $template_path ) {
$template_path = $woocommerce->template_url;
}
$plugin_path = activewoo_plugin_path() . '/woocommerce/';
// Look within passed path within the theme - this is priority
$template = locate_template(
array(
$template_path . $template_name,
$template_name
)
);
// Modification: Get the template from this plugin, if it exists
if ( ! $template && file_exists( $plugin_path . $template_name ) ){
$template = $plugin_path . $template_name;
}
// Use default template
if ( ! $template ){
$template = $_template;
}
// Return what we found
return $template;
}
}
}
}
/**
* Generate Button HTML.
*/
public function generate_button_cancel_html( $key, $data ) {
$field = $this->plugin_id . $this->id . '_' . $key;
$defaults = array(
'class' => 'button-secondary',
'css' => '',
'custom_attributes' => array(),
'desc_tip' => false,
'description' => '',
'title' => '',
);
$data = wp_parse_args( $data, $defaults );
$style = $this->sync_orders->is_empty() ? ' style="display: none;"' : '';
ob_start();
?>
<tr valign="top" <?php echo $style;?> id="tr-<?php echo $key; ?>">
<th scope="row" class="titledesc">
<label for="<?php echo esc_attr( $field ); ?>"><?php echo wp_kses_post( $data['title'] ); ?></label>
<?php echo $this->get_tooltip_html( $data ); ?>
</th>
<td class="forminp">
<fieldset>
<legend class="screen-reader-text"><span><?php echo wp_kses_post( $data['title'] ); ?></span></legend>
<button class="<?php echo esc_attr( $data['class'] ); ?>" type="button" name="<?php echo esc_attr( $field ); ?>" id="<?php echo esc_attr( $field ); ?>" style="<?php echo esc_attr( $data['css'] ); ?>" <?php echo $this->get_custom_attribute_html( $data ); ?>><?php echo wp_kses_post( $data['title'] ); ?></button>
<img src="<?php echo admin_url('/images/wpspin_light.gif'); ?>" class="waiting" style="display:none" id="aw_loading_cancel" alt="">
<div id="aw_results_cancel"></div>
<?php echo $this->get_description_html( $data ); ?>
</fieldset>
</td>
</tr>
<?php
return ob_get_clean();
}
public function generate_button_html( $key, $data ) {
$field = $this->plugin_id . $this->id . '_' . $key;
$defaults = array(
'class' => 'button-secondary',
'css' => '',
'custom_attributes' => array(),
'desc_tip' => false,
'description' => '',
'title' => '',
);
$data = wp_parse_args( $data, $defaults );
$allorders = wp_count_posts( 'shop_order' );
wp_enqueue_script('aw_do_sync', plugin_dir_url(__FILE__).'js/aw_do_sync.js', array('jquery'));
wp_localize_script('aw_do_sync', 'aw_vars', array(
'aw_nonce' => wp_create_nonce('aw_nonce')
)
);
$args = array(
'post_type' => 'shop_order',
'post_status' => array( 'wc-processing', 'wc-completed' ),
'posts_per_page' => '-1',
'meta_key' => 'aw_sync',
'meta_value' => ' ',
'meta_compare' => '!=',
);
$aw_synced = new WP_Query( $args );
ob_start();
?>
<tr valign="top">
<th scope="row" class="titledesc">
<label for="<?php echo esc_attr( $field ); ?>"><?php echo 'Completed Orders: '.$allorders->{'wc-completed'}.'<br> Synced Orders: '.$aw_synced->post_count; ?></label>
<?php echo $this->get_tooltip_html( $data ); ?>
</th>
<td class="forminp">
<?php
// if ($this->get_aw_synced_orders() == "true") { ?>
<fieldset>
<legend class="screen-reader-text"><span><?php echo wp_kses_post( $data['title'] ); ?></span></legend>
<button class="<?php echo esc_attr( $data['class'] ); ?>" type="button" name="<?php echo esc_attr( $field ); ?>" id="<?php echo esc_attr( $field ); ?>" style="<?php echo esc_attr( $data['css'] ); ?>" <?php echo $this->get_custom_attribute_html( $data ); ?>><?php echo wp_kses_post( $data['title'] ); ?></button>
<img src="<?php echo admin_url('/images/wpspin_light.gif'); ?>" class="waiting" style="display:none" id="aw_loading" alt="">
<div id="aw_results"><?php echo $this->get_description_html( $data ); ?></div>
</fieldset>
<?php //} else {
//echo $this->get_aw_synced_orders();
// } ?>
</td>
</tr>
<?php
return ob_get_clean();
}
public function aw_process_ajax(){
if ( !isset($_POST['aw_nonce']) || !wp_verify_nonce($_POST['aw_nonce'], 'aw_nonce')){
die('Permission Check Failed');
}
// Cancel Sync
if ( $_POST['cancel_sync'] === 'true' ) {
$this->sync_orders->cancel_sync();
if ($this->sync_orders->is_empty()) {
echo 'Sync Cancelled';
}
die();
}
$args = array(
'post_type' => 'shop_order',
'post_status' => array( 'wc-processing', 'wc-completed' ),
'posts_per_page' => '-1',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'aw_sync',
'compare' => 'NOT EXISTS', // works!
'value' => '' // This is ignored, but is necessary...
),
array(
'key' => 'aw_sync',
'value' => 'Not synced'
)
)
);
$aw_orders = new WP_Query( $args );
if ( $aw_orders->have_posts() ) {
$i = 0;
while ( $aw_orders->have_posts() ) : $aw_orders->the_post();
$order_id = get_the_ID();
// Push the order ID to background task manager
$this->sync_orders->push_to_queue( $order_id );
$i++;
endwhile;
$this->sync_orders->save()->dispatch();
echo 'Orders are now being synced in the background. Refresh this page to check on the progress of the sync.';
} else {
echo "All Orders are already synced, so nothing new was synced.";
}
die();
}
}//end class
endif;