Feature/TWEB-143 woo order data to sf

This commit is contained in:
Tony Volpe
2024-10-16 23:56:36 +00:00
parent a6fc17dcaa
commit 31eacf670a
6 changed files with 758 additions and 248 deletions

View File

@@ -1,8 +1,98 @@
<?php
add_action( 'gform_after_submission_1', 'post_to_salesforce_and_five9', 10, 2 );
function post_to_salesforce_and_five9( $entry, $form ) {
post_to_salesforce( $entry, $form );
postFiveNine( $entry, $form );
}
function post_to_salesforce( $entry, $form ) {
$salesforceEnvironment = get_option('select-environment');
if ($salesforceEnvironment == 'full') {
$Campaign_ID = '7011I000000dF9n';
$sfdc_oid = '00DDh0000009Umu';
$webtolead_url = 'https://test.salesforce.com/servlet/servlet.WebToLead';
} else {
$Campaign_ID = '7011I000000dDwA';
$sfdc_oid = '00D1I000000mJ0Q';
$webtolead_url = 'https://webto.salesforce.com/servlet/servlet.WebToLead';
}
$cleanPOST = array(
'first_name' => rgar( $entry, '1.3' ),
'last_name' => rgar( $entry, '1.6' ),
'phone' => rgar( $entry, '3' ),
'email' => rgar( $entry, '4' ),
'lead_source' => 'Web',
'oid' => $sfdc_oid,
'Campaign_ID' => $Campaign_ID,
'member_status' => 'Web response',
'Inquiring_for__c' => rgar( $entry, '5' ),
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $webtolead_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($cleanPOST));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
//error_log('Salesforce Web-to-Lead Error: ' . $error_msg);
}
curl_close($ch);
}
// Function to send data to Five9
function postFiveNine( $entry, $form ) {
$Campaign_ID = '701130000026vNy';
$F9list = "Web Form Submissions H";
$F9domain = "connect america";
$permalink = getenv('HTTP_REFERER');
$title = get_permalink(url_to_postid($permalink));
date_default_timezone_set('America/New_York');
$F9Date = date("Y-m-d") . "-" . date("H:i");
$newphone = preg_replace('/^1|\D/', '', rgar($entry, '3'));
$cleanPOST = array(
'first_name' => sanitize_text_field(rgar($entry, '1.3')),
'last_name' => sanitize_text_field(rgar($entry, '1.6')),
'number1' => $newphone,
'F9domain' => $F9domain,
'F9list' => $F9list,
'salesforce_id' => $Campaign_ID,
'Device_6' => $title,
'WebDialer_Key' => $F9Date,
'F9key' => WebDialer_Key,
'F9CallASAP' => true
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.five9.com/web2campaign/AddToList");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($cleanPOST));
$response = curl_exec($ch);
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
//error_log('Five9 API Error: ' . $error_msg);
}
curl_close($ch);
}
// To complete at at later date
//add_action('wp_enqueue_scripts', 'enqueue_google_maps_autocomplete');
include_once(get_template_directory() . '/helpers/SecuredContent.php');
function enqueue_google_maps_autocomplete() {
wp_enqueue_script( 'auto-complete', get_template_directory_uri().'/vendor/google/auto-complete.js');
}
@@ -386,6 +476,9 @@ $protectionPlan = array_filter($_SESSION["addOns"], function($item) {
$keyLockbox = array_filter($_SESSION["addOns"], function($item) {
return $item["label"] === "Key Lockbox";
});
$keyLockbox = array_filter($_SESSION["addOns"], function($item) {
return $item["label"] === "Lockbox";
});
// Store label and price in individual variables
$fallDetectionLabel = reset($fallDetection)["label"];
@@ -469,6 +562,7 @@ if (is_iterable($_SESSION["addOns"])) {
// addons salesforce ID
$falldetection_sfid = $_SESSION["addOns"]["Fall Detection"]["salesforce_id"];;
$protectionplan_sfid = $_SESSION["addOns"]["Protection Plan"]["salesforce_id"];
$lockbox_sfid = $_SESSION["addOns"]["Lockbox"]["salesforce_id"];
// Method to access protected property
function get_protected_property($object, $property) {
@@ -477,16 +571,22 @@ function get_protected_property($object, $property) {
$property->setAccessible(true);
return $property->getValue($object);
}
//var_dump($falldetection_sfid);
//var_dump($protectionplan_sfid);
//var_dump($_SESSION["addOns"]);
//var_dump($lockbox_sfid);
// Get the SKU from the protected parent_data property
$parent_data = get_protected_property($cart_item['data'], 'parent_data');
$sku = $parent_data['sku']; // Salesforce ProductID
//$parent_data = get_protected_property($cart_item['data'], 'parent_data');
//$sku = $parent_data['sku']; // Salesforce ProductID
$rate_plan_sfid = $cart_item['variation']['attribute_rate-plan-sfid']; // Product rate plan salesforce ID
$product_id = $cart_item['product_id'];
$accessories = get_field( 'accessories', $product_id );
//var_dump($rate_plan_sfid);
foreach ($accessories as $accessory) {
// Sanitize the accessory to create a valid PHP variable
// Sanitize the accessory to create a valid PHP variable
$sanitized_name = strtolower(str_replace(' ', '_', $accessory["accessory_name"]));
// Assigning values to individual variables for each accessory
@@ -573,6 +673,10 @@ if ($is_sixforsix_applied || $is_fiveoff_applied) {
$coupon_amount = $coupon->amount;
}
$cart_items = WC()->cart->get_cart();
//var_dump($cart_items);
return site()->render("cart_summary", array_merge($product, [
"variable_price" => $variable_price,
"addonPrice" => $addon_price,
@@ -968,7 +1072,7 @@ function get_phone()
return $fnum;
global $fnum;
} else {
$num = get_option('cta_tel', true);
$ufnum = preg_replace("/[^0-9]/", "", $num);
@@ -1067,7 +1171,7 @@ add_filter('woocommerce_email_order_meta_fields', function ($fields, $sent_to_ad
foreach ($additionalWooFields as $key => $value) {
$fields[$key] = [
'label' => strlen($value["label"]) ? $value["label"] : $value["placeholder"],
'value' => get_post_meta($order->id, $key, true),
'value' => get_post_meta($order->get_id(), $key, true), // Corrected line
];
}
@@ -1080,71 +1184,405 @@ add_filter('woocommerce_email_order_meta_fields', function ($fields, $sent_to_ad
return $fields;
}, 10, 3);
add_action('woocommerce_thankyou', function ($order_id) {
$order = wc_get_order($order_id);
//wc_get_template( 'order/order-details-customer.php', array('order' => $order ));
// Save the card number during checkout
//add_action('woocommerce_checkout_update_order_meta', 'save_card_number_to_order_meta');
//function save_card_number_to_order_meta($order_id) {
// if (isset($_POST['card_number']) && !empty($_POST['card_number'])) {
// $card_number = sanitize_text_field($_POST['card_number']);
// update_post_meta($order_id, '_card_number', $card_number);
// }
//}
foreach( $order->get_items() as $item ){
$item_data = $item->get_data();
$formatted_meta_data = $item->get_formatted_meta_data( '_', true );
}
foreach ( $order->get_fees() as $fees )
$coupon = new WC_Coupon( $coupon_code );
$product_subtotal = $order->subtotal; // 29.95
$order_total = (float)$order->get_total();
$shipping = (float)$order->discount_total;
$coupon_total = (float)$coupon->amount; // $50.00
add_action('woocommerce_checkout_update_order_meta', 'save_card_details_to_order_meta');
function save_card_details_to_order_meta($order_id) {
// Save the card number
if (isset($_POST['card_number']) && !empty($_POST['card_number'])) {
$card_number = sanitize_text_field($_POST['card_number']);
update_post_meta($order_id, '_card_number', $card_number);
foreach( $order->get_coupon_codes() as $coupon_code ) {
$coupon = new WC_Coupon( $coupon_code );
$count = $coupon->get_usage_count();
$limit = $coupon->get_usage_limit_per_user();
if ( ! empty ( $count ) && ! empty ( $limit ) ) {
$remaining = $limit - $count;
// Determine card type based on the card number
$card_type = detect_card_type($card_number);
if ($card_type) {
update_post_meta($order_id, '_card_type', $card_type);
}
}
if ($order->shipping_total == 0) {
$shipping_label = 'Shipping';
$freeshipping_cost = 'Free';
// Save the expiration month
if (isset($_POST['expiration_month']) && !empty($_POST['expiration_month'])) {
$expiration_month = sanitize_text_field($_POST['expiration_month']);
update_post_meta($order_id, '_expiration_month', $expiration_month);
}
// Save the expiration year
if (isset($_POST['expiration_year']) && !empty($_POST['expiration_year'])) {
$expiration_year = sanitize_text_field($_POST['expiration_year']);
update_post_meta($order_id, '_expiration_year', $expiration_year);
}
}
/**
* Function to detect card type based on the card number.
*/
function detect_card_type($number) {
$number = preg_replace('/\D/', '', $number); // Remove all non-digit characters
// Regex patterns for card types
$patterns = [
'Visa' => '/^4[0-9]{12}(?:[0-9]{3})?$/',
'MasterCard' => '/^5[1-5][0-9]{14}$/',
'American Express' => '/^3[47][0-9]{13}$/',
'Discover' => '/^6(?:011|5[0-9]{2})[0-9]{12}$/'
];
foreach ($patterns as $type => $pattern) {
if (preg_match($pattern, $number)) {
return $type;
}
}
// Return null if no patterns match
return null;
}
// Hook into woocommerce_thankyou action
add_action('woocommerce_thankyou', function ($order_id) {
// Get and sanitize card number from POST data
$card_number = get_post_meta($order_id, '_card_number', true);
error_log("Card Number: " . $card_number);
// Fetch the order
$order = wc_get_order($order_id);
// Collect order details for Salesforce and rendering (this remains the same)
$order_data = [];
foreach ($order->get_items() as $item) {
$item_data = $item->get_data();
$formatted_meta_data = $item->get_formatted_meta_data('_', true);
$order_data['items'][] = [
'name' => $item->get_name(),
'product_id' => $item->get_product_id(),
'quantity' => $item->get_quantity(),
'subtotal' => $item->get_subtotal(),
'total' => $item->get_total(),
];
}
$order_products = [];
foreach ($order->get_items() as $item) {
$product = $item->get_product(); // Get the WC_Product object
$product_id = $product->get_id();
$product_sku = $product->get_sku();
$quantity = $item->get_quantity();
// Initialize variables
$rate_plan_id = null;
$attributes = [];
// Check if the product is a variation
if ($product->is_type('variation')) {
$parent_id = $product->get_parent_id(); // Get the parent variable product ID
$attributes = $product->get_attributes(); // Get variation attributes
var_dump($attributes['rate-plan-sfid']);
// Get Rate Plan ID custom field for the variation
$rate_plan_id = get_post_meta($product_id, 'rate_plan_id', true); // Adjust if needed
// Optional: Include additional variation details
$variation_label = implode(', ', $attributes);
} else {
// For non-variation products, still fetch Rate Plan ID if it exists
$rate_plan_id = get_post_meta($product_id, 'rate_plan_id', true);
}
}
$fees_total = 0;
foreach ($order->get_fees() as $fees) {
$order_data['fees'][] = [
'name' => $fees->get_name(),
'amount' => $fees->get_amount(),
];
$fees_total += $fees->get_amount();
}
foreach ($order->get_coupon_codes() as $coupon_code) {
$coupon = new WC_Coupon($coupon_code);
$order_data['coupons'][] = [
'code' => $coupon_code,
'discount_amount' => $coupon->get_amount(),
'remaining_usage' => ($coupon->get_usage_limit_per_user() - $coupon->get_usage_count())
];
}
// Shipping and Coupon Amount Calculation
if ($order->get_shipping_total() == 0) {
$shipping_label = 'Free Shipping';
$shipping_cost = 0;
} else {
$shipping_label = 'Shipping';
$shipping_cost = $order->shipping_total;
$shipping_cost = $order->get_shipping_total();
}
$coupon_amount = $order->discount_total;
if ($coupon_amount == 0) {
unset($coupon_code);
$order_data['shipping'] = [
'label' => $shipping_label,
'cost' => $shipping_cost
];
// Total and Subtotal Data
$order_total = (float)$order->get_total();
$order_subtotal = (float)$order->get_subtotal();
$coupon_total = (float)$order->get_discount_total();
$order_data['totals'] = [
'subtotal' => $order_subtotal,
'total' => $order_total,
'discount' => $coupon_total
];
// Send the order data to Salesforce with encryption
$request_payload = createOrderRequest($order, $card_number);
// Create a new instance of the SalesforceSync class and send the request
$sf = new SalesforceSync(SalesforceSync::kACTION_ORDER_CREATE, $request_payload);
// Send the request and log the response
$response = $sf->sendRequest();
// Log the raw response from Salesforce for debugging
error_log('Salesforce Response (Raw): ' . print_r($response, true));
// Decode the response (assuming it is double-encoded JSON)
$decoded_response = json_decode(json_decode($response));
// Check if there are errors in the decoded response and log them
if (isset($decoded_response->ErrorList)) {
$error_response = serialize($decoded_response->ErrorList);
error_log('Salesforce API Error: ' . $error_response);
} else {
// Log the successful response if no errors are present
error_log('Salesforce Response (Decoded): ' . print_r($decoded_response, true));
}
// Render the order details on the thank-you page
echo site()->render("thank-you-order-details", [
"setupFeePrice" => $fees->get_amount(),
"setupFeeName" => $fees->get_name(),
"couponCode" => $coupon_code,
"couponAmount" => $coupon_amount,
"monthlyFee" => $order->subtotal,
"setupFeePrice" => $fees_total,
"setupFeeName" => isset($order_data['fees'][0]['name']) ? $order_data['fees'][0]['name'] : '',
"couponCode" => isset($order_data['coupons'][0]['code']) ? $order_data['coupons'][0]['code'] : '',
"couponAmount" => $coupon_total,
"monthlyFee" => $order_subtotal,
"shippingLabel" => $shipping_label,
"shippingCost" => $shipping_cost,
"freeshippingCost" => $freeshipping_cost,
"freeshippingCost" => ($shipping_cost == 0) ? 'Free' : '',
"items" => array_map(function ($i) {
return [
"name" => $i->get_name(),
"image" => $i->get_product()->get_image([100, 100]),
"name" => $i['name'],
"image" => wc_get_product($i['product_id'])->get_image([100, 100]), // Get product image
];
}, $order->get_items()),
"total" => $order->get_total(),
"fees" => array_map(function ($f) {
return [
"name" => $f->get_name(),
"amount" => $f->get_amount(),
];
}, $order->get_fees()),
}, $order_data['items']),
"total" => $order_total,
"fees" => $order_data['fees']
]);
});
/**
* Retrieve accessories data for a product.
*/
function getProductAccessories($product_id) {
$accessories = get_field('accessories', $product_id);
$formatted_accessories = [];
if (!empty($accessories)) {
foreach ($accessories as $accessory) {
$formatted_accessories[] = [
"AccessoryID" => $accessory['salesforce_id'],
"Quantity" => 1,
"Price" => $accessory['price']
];
}
}
return $formatted_accessories;
}
/**
* Creates the payload for the order to send to Salesforce.
*/
/**
* Creates the payload for the order to send to Salesforce.
*/
function createOrderRequest($order) {
// Retrieve card type from order meta
$card_type = get_post_meta($order->get_id(), '_card_type', true);
// Retrieve other payment information from the order if needed
$card_number = get_post_meta($order->get_id(), '_card_number', true);
$expiration_month = get_post_meta($order->get_id(), '_expiration_month', true);
$expiration_year = get_post_meta($order->get_id(), '_expiration_year', true);
// Create the expiration date in the required format (e.g., "MM/YYYY")
$expiration_date = sprintf('%02d/%s', $expiration_month, $expiration_year);
// Generate the request header
$header = createRequestHeader();
// Get billing and shipping information from the order
$billing = $order->get_address('billing');
$shipping = $order->get_address('shipping');
$payment_type = "Credit Card"; // Assuming credit card
// Format phone number (example: XXX-XXX-XXXX)
$billing_phone = preg_replace('/(\d{3})(\d{3})(\d{4})/', '$1-$2-$3', $billing['phone']);
$shipping_phone = !empty($shipping['phone']) ? preg_replace('/(\d{3})(\d{3})(\d{4})/', '$1-$2-$3', $shipping['phone']) : $billing_phone;
// Prepare product items and accessories
$order_products = [];
foreach ($order->get_items() as $item) {
$product = $item->get_product(); // Get the WC_Product object
$product_id = $product->get_id();
$product_sku = $product->get_sku();
$quantity = $item->get_quantity();
// Initialize variables
$rate_plan_id = null;
$attributes = [];
$parent_id = $product->get_parent_id(); // Get the parent variable product ID
$attributes = $product->get_attributes(); // Get variation attributes
// Get Rate Plan ID custom field for the variation
$rate_plan_id = get_post_meta($product_id, 'rate_plan_id', true); // Adjust if needed
// Optional: Include additional variation details
$variation_label = implode(', ', $attributes);
// Fetch accessories related to this product
$accessories = getProductAccessories($item->get_product_id());
error_log( print_r($accessories, true) );
// Add variation or product details to the order products array
$order_products[] = [
'ProductID' => $product_sku,
'Quantity' => $item->get_quantity(),
'RatePlanID' => $attributes['rate-plan-sfid'],
'Accessories' => $accessories,
'PromotionID' => $promotion_id
];
}
// Create the payload structure
$orderRequest = [
"RequestHeader" => $header,
"RequestBody" => [
"CustomerFirstName" => $billing['first_name'],
"CustomerLastName" => $billing['last_name'],
"CustomerEmail" => $billing['email'],
"CustomerPhoneNumber" => $billing_phone,
"GCLID" => "", // Add Google Click ID if available
"UserExperience" => null, // Optional field
"CustomField1" => "", // Add if needed
"CustomField2" => "", // Add if needed
"CustomField3" => "", // Add if needed
"CustomField4" => "", // Add if needed
"MarketingCampaign" => "ecom campaign", // Set the campaign name
"ShippingID" => "a4t3s000000pYVVAA2", // Replace with dynamic ShippingID if needed
"PaymentInformation" => [
"PaymentType" => $payment_type,
"CardholderName" => $billing['first_name'] . ' ' . $billing['last_name'],
"CardType" => $card_type, // Use the card type retrieved from meta
"CardNumber" => "XXXXXXXXXXXXXXXX", // Masked card number
"ExpirationDate" => $expiration_date // Use the formatted expiration date
],
"ShippingInformation" => [
"FirstName" => $shipping['first_name'],
"LastName" => $shipping['last_name'],
"Phone" => $shipping_phone,
"Street1" => $shipping['address_1'],
"Street2" => $shipping['address_2'],
"City" => $shipping['city'],
"State" => $shipping['state'],
"PostalCode" => $shipping['postcode'],
"Country" => $shipping['country'] == 'US' ? 'United States' : $shipping['country']
],
"BillingInformation" => [
"FirstName" => $billing['first_name'],
"LastName" => $billing['last_name'],
"Phone" => $billing_phone,
"Street1" => $billing['address_1'],
"Street2" => $billing['address_2'],
"City" => $billing['city'],
"State" => $billing['state'],
"PostalCode" => $billing['postcode'],
"Country" => $billing['country'] == 'US' ? 'United States' : $billing['country']
],
"OrderProducts" => $order_products
],
];
return $orderRequest; // Return the raw PHP array, not encoded
}
/**
* Creates a request header with a unique ID.
*/
function createRequestHeader() {
return [
"RequestID" => "Request_" . microtime(true) // Unique request ID
];
}
if (!class_exists("SalesforceSync")) {
class SalesforceSync {
const kACTION_ORDER_CREATE = "CreateOrder";
const kAPPEND_URL = "?brand=MedicalAlert"; // Append brand as a query parameter
private $url;
private $content;
private $method;
public function __construct($action, $content, $method = "POST") {
// Appending ?brand=MedicalAlert to the URL
$environment_url = get_option('id_api_salesforce', true);
$this->url = "{$environment_url}/{$action}" . self::kAPPEND_URL;
$this->content = $content;
$this->method = $method;
}
public function sendRequest() {
$crypto = new SecuredContent();
$encoded_content = json_encode($crypto->encode_content(json_encode($this->content)));
$request = curl_init($this->url);
curl_setopt($request, CURLOPT_CUSTOMREQUEST, $this->method);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
curl_setopt($request, CURLOPT_POSTFIELDS, $encoded_content);
curl_setopt($request, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($encoded_content),
]);
// Execute the request and retrieve the response
$response = curl_exec($request);
curl_close($request);
// Decode the encrypted response
return $crypto->decode_content($response);
}
}
}
/**
* Rewrite WordPress URLs to Include /blog/ in Post Permalink Structure
*
@@ -1213,7 +1651,7 @@ function gtm_output() { ?>
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-K438P59');</script>
})(window,document,'script','dataLayer','GTM-MJH5WQQ');</script>
<!-- End Google Tag Manager -->
<?php
@@ -1221,7 +1659,7 @@ j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
function gtm_noscript_output() { ?>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-K438P59"
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-MJH5WQQ"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
@@ -1301,8 +1739,10 @@ function woocommerce_shipping_instances_form_fields_filters(){
function shipping_methods_additional_custom_field( $settings ) {
$settings['shipping_comment'] = array(
'title' => __('Salesforce ID', 'woocommerce'),
'type' => 'text',
'type' => 'text',
'placeholder' => __( 'Enter any additional comments for this shipping method.', 'woocommerce' ),
);
return $settings;
}
}