aw-functions.php 17.3 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
<?php

// don't load directly
defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

/* ==========================================================================
   Actions and Hooks
   ========================================================================== */

//add_filter( 'woocommerce_thankyou', 'aw_add_ac_contact' );  //uncomment this line and comment the one below then add var dumps etc to debug.
add_action('woocommerce_payment_complete', 'aw_add_ac_contact', 10, 1);
function aw_add_ac_contact($order_id) {

    $issynced = 0;
    $issynced = get_post_meta( $order_id, 'aw_sync', true );

    if ( ($issynced == 1 ) OR (strlen($issynced) > 30 ) ) {

        // return;
    }

    $awc = new WC_Integration_Active_Woo();

    $ac               = new aw_ActiveCampaign($awc->api_url, $awc->api_key);
    $default_tag      = trim($awc->default_tag);
    $customer_revenue = $awc->customer_revenue;
    $synccat          = $awc->settings['sync_cat'];
    $synctags         = $awc->settings['sync_tag'];
    $synccoupons      = $awc->settings['sync_coupon'];
    $orderdate        = $awc->settings['last_order_date'];
    $syncallbilling   = $awc->settings['sync_billing'];
    $sync_ch_fields   = $awc->settings['wc_checkout_sync'];


    if ($customer_revenue){

        $pers    =  preg_replace("/[^a-zA-Z]+/", "_", $customer_revenue);
        $revenue_perstag = strtoupper($pers);

    }

	/*
 	* TEST API CREDENTIALS.
 	*/

	if ( !(int) $ac->credentials_test() ) {
        $to      = get_option( 'admin_email' );
        $subject = "ALERT: WooCommerce Active Campaign API Failure";
        $headers = 'From: ActiveWoo <'.$to.'>' . "\r\n";
        $message = "The API key is no longer working, it may have been reset, or something else. Please log into your site and correct this immediately, or disable the Active Woo plugin.";

		wp_mail( $to, $subject, $message, $headers, $attachments );
		exit();
	}

	//get the contact info via the order_id, get the items that were in the order as well
    $order       = new WC_Order( $order_id );
    $wooid       = $order->id;
    $syncmessage = 1;

    if ( ! add_post_meta( $wooid, 'aw_sync', $syncmessage, true ) ) { //Adds aw_sync if the key does not already exist, else it update value of aw_sync
        update_post_meta ( $wooid, 'aw_sync', $syncmessage );
    } else {
        update_post_meta ( $wooid, 'aw_sync', $syncmessage );
    }

    $issynced = get_post_meta( $wooid, 'aw_sync', true );
    $acemail  = $order->billing_email; //billing email is Active Campaign email
    $acfname  = $order->billing_first_name;
    $aclname  = $order->billing_last_name;
    $acphone  = $order->billing_phone;
    $items    = $order->get_items();
    $total    = $order->get_total();

    if( $syncallbilling ){
        $acstreet   = $order->billing_address_1;
        $acstreet2  = $order->billing_address_2;
        $accity     = $order->billing_city;
        $acstate    = $order->billing_state;
        $accountry  = $order->billing_country;
        $acpostcode = $order->billing_postcode;
    }

	//Active campaign takes a string of comma seperated tags so:
	$actags = "";

	//add the default tag if it was saved
    if ( !empty($default_tag) ) {
        $dirty_default = html_entity_decode($default_tag);
        $clean_default = str_replace(",", "-",$dirty_default);
        $actags .= $clean_default.",";
    }

    if ( !empty($revenue_perstag) && !empty($acemail) ){

        $contact            = array ('email' => $acemail);
        $contact_view_email = $ac->api("contact/view?email={$acemail}");
        if ($contact_view_email->fields) { //brand new contacts won't be in AC yet so we can't view their fields.
            foreach( $contact_view_email->fields as $field ) {
                if ( $field->perstag == $revenue_perstag ) { //this is an existing customer, who already has a value in the revenue field
                    $existing_revenue = (float)$field->val;

                } 
            }
        } 
        
        if (empty($existing_revenue)) { $existing_revenue = 0; }
        
    }

    if ( !empty($acemail) ){
        foreach ($items as $item) {  //loop through the items in the purchase
            $product_variation_id = $item['variation_id'];

            if ( $product_variation_id ) {
                $variation = new WC_Product($item['variation_id']);
                $skuvar    = $variation->get_sku();
                $product   = new WC_Product($item['product_id']);
                $sku       = $product->get_sku();
            } else {
                $product = new WC_Product($item['product_id']);
                $sku     = $product->get_sku();
            }

            //now get the product's sku
            if ( $skuvar ) {
                $actags .=$sku.",".$skuvar.",";
            } else {
                $actags .=$sku.",";
            }

            if ( $synccat == "yes" ) {
                $terms = get_the_terms( $item['product_id'], 'product_cat' ); // now lets get the product categories and make those into tags
                if (!empty($terms)) {	//don't look for categories if there are none for this product
                    foreach ($terms as $term) {
                        $actags .=$term->name.",";
                    }
                }
            }


            if ($synctags == "yes"){
                $ptags = get_the_terms( $item['product_id'], 'product_tag' ); // now lets get the product categories and make those into tags

                if (!empty($ptags)) {	//don't look for categories if there are none for this product
                    foreach ($ptags as $ptag) {
                        $actags .=$ptag->name.",";
                    }
                }
            }
                
            if ($synccoupons == "yes"){
                foreach( $order->get_used_coupons() as $coupon) {
                    $actags .=  $coupon . ",";
                }
            }
        }//each items as item

    	//ball up the contact stuff to send over to AC
        $contact = array(
            "email"       => $acemail,
            "first_name"  => $acfname,
            "last_name"   => $aclname,
            "phone"		  => $acphone,
            'tags'        => $actags,
        );

		if ( !empty($revenue_perstag) ) { //we'll sync contact with the customer revenue totaled up.
            $updaterevenue                = 'field[%'.$revenue_perstag.'%,0]'; //make the field
            $updaterevenueclean           = urlencode($updaterevenue);
            $contact[$updaterevenueclean] = $existing_revenue + $total;
		}

		if ( $syncallbilling == 'yes' ) {

            if ($acstreet){
                $contact['field[%BILLING_ADDRESS%,0]'] = $acstreet;
            }

            if ($acstreet2){
                $contact['field[%BILLING_ADDRESS_2%,0]'] = $acstreet2;
            }

            if($accity){
                $contact['field[%BILLING_CITY%,0]'] = $accity;
            }

            if ($acstate){
                $contact['field[%BILLING_STATE%,0]'] = $acstate;
            }

            if ($acpostcode){
                $contact['field[%BILLING_POSTCODE%,0]'] = $acpostcode;
            }

            if ($accountry){
                $contact['field[%BILLING_COUNTRY%,0]'] = $accountry;
            }
		}

        // sync custom checkout fields
        if ($sync_ch_fields == 'yes') {
            $custom_ch_fields = aw_get_custom_checkout_fields();

            foreach ($custom_ch_fields as $field) {
                $ch_field_raw   = strtoupper( preg_replace("/[^a-zA-Z]+/", "_", $field) );
                $ch_field_dirty = 'field[%'.$ch_field_raw.'%,0]';
                $ch_field       = urlencode($ch_field_dirty);
                $contact[$ch_field] = get_post_meta( $wooid, $field, true );

            }
        }

        if ($orderdate){
            $opers                          = preg_replace("/[^a-zA-Z]+/", "_", $orderdate);
            $orderperstag                   = strtoupper($opers);
            $updatelastorder                = 'field[%'.$orderperstag.'%,0]';
            $order_date                     = $order->order_date;
            $updatelastorderclean           = urlencode($updatelastorder);
            $contact[$updatelastorderclean] = $order_date;
        }

		//send it it over.
		$contact_sync = $ac->api("contact/sync", $contact);
		
        //make sure it got there.
        if (!(int)$contact_sync->success) {
            // uh oh, request failed send an email to the WordPress admin email:
            $to      = get_option( 'admin_email' );
            $subject = "ALERT: WooCommerce Active Campaign API Failure";
            $headers = 'From: ActiveWoo <'.$to.'>' . "\r\n";
            $message = "<p>Syncing contact failed for Woo Commerce order number: #".$wooid." Error returned: " . $contact_sync->error . "</p>";

            wp_mail( $to, $subject, $message, $headers, $attachments );
            exit();
        }

		//now let's add a note to the contact with the Woo Commerce order ID and a link to the order:
		$url = site_url().'/wp-admin/post.php?post='.$wooid.'&action=edit';

        //grab the contact ID from the first API call
		$contact_id = (int)$contact_sync->subscriber_id;

        //create the note:
        $contact_note = array(
            'id'   => $contact_id,
            'note' => 'WooCommerce Order #'.$wooid.' View Order Details:'.$url
        );

    	$contact_note = $ac->api("contact/note/add", $contact_note);

    	$accounturl = $ac->api("account/view", $awc->api_key, 'account_view');

        if ( !empty( $accounturl->account) ){
            $syncmessage = 'This order has been synced to Contact ID: <a href="https://'.$accounturl->account.'/contact/'.$contact_id.'" target=_"blank">https://'.$accounturl->account.'/contact/'.$contact_id.'</a>';

            if ( ! add_post_meta( $wooid, 'aw_sync', $syncmessage, true ) ) { //Adds aw_sync if the key does not already exist, else it update value of aw_sync
                update_post_meta ( $wooid, 'aw_sync', $syncmessage );

            } else {

                update_post_meta ( $wooid, 'aw_sync', $syncmessage );
            }
            $issynced = get_post_meta( $wooid, 'aw_sync', true );

        }
    	//assumes that if the tags made it, the note made it, so no error catch here.
    } else {

        $syncmessage = 'Not Synced - no valid email.';

        if ( ! add_post_meta( $wooid, 'aw_sync', $syncmessage, true ) ) { //Adds aw_sync if the key does not already exist, else it update value of aw_sync
            update_post_meta ( $wooid, 'aw_sync', $syncmessage );
        }
    }
} // end of function aw_add_ac_contact

