pl-sync-ac.php 11.4 KB
<?php

/**
 * Plugin Name: ActiveCampaign Sync
 * Description: ActiveCampaign Sync
 * Version: 1.0.0
 * Author: Ket Con Ma
 * Author URI: http://ketconma.com
 */
add_action('init', 'define_activecampaign');

function define_activecampaign() {
    $setting_ac = get_option("settings_activecampaign");
    define("ACTIVECAMPAIGN_URL_KCM", $setting_ac["api_url"]);
    define("ACTIVECAMPAIGN_API_KEY_KCM", $setting_ac["api_key"]);
}

require_once("activecampaign/includes/ActiveCampaign.class.php");

add_action('woocommerce_checkout_update_order_meta', 'update_activeCampaign', 10, 2);

function update_activeCampaign($order_id, $posted) {
    $tags = array();

    $expiry_date = $_POST['expiry_date'];

    $price_order_shop_subscription = 0;
    $price_order_shop_order = 0;
    $drinks_order_shop_subscription = 0;
    $drinks_order_shop_order = 0;
    $price_order_shop_subscription_new = 0;

    $orders_shop_subscription = get_posts(array(
        'numberposts' => -1,
        'meta_key' => '_customer_user',
        'meta_value' => get_current_user_id(),
        'post_type' => 'shop_subscription',
        'post_status' => 'any',
    ));


    if (count($orders_shop_subscription) > 0) {
        $orders_shop_subscription_child = get_posts(array(
            'numberposts' => -1,
            'post_type' => 'shop_order',
            'post_status' => 'any',
            'meta_query' => array(
                array(
                    'key' => '_subscription_renewal',
                    'value' => $orders_shop_subscription[0]->ID,
                ),
            ),
        ));

        $post_parent = get_post($orders_shop_subscription[0]->ID);

        $orders_shop_subscription_child[] = get_post($post_parent);

        foreach ($orders_shop_subscription_child as $orders_shop_subscription_c) {
            if ($orders_shop_subscription_c->post_parent != 0) {
                $subscription_new = new WC_Order($orders_shop_subscription_c->ID);
                $price_order_shop_subscription_new = $price_order_shop_subscription_new + $subscription_new->get_total();
            } else {
                if ($orders_shop_subscription_c->post_status == 'wc-completed') {
                    $subscription_new = new WC_Order($orders_shop_subscription_c->ID);
                    $price_order_shop_subscription_new = $price_order_shop_subscription_new + $subscription_new->get_total();
                    /*
                      foreach($subscription_new->get_items() as $item){
                      $drinks_order_shop_subscription = $drinks_order_shop_subscription + (int)$item['item_meta']['drinks'][0];
                      }
                     */
                }
            }
        }

        $order_shop_subscription = new WC_Order($orders_shop_subscription[0]->ID);

        $price_order_shop_subscription = $order_shop_subscription->get_total();

        foreach ($order_shop_subscription->get_items() as $item) {
            $drinks_order_shop_subscription = $drinks_order_shop_subscription + (int) $item['item_meta']['drinks'][0];
        }
    }





    $orders_shop_order = get_posts(array(
        'numberposts' => -1,
        'meta_key' => '_customer_user',
        'meta_value' => get_current_user_id(),
        'post_type' => 'shop_order',
        'post_status' => array_keys(wc_get_order_statuses()),
    ));

    foreach ($orders_shop_order as $orders_shop_order_v) {
        $order_v = new WC_Order($orders_shop_order_v->ID);
        if ($order_v->get_total() == 0) {

        } else {
            foreach ($order_v->get_items() as $item) {
                if ($item['item_meta']['drinks'] == NULL) {
                    $price_order_shop_order = $price_order_shop_order + $order_v->get_total();
                    $drinks_order_shop_order = $drinks_order_shop_order + (int) get_num_product($item["name"]);
                } else {

                }
            }
        }
    }

    $customer_orders = get_posts(array(
        'numberposts' => -1,
        'meta_key' => '_customer_user',
        'meta_value' => get_current_user_id(),
        'post_type' => wc_get_order_types(),
        'post_status' => array_keys(wc_get_order_statuses()),
    ));

    $drinks = 0;
    $line_total = 0;

    $cart = WC()->cart;
    if (count($cart->recurring_carts) > 0) {
        foreach ($cart->recurring_carts as $k_carts => $v_carts) {
            foreach ($v_carts->cart_contents as $k_cart => $v_cart) {
                $drinks_order_shop_subscription = $v_cart['variation']['attribute_drinks'];
                $price_order_shop_subscription = $v_cart['line_total'];
                $price_order_shop_subscription_new = $v_cart['line_total'];
            }
        }
    }



    foreach ($customer_orders as $customer_order) {
        $customer_order = new WC_Order($customer_order->ID);
        foreach ($customer_order->get_items() as $item) {
            $drinks = $drinks + (int) $item['item_meta']['drinks'][0];
            $line_total = $line_total + (float) $item['item_meta']['_line_total'][0];
        }
    }

    $order = new WC_Order($order_id);

    $current_user = wp_get_current_user();

    $ac = new ActiveCampaign(ACTIVECAMPAIGN_URL_KCM, ACTIVECAMPAIGN_API_KEY_KCM);

    if ($posted["ship_to_different_address"]) {
        $contact = array(
            "email" => $current_user->user_email,
            "first_name" => $posted['billing_first_name'],
            "last_name" => $posted['billing_last_name'],
            "phone" => $posted['billing_phone'],
            "field[%BILLING_ADDRESS%,0]" => $posted['billing_address_1'],
            "field[%BILLINGCITY%,0]" => $posted['billing_city'],
            "field[%BILLINGSTATE%,0]" => $posted['billing_state'],
            "field[%BILLINGPOSTCODE%,0]" => $posted['billing_postcode'],
            "field[%SHIPPING_ADDRESS%,0]" => $posted['shipping_address_1'],
            "field[%SHIPPING_CITY%,0]" => $posted['shipping_city'],
            "field[%SHIPPING_STATE%,0]" => $posted['shipping_state'],
            "field[%SHIPPING_POSTCODE%,0]" => $posted['shipping_postcode'],
            "field[%BILLING_COUNTRY%,0]" => $posted['billing_country'],
            "field[%SHIPPING_COUNTRY%,0]" => $posted['shipping_country'],
            "field[%BILLING_ADDRESS_2%,0]" => $posted['billing_address_2'],
            "p[5]" => 5,
            "status[2]" => 1, // "Active" status
        );
    } else {
        $contact = array(
            "email" => $current_user->user_email,
            "first_name" => $posted['billing_first_name'],
            "last_name" => $posted['billing_last_name'],
            "phone" => $posted['billing_phone'],
            "field[%BILLING_ADDRESS%,0]" => $posted['billing_address_1'],
            "field[%BILLINGCITY%,0]" => $posted['billing_city'],
            "field[%BILLINGSTATE%,0]" => $posted['billing_state'],
            "field[%BILLINGPOSTCODE%,0]" => $posted['billing_postcode'],
            "field[%SHIPPING_ADDRESS%,0]" => $posted['billing_address_1'],
            "field[%SHIPPING_CITY%,0]" => $posted['billing_city'],
            "field[%SHIPPING_STATE%,0]" => $posted['billing_state'],
            "field[%SHIPPING_POSTCODE%,0]" => $posted['billing_postcode'],
            "field[%SHIPPING_COUNTRY%,0]" => $posted['billing_country'],
            "field[%BILLING_COUNTRY%,0]" => $posted['billing_country'],
            "field[%BILLING_ADDRESS_2%,0]" => $posted['billing_address_2'],
            "p[5]" => 5,
            "status[2]" => 1, // "Active" status
        );
    }
    $post_status = $order->post_status;
    $isPaid = false;
    if ($post_status == 'wc-processing' || $post_status == 'wc-completed') {
        $isPaid = true;
    }
    if (count($customer_orders) == 1) {
        if ($isPaid) {
            $contact["field[%FIRST_ORDER_DATE%,0]"] = time();
        }
        $contact["field[%CREDIT_CARD_EXPIRY_DATE%,0]"] = date('Y-m-d', strtotime($expiry_date . " +27 days"));
    }

    if ($isPaid) {
        $contact["field[%MOST_RECENT_ORDER_DATE%,0]"] = time();
        if (count($cart->recurring_carts) > 0) {
            $contact["field[%SUBSCRIBER_FLAG%,0]"] = 'Y';
            $contact["field[%MONTHLY_SUBSCRIPTION%,0]"] = $drinks_order_shop_subscription;
            $contact["field[%MONTHLY_SUBSCRIPTION_QUANTITY%,0]"] = $drinks_order_shop_subscription;
            $contact["field[%MONTHLY_SUBSCRIPTION_AMOUNT%,0]"] = $price_order_shop_subscription;
            $tags[] = 'PURCHASE: Subscription';
        } else {
            $tags[] = 'PURCHASE: One-Time';
        }
        $contact["field[%MOST_RECENT_ORDER_NUMBER%,0]"] = $order_id;
    }

    $contact["field[%MOST_RECENT_ORDER_STATUS%,0]"] = $order->post->post_status;

    $contact["field[%UNIQUE_CUSTOMER_COUPON_CODE%,0]"] = '';
    $contact["tags"] = implode(",", $tags);

    $contact_sync = $ac->api("contact/sync", $contact);
}

