TWEB-143: Woo Order Data to Salesforce

This commit is contained in:
Tony Volpe
2024-10-24 16:30:41 +00:00
parent 31eacf670a
commit 8217f0dbed

View File

@@ -213,7 +213,6 @@ add_action('after_setup_theme', function () {
add_filter('woocommerce_checkout_fields', function ($fields) {
// $fields['order']['order_comments']['placeholder'] = 'My new placeholder';
return $fields;
});
});
@@ -326,7 +325,6 @@ function add_setup_fees($cart) {
}
}
/**
* Generates a cart summary based on your current state
*
@@ -571,20 +569,11 @@ 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
$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
$sanitized_name = strtolower(str_replace(' ', '_', $accessory["accessory_name"]));
@@ -674,8 +663,6 @@ if ($is_sixforsix_applied || $is_fiveoff_applied) {
}
$cart_items = WC()->cart->get_cart();
//var_dump($cart_items);
return site()->render("cart_summary", array_merge($product, [
"variable_price" => $variable_price,
@@ -1171,7 +1158,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->get_id(), $key, true), // Corrected line
'value' => get_post_meta($order->get_id(), $key, true),
];
}
@@ -1184,38 +1171,23 @@ add_filter('woocommerce_email_order_meta_fields', function ($fields, $sent_to_ad
return $fields;
}, 10, 3);
// 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);
// }
//}
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);
// 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);
}
}
// 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);
@@ -1226,9 +1198,7 @@ function save_card_details_to_order_meta($order_id) {
* 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
$number = preg_replace('/\D/', '', $number);
$patterns = [
'Visa' => '/^4[0-9]{12}(?:[0-9]{3})?$/',
'MasterCard' => '/^5[1-5][0-9]{14}$/',
@@ -1242,21 +1212,14 @@ function detect_card_type($number) {
}
}
// 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
//error_log("Card Number: " . $card_number);
$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();
@@ -1272,16 +1235,15 @@ add_action('woocommerce_thankyou', function ($order_id) {
$order_products = [];
foreach ($order->get_items() as $item) {
$product = $item->get_product(); // Get the WC_Product object
$product = $item->get_product();
$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
@@ -1289,7 +1251,6 @@ add_action('woocommerce_thankyou', function ($order_id) {
// 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
@@ -1349,7 +1310,7 @@ add_action('woocommerce_thankyou', function ($order_id) {
$response = $sf->sendRequest();
// Log the raw response from Salesforce for debugging
error_log('Salesforce Response (Raw): ' . print_r($response, true));
//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));
@@ -1357,10 +1318,10 @@ add_action('woocommerce_thankyou', function ($order_id) {
// 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);
//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));
//error_log('Salesforce Response (Decoded): ' . print_r($decoded_response, true));
}
// Render the order details on the thank-you page
@@ -1404,9 +1365,6 @@ function getProductAccessories($product_id) {
return $formatted_accessories;
}
/**
* Creates the payload for the order to send to Salesforce.
*/
/**
* Creates the payload for the order to send to Salesforce.
*/
@@ -1442,23 +1400,22 @@ function createOrderRequest($order) {
$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
$rate_plan_id = get_post_meta($product_id, 'rate_plan_id', true);
// Optional: Include additional variation details
// 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) );
//error_log( print_r($accessories, true) );
// Add variation or product details to the order products array
$order_products[] = [
'ProductID' => $product_sku,
@@ -1477,20 +1434,20 @@ function createOrderRequest($order) {
"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
"GCLID" => "",
"UserExperience" => null,
"CustomField1" => "",
"CustomField2" => "",
"CustomField3" => "",
"CustomField4" => "",
"MarketingCampaign" => "ecom campaign",
"ShippingID" => "a4t3s000000pYVVAA2",
"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
"CardType" => $card_type,
"CardNumber" => $card_number,
"ExpirationDate" => $expiration_date
],
"ShippingInformation" => [
"FirstName" => $shipping['first_name'],
@@ -1518,29 +1475,23 @@ function createOrderRequest($order) {
],
];
return $orderRequest; // Return the raw PHP array, not encoded
return $orderRequest;
}
/**
* Creates a request header with a unique ID.
*/
function createRequestHeader() {
return [
"RequestID" => "Request_" . microtime(true) // Unique request ID
"RequestID" => "Request_" . microtime(true)
];
}
if (!class_exists("SalesforceSync")) {
class SalesforceSync {
const kACTION_ORDER_CREATE = "CreateOrder";
const kAPPEND_URL = "?brand=MedicalAlert"; // Append brand as a query parameter
const kAPPEND_URL = "?brand=MedicalAlert";
private $url;
private $content;
@@ -1557,7 +1508,7 @@ if (!class_exists("SalesforceSync")) {
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);
@@ -1566,23 +1517,18 @@ if (!class_exists("SalesforceSync")) {
'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
*