add_action( 'woocommerce_order_status_completed', 'aw_force_order_sync_on_status_complete');
function aw_force_order_sync_on_status_complete($order_id){

    $issynced = get_post_meta( $order_id, 'aw_sync', true );

	if (($issynced !== 1 ) AND (strlen($issynced) < 30 )) { //30 characters to enable re-try an order that has the 'not synced no email message saved';

        aw_add_ac_contact($order_id);

	} else {

        $file    = WP_PLUGIN_DIR.'/woocommerce-active-campaign/includes/debug.txt';
        // Open the file to get existing content
        $current = file_get_contents($file);
        // Append a new person to the file
        ob_start();

        echo 'FAIL';           // start buffer capture
        if ( $issynced !== 1 ) {
            echo 'Is Synced is not 1';
        }

        if ( strlen($issynced ) < 30 ) {
            echo 'strlen less than 30';
        }

        $contents = ob_get_contents(); // put the buffer into a variable
        ob_end_clean();                // end capture

        $current .= $contents;

        // Write the contents back to the file
        file_put_contents($file, $current);
	}
}

add_action( 'wp_ajax_aw_rc', 'aw_rc_callback' );
add_action( 'wp_ajax_nopriv_aw_rc', 'aw_rc_callback' );
function aw_rc_callback() {
    global $woocommerce;

    $vars    = get_object_vars($woocommerce->integrations);
    $apiurl  = $vars['integrations']['active-woo']->settings['api_url'];
    $apikey  = $vars['integrations']['active-woo']->settings['api_key'];
    $ac      = new aw_ActiveCampaign($apiurl, $apikey);
    $acfname = $_REQUEST['fname'];
    $aclname = $_REQUEST['lname'];
    $acemail = $_REQUEST['email'];
    $prefix  = $vars['integrations']['active-woo']->settings['rc_prefix'];

    if ( empty($prefix) ) {
        $prefix = 'AW_RC';
    }

    $actags  = "";
    $items   = $woocommerce->cart->get_cart();
    $actags .= $prefix.",";
    //var_dump($items);
    foreach($items as $item) {
        if ($vars['integrations']['active-woo']->settings['rc_sku'] == 'yes' ) {

            $product_variation_id = $item['variation_id'];

            if ($product_variation_id) {
                $variation = new WC_Product($item['variation_id']);
                $skuvar    = $variation->get_sku();
                $product   = new WC_Product($item['product_id']);
                $sku       = $product->get_sku();
            } else {
                $product = new WC_Product($item['product_id']);
                $sku     = $product->get_sku();
            }

            //now get the product's sku
            if ( $skuvar ) {
                $actags .= $prefix."-".$sku.",".$prefix."-".$skuvar.",";
            } else {
                $actags .= $prefix."-".$sku.",";
            }

        }

        $terms = get_the_terms( $item['product_id'], 'product_cat' ); // now lets get the product categories and make those into tags

        if ( !empty($terms) AND ($vars['integrations']['active-woo']->settings['rc_cat'] == 'yes'))  {  //don't look for categories if there are none for this product
            foreach ($terms as $term) {
                $actags .= $prefix."-".$term->name.",";
            }
        }

        $ptags = get_the_terms( $item['product_id'], 'product_tag' ); // now lets get the product categories and make those into tags
        if ( !empty($ptags) AND ($vars['integrations']['active-woo']->settings['rc_tag'] == 'yes') ) {  //don't look for categories if there are none for this product
            foreach ($ptags as $ptag) {
                $actags .= $prefix."-".$ptag->name.",";
            }
        }
    }//each items as item


    $contact = array(
        "email"       => $acemail,
        "first_name"  => $acfname,
        "last_name"   => $aclname,
        'tags'        => $actags
    );

    $contact_sync = $ac->api("contact/sync", $contact);
    if (!(int)$contact_sync->success) {
        // uh oh, request failed send an email to the WordPress admin email:
        $to = get_option( 'admin_email' );
        $subject = "ALERT: WooCommerce Active Campaign API Failure";
        $headers = 'From: ActiveWoo <'.$to.'>' . "\r\n";
        $message = "<p>Syncing contact failed for Woo Commerce order number: #".$wooid." Error returned: " . $contact_sync->error . "</p>";
        wp_mail( $to, $subject, $message, $headers, $attachments );
        exit();
    } else {
        echo
        '<div id="awrc-contact"><h3>Name:</h3>
        <h4><span id="fname">'.$acfname.'</span> <span id="lname">'.$aclname.'</span></h4>
        <h3>Email:</h3>
        <h4><!--email_off--><span id="cemail">'.$acemail.'</span><!--/email_off--></h4>
        <p style="text-align:right"><a href="javascript:window.location.href=window.location.href">EDIT</a></p></div>';
    }
       die();
}