add_action('woocommerce_thankyou_custom', function( $order_id ) {
    $current_user = wp_get_current_user();
    $order = new WC_Order($order_id);
    $ac = new ActiveCampaign(ACTIVECAMPAIGN_URL_KCM, ACTIVECAMPAIGN_API_KEY_KCM);
    $contact = array(
        "email" => $current_user->user_email,
        "p[5]" => 5,
        "status[2]" => 1, // "Active" status
    );
    $contact["field[%MOST_RECENT_ORDER_STATUS%,0]"] = $order->post->post_status;
    $contact["field[%MOST_RECENT_ORDER_NUMBER%,0]"] = $order_id;

    $contact_sync = $ac->api("contact/sync", $contact);
});


add_action('woocommerce_after_order_notes', 'add_expiry_date_checkout_field');

function add_expiry_date_checkout_field($checkout) {
    ?>
    <input type="hidden" id="expiry_date" name="expiry_date" value="" />
    <script>
        jQuery(document).ready(function ($) {
            $('[name="woocommerce_checkout_place_order"]').click(function () {
                var month = $('#tvmonth').val();
                var year = $('#tvyear').val();
                $('#expiry_date').val(year + '-' + month + '-01');
            });
        });
    </script>
    <?php

}

function get_num_product($name) {
    $name = explode(' ', $name);
    return (float) $name[0];
}

function save_order_meta($post_id, $post, $update) {

    /*
     * In production code, $slug should be set only once in the plugin,
     * preferably as a class property, rather than in each function that needs it.
     */

    // If this isn't a 'book' post, don't update it.
    if ($post->post_type == 'shop_order' || $post->post_type == 'shop_subscription') {

        $user_id = get_post_meta($post_id, '_customer_user', true);
        $lastest_order = array();
        if ($user_id > 0) {
            $lastest_order = get_posts(array(
                'numberposts' => -1,
                'meta_key' => '_customer_user',
                'meta_value' => $user_id,
                'post_type' => array('shop_subscription', 'shop_order'),
                'post_status' => 'any',
                'orderby' => 'date',
                'order' => 'DESC',
            ));
        }
        if (count($lastest_order) > 0) {
            if ($lastest_order[0]->ID == $post_id) {
                $user = get_user_by('ID', $user_id);
                $ac = new ActiveCampaign(ACTIVECAMPAIGN_URL_KCM, ACTIVECAMPAIGN_API_KEY_KCM);
                $contact = array(
                    "email" => $user->user_email,
                    "p[5]" => 5,
                    "status[2]" => 1, // "Active" status
                );
                $contact["field[%MOST_RECENT_ORDER_STATUS%,0]"] = $post->post_status;

                $contact_sync = $ac->api("contact/sync", $contact);
            }
        }
    } else {
        return;
    }
}

add_action('save_post', 'save_order_meta', 10, 3);
?>