// display the extra data in the order admin panel
add_action( 'woocommerce_admin_order_data_after_order_details', 'aw_display_order_data_in_admin' );
function aw_display_order_data_in_admin( $order ){
    $is_subs_page = $order instanceof WC_Subscription;
    $order_id     = $order instanceof WC_Subscription ? $order->order->id : $order->id;
    ?>
    <div class="order_data_column">
        <h4><?php _e( 'Active Campaign Sync Details:' ); ?></h4>
      <?php
        echo '<p><strong>' . __( 'Sync Status' ) . ': </strong>';
        $syncempty = get_post_meta( $order_id, 'aw_sync', true );
        if (strlen($syncempty) < 2) {
            echo "Not synced";
        } else {
            echo get_post_meta( $order_id, 'aw_sync', true ) . '</p>';

            if ( $is_subs_page ) {
                echo '<p><strong>' . __( 'Last Synced Tags' ) . ': </strong>';
                echo implode( ', ', get_post_meta( $order_id, 'aw_subs_tags', true ));
            }
        }
      ?>
    </div>
<?php }

/* ==========================================================================
   Helpers:
   ========================================================================== */

// helper function to check if Checkout Field Editor is active
function aw_is_checkout_editor_active(){

  $active_plugins = (array) get_option( 'active_plugins', array() );

  if ( is_multisite() ){
    $active_plugins = array_merge( $active_plugins, get_site_option( 'active_sitewide_plugins', array() ) );
  }

  return in_array( 'woocommerce-checkout-field-editor/checkout-field-editor.php', $active_plugins ) || array_key_exists( 'woocommerce/woocommerce.php', $active_plugins );
}

function aw_get_custom_checkout_fields(){

    // exit if chekout editor isn't active
    if ( ! aw_is_checkout_editor_active() ) {
        return array();
    }

    $custom_fields = array();
    $fields        = array_merge( WC_Checkout_Field_Editor::get_fields( 'billing' ), WC_Checkout_Field_Editor::get_fields( 'shipping' ), WC_Checkout_Field_Editor::get_fields( 'additional' ) );

    // Loop through all custom fields to see if it should be added
    foreach ( $fields as $field => $options ) {
        if (  $options[ 'custom' ] ) {
            $custom_fields[] = $field;
        }
    }

    return $custom_fields;
}