mailchimp_ecommerce.module in Mailchimp E-Commerce 7
Same filename and directory in other branches
Mailchimp eCommerce core functionality.
File
mailchimp_ecommerce.moduleView source
<?php
/**
* @file
* Mailchimp eCommerce core functionality.
*/
/**
* Implements hook_menu().
*/
function mailchimp_ecommerce_menu() {
$items = [];
$items['admin/config/services/mailchimp/ecommerce'] = [
'title' => 'eCommerce',
'description' => 'Configure Mailchimp eCommerce.',
'page callback' => 'drupal_get_form',
'page arguments' => [
'mailchimp_ecommerce_admin_settings',
],
'access callback' => 'mailchimp_apikey_ready_access',
'access arguments' => [
'administer mailchimp',
],
'file' => 'includes/mailchimp_ecommerce.admin.inc',
'type' => MENU_LOCAL_TASK,
'weight' => 20,
];
$items['admin/config/services/mailchimp/ecommerce/sync'] = [
'title' => 'eCommerce product sync',
'description' => 'Sync eCommerce product data to Mailchimp.',
'page callback' => 'drupal_get_form',
'page arguments' => [
'mailchimp_ecommerce_admin_sync',
],
'access callback' => 'mailchimp_apikey_ready_access',
'access arguments' => [
'administer mailchimp',
],
'file' => 'includes/mailchimp_ecommerce.admin.inc',
'type' => MENU_LOCAL_TASK,
'weight' => 21,
];
$items['admin/config/services/mailchimp/ecommerce/sync-orders'] = [
'title' => 'eCommerce historical orders sync',
'description' => 'Sync past eCommerce order data to Mailchimp.',
'page callback' => 'drupal_get_form',
'page arguments' => [
'mailchimp_ecommerce_admin_sync_orders',
],
'access callback' => 'mailchimp_apikey_ready_access',
'access arguments' => [
'administer mailchimp',
],
'file' => 'includes/mailchimp_ecommerce.admin.inc',
'type' => MENU_LOCAL_TASK,
'weight' => 22,
];
return $items;
}
function mailchimp_ecommerce_use_queue() {
return variable_get('mailchimp_ecommerce_use_queue', FALSE);
}
/**
* Implements hook_queue_info().
*/
function mailchimp_ecommerce_cron_queue_info() {
$queues['mailchimp_ecommerce_ops'] = [
'worker callback' => 'mailchimp_ecommerce_queue_process',
'time' => 60,
];
return $queues;
}
/**
* Callback to create a queue item.
*
* @param array $item
* Properties to send to the Queue API.
* - 'op' (string) The operation to be performed by the Mailchimp API. This
* maps to the actual Mailchimp API methods.
* - 'cart_id' (string) The ID of the current cart.
* - 'store_id' (string) The Store ID.
* - 'customer' (array) A fully loaded Mailchimp $customer.
* - 'cart' For cart operations, this is the $order from Drupal.
* - 'order' For order operations, this is the $order from Drupal.
*/
function mailchimp_ecommerce_create_queue_item($item) {
$queue = DrupalQueue::get('mailchimp_ecommerce_ops');
$queue
->createItem($item);
}
/**
* Worker function to process a Mailchimp eCommerce queue item.
*
* @param array $item
* A Drupal Queue item array.
*/
function mailchimp_ecommerce_queue_process($item) {
$list_id = mailchimp_ecommerce_get_list_id();
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
$customer = NULL;
if (isset($item['customer'])) {
$customer = $item['customer'];
$store_id = mailchimp_ecommerce_get_store_id();
if (empty($store_id)) {
return;
}
if (!mailchimp_ecommerce_validate_customer($customer) && !$customer['email_address']) {
return;
}
// Pull member information to get member status.
$memberinfo = mailchimp_get_memberinfo($list_id, $customer['email_address'], TRUE);
$customer['opt_in_status'] = isset($memberinfo->status) && $memberinfo->status == 'subscribed' ? TRUE : FALSE;
}
switch ($item['op']) {
case 'addCart':
case 'updateCart':
$mc_ecommerce
->{$item['op']}($item['store_id'], $item['cart_id'], $customer, $item['cart']);
break;
case 'deleteCart':
$mc_ecommerce
->{$item['op']}($item['store_id'], $item['cart_id']);
break;
case 'addCartLine':
case 'updateCartLine':
$mc_ecommerce
->{$item['op']}($item['store_id'], $item['cart_id'], $item['line_id'], $item['product']);
break;
case 'deleteCartLine':
$mc_ecommerce
->{$item['op']}($item['store_id'], $item['cart_id'], $item['line_id']);
break;
case 'addOrder':
// Pull member information to get member status.
$memberinfo = mailchimp_get_memberinfo($list_id, $customer['email_address'], TRUE);
$customer['opt_in_status'] = isset($memberinfo->status) && $memberinfo->status == 'subscribed' ? TRUE : FALSE;
// Increment customer totals
$remote_customer = mailchimp_ecommerce_get_customer($customer['id']);
// Customer doesn't exist in the store.
if (!$remote_customer) {
return;
}
$customer['orders_count'] = $remote_customer->orders_count + 1;
$customer['total_spent'] = $remote_customer->total_spent + $item['order']['order_total'];
$mc_ecommerce
->{$item['op']}($item['store_id'], $item['order_id'], $customer, $item['order']);
break;
case 'updateOrder':
$mc_ecommerce
->{$item['op']}($item['store_id'], $item['order_id'], $item['order']);
break;
case 'deleteOrder':
$mc_ecommerce
->{$item['op']}($item['store_id'], $item['order_id'], $item['order']);
// Decrement customer totals.
$remote_customer = mailchimp_ecommerce_get_customer($customer['id']);
// Customer doesn't exist in the store.
if (!$remote_customer) {
return;
}
$customer['orders_count'] = $remote_customer->orders_count - 1;
$customer['total_spent'] = $remote_customer->total_spent - $item['order']['order_total'];
$mc_ecommerce
->updateCustomer($store_id, $remote_customer);
break;
}
}
/**
* Implements hook_page_build().
*/
function mailchimp_ecommerce_page_build(&$page) {
$campaign_id = isset($_GET['mc_cid']) ? check_plain($_GET['mc_cid']) : '';
if ($campaign_id) {
$_SESSION['mc_cid'] = $campaign_id;
$_SESSION['mc_landing_site'] = $_SERVER['HTTP_HOST'] . request_uri();
}
}
/**
* Return information about the store from the supplied id.
*
* @param string $store_id
* The ID of the store.
*
* @return object
* Mailchimp store object.
*/
function mailchimp_ecommerce_get_store($store_id) {
$store = NULL;
try {
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
$store = $mc_ecommerce
->getStore($store_id);
} catch (Exception $e) {
if ($e
->getCode() == 404) {
// Store doesn't exist; no need to log an error.
}
else {
mailchimp_ecommerce_log_error_message('Unable to get store: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
return $store;
}
/**
* Add a new store to Mailchimp.
*
* @param string $store_id
* The ID of the store.
* @param array $store
* Associative array of store information.
* - list_id (string) The id for the list associated with the store.
* - name (string) The name of the store.
* - currency_code (string) The three-letter ISO 4217 code for the currency
* that the store accepts.
* @param string $platform
* The eCommerce platform being used to create this store.
* This module's submodules use 'Drupal Ubercart' and 'Drupal Commerce'.
*/
function mailchimp_ecommerce_add_store($store_id, $store, $platform) {
try {
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
$parameters = [
'platform' => $platform,
];
$mc_store = $mc_ecommerce
->addStore($store_id, $store, $parameters);
module_invoke_all('mailchimp_ecommerce_add_store', $mc_store);
} catch (Exception $e) {
mailchimp_ecommerce_log_error_message('Unable to add a new store: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
/**
* Update a store name or currency code.
*
* @param string $store_id
* The ID of the store.
* @param string $name
* The name of the store.
* @param string $currency_code
* The three-letter ISO 4217 code.
* @param string $platform
* The eCommerce platform being used to create this store.
* This module's submodules use 'Drupal Ubercart' and 'Drupal Commerce'.
*/
function mailchimp_ecommerce_update_store($store_id, $name, $currency_code, $platform) {
try {
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
$parameters = [
'platform' => $platform,
];
$mc_ecommerce
->updateStore($store_id, $name, $currency_code, $parameters);
} catch (Exception $e) {
mailchimp_ecommerce_log_error_message('Unable to update a store: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
/**
* Add a new customer to Mailchimp.
*
* @param array $customer
* Array of customer fields.
*
* @see http://developer.mailchimp.com/documentation/mailchimp/reference/ecommerce/stores/customers/#create-post_ecommerce_stores_store_id_customers
*/
function mailchimp_ecommerce_add_customer($customer) {
try {
$store_id = mailchimp_ecommerce_get_store_id();
$list_id = mailchimp_ecommerce_get_list_id();
if (empty($store_id)) {
throw new Exception('Cannot add a customer without a store ID.');
}
// Pull member information to get member status.
$memberinfo = mailchimp_get_memberinfo($list_id, $customer['email_address'], TRUE);
$opt_in_status = isset($memberinfo->status) && $memberinfo->status == 'subscribed' ? TRUE : FALSE;
$customer['opt_in_status'] = $opt_in_status;
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
$mc_ecommerce
->addCustomer($store_id, $customer);
} catch (Exception $e) {
mailchimp_ecommerce_log_error_message('Unable to add a customer: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
/**
* Read a customer from Mailchimp.
*
* @param string $customer_id
* Unique id of customer.
*
* @return object
* Mailchimp customer object.
*/
function mailchimp_ecommerce_get_customer($customer_id) {
$customer = NULL;
try {
$store_id = mailchimp_ecommerce_get_store_id();
if (empty($store_id)) {
throw new Exception('Cannot get a customer without a store ID.');
}
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
$customer = $mc_ecommerce
->getCustomer($store_id, $customer_id);
} catch (Exception $e) {
if ($e
->getCode() == 404) {
// Customer doesn't exist in the store; no need to log an error.
}
else {
mailchimp_ecommerce_log_error_message('Unable to get a customer: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
return $customer;
}
/**
* Update a customer record in Mailchimp.
*
* @param array $customer
* Array of customer fields.
*
* @see http://developer.mailchimp.com/documentation/mailchimp/reference/ecommerce/stores/customers/#create-post_ecommerce_stores_store_id_customers
*/
function mailchimp_ecommerce_update_customer($customer) {
try {
$store_id = mailchimp_ecommerce_get_store_id();
$list_id = mailchimp_ecommerce_get_list_id();
if (empty($store_id)) {
throw new Exception('Cannot update a customer without a store ID.');
}
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
// Pull member information to get member status.
$memberinfo = mailchimp_get_memberinfo($list_id, $customer['email_address'], TRUE);
$customer['opt_in_status'] = isset($memberinfo->status) && $memberinfo->status == 'subscribed' ? TRUE : FALSE;
$mc_ecommerce
->updateCustomer($store_id, $customer);
} catch (Exception $e) {
mailchimp_ecommerce_log_error_message('Unable to update a customer: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
/**
* Delete a customer from Mailchimp.
*
* @param string $customer_id
* Unique id of customer.
*/
function mailchimp_ecommerce_delete_customer($customer_id) {
try {
$store_id = mailchimp_ecommerce_get_store_id();
if (empty($store_id)) {
throw new Exception('Cannot delete a customer without a store ID.');
}
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
$mc_ecommerce
->deleteCustomer($store_id, $customer_id);
} catch (Exception $e) {
mailchimp_ecommerce_log_error_message('Unable to delete a customer: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
/**
* Adds a new cart to the current Mailchimp store.
*
* @param string $cart_id
* The cart ID.
* @param array $customer
* Associative array of customer information.
* - id (string): A unique identifier for the customer.
* @param array $cart
* Associative array of cart information.
* - currency_code (string): The three-letter ISO 4217 currency code.
* - order_total (float): The total for the order.
* - lines (array): An array of the order's line items.
*
* @see http://developer.mailchimp.com/documentation/mailchimp/reference/ecommerce/stores/carts/#create-post_ecommerce_stores_store_id_carts
*/
function mailchimp_ecommerce_add_cart($cart_id, array $customer, array $cart) {
try {
$store_id = mailchimp_ecommerce_get_store_id();
if (empty($store_id)) {
throw new Exception('Cannot add a cart without a store ID.');
}
// Do nothing with no email.
if (!$customer['email_address']) {
return;
}
if (!mailchimp_ecommerce_validate_customer($customer)) {
// A user not existing in the store's Mailchimp list/audience is not an error, so
// don't throw an exception.
return;
}
$campaign_id = mailchimp_ecommerce_get_campaign_id();
if (!empty($campaign_id)) {
$cart['campaign_id'] = $campaign_id;
$cart['landing_site'] = isset($_SESSION['mc_landing_site']) ? $_SESSION['mc_landing_site'] : '';
}
if (mailchimp_ecommerce_use_queue()) {
mailchimp_ecommerce_create_queue_item([
'op' => 'addCart',
'cart_id' => $cart_id,
'store_id' => $store_id,
'customer' => $customer,
'cart' => $cart,
]);
}
else {
$list_id = mailchimp_ecommerce_get_list_id();
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
// Pull member information to get member status.
$memberinfo = mailchimp_get_memberinfo($list_id, $customer['email_address'], TRUE);
$customer['opt_in_status'] = isset($memberinfo->status) && $memberinfo->status == 'subscribed' ? TRUE : FALSE;
$mc_ecommerce
->addCart($store_id, $cart_id, $customer, $cart);
}
} catch (Exception $e) {
mailchimp_ecommerce_log_error_message('Unable to add a cart: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
/**
* Updates an existing cart in the current Mailchimp store.
*
* @param string $cart_id
* The cart ID.
* @param array $customer
* Associative array of customer information.
* - id (string): A unique identifier for the customer.
* @param array $cart
* Associative array of cart information.
* - currency_code (string): The three-letter ISO 4217 currency code.
* - order_total (float): The total for the order.
* - lines (array): An array of the order's line items.
*
* @see http://developer.mailchimp.com/documentation/mailchimp/reference/ecommerce/stores/carts/#edit-patch_ecommerce_stores_store_id_carts_cart_id
*/
function mailchimp_ecommerce_update_cart($cart_id, array $customer, array $cart) {
try {
$store_id = mailchimp_ecommerce_get_store_id();
if (empty($store_id)) {
throw new Exception('Cannot update a cart without a store ID.');
}
// Do nothing with no email.
if (!$customer['email_address']) {
return;
}
if (mailchimp_ecommerce_use_queue()) {
mailchimp_ecommerce_create_queue_item([
'op' => 'updateCart',
'cart_id' => $cart_id,
'store_id' => $store_id,
'customer' => $customer,
'cart' => $cart,
]);
}
else {
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
$list_id = mailchimp_ecommerce_get_list_id();
// Pull member information to get member status.
$memberinfo = mailchimp_get_memberinfo($list_id, $customer['email_address'], TRUE);
$customer['opt_in_status'] = isset($memberinfo->status) && $memberinfo->status == 'subscribed' ? TRUE : FALSE;
$parameters = [
'customer' => (object) $customer,
];
$parameters += $cart;
$mc_ecommerce
->updateCart($store_id, $cart_id, $parameters);
}
} catch (Exception $e) {
mailchimp_ecommerce_log_error_message('Unable to update a cart: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
/**
* Deletes a cart in the current Mailchimp store.
*
* @param string $cart_id
* The cart ID.
*/
function mailchimp_ecommerce_delete_cart($cart_id) {
try {
$store_id = mailchimp_ecommerce_get_store_id();
if (empty($store_id)) {
throw new Exception('Cannot delete a cart without a store ID.');
}
if (mailchimp_ecommerce_use_queue()) {
mailchimp_ecommerce_create_queue_item([
'op' => 'deleteCart',
'cart_id' => $cart_id,
'store_id' => $store_id,
]);
}
else {
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
$mc_ecommerce
->deleteCart($store_id, $cart_id);
}
} catch (Exception $e) {
if ($e
->getCode() == 404) {
// Cart doesn't exist; no need to log an error.
}
else {
mailchimp_ecommerce_log_error_message('Unable to delete a cart: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
}
/**
* Adds a line to a cart in the current Mailchimp store.
*
* @param string $cart_id
* The cart ID.
* @param string $line_id
* A unique identifier for the order line item.
* @param array $product
* Associative array of product information.
* - product_id (string) The unique identifier for the product.
* - product_variant_id (string) The unique identifier for the variant.
* - quantity (int) The quantity of a cart line item.
* - price (float) The price of a cart line item.
*/
function mailchimp_ecommerce_add_cart_line($cart_id, $line_id, $product) {
try {
$store_id = mailchimp_ecommerce_get_store_id();
if (empty($store_id)) {
throw new Exception('Cannot add a cart line without a store ID.');
}
if (mailchimp_ecommerce_use_queue()) {
mailchimp_ecommerce_create_queue_item([
'op' => 'addCartLine',
'cart_id' => $cart_id,
'store_id' => $store_id,
'line_id' => $line_id,
'product' => $product,
]);
}
else {
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
$mc_ecommerce
->addCartLine($store_id, $cart_id, $line_id, $product);
}
} catch (Exception $e) {
mailchimp_ecommerce_log_error_message('Unable to add a cart line: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
/**
* Updates an existing line in a cart in the current Mailchimp store.
*
* @param string $cart_id
* The cart ID.
* @param string $line_id
* A unique identifier for the order line item.
* @param array $product
* Associative array of product information.
* - product_id (string) The unique identifier for the product.
* - product_variant_id (string) The unique identifier for the variant.
* - quantity (int) The quantity of a cart line item.
* - price (float) The price of a cart line item.
*/
function mailchimp_ecommerce_update_cart_line($cart_id, $line_id, $product) {
try {
$store_id = mailchimp_ecommerce_get_store_id();
if (empty($store_id)) {
throw new Exception('Cannot update a cart line without a store ID.');
}
if (mailchimp_ecommerce_use_queue()) {
mailchimp_ecommerce_create_queue_item([
'op' => 'updateCartLine',
'cart_id' => $cart_id,
'store_id' => $store_id,
'line_id' => $line_id,
'product' => $product,
]);
}
else {
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
$mc_ecommerce
->updateCartLine($store_id, $cart_id, $line_id, $product);
}
} catch (Exception $e) {
mailchimp_ecommerce_log_error_message('Unable to update a cart line: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
/**
* Deletes a line in a cart in the current Mailchimp store.
*
* @param string $cart_id
* The cart ID.
* @param string $line_id
* A unique identifier for the order line item.
*/
function mailchimp_ecommerce_delete_cart_line($cart_id, $line_id) {
try {
$store_id = mailchimp_ecommerce_get_store_id();
if (empty($store_id)) {
throw new Exception('Cannot delete a cart line without a store ID.');
}
if (mailchimp_ecommerce_use_queue()) {
mailchimp_ecommerce_create_queue_item([
'op' => 'deleteCartLine',
'cart_id' => $cart_id,
'store_id' => $store_id,
'line_id' => $line_id,
]);
}
else {
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
$mc_ecommerce
->deleteCartLine($store_id, $cart_id, $line_id);
}
} catch (Exception $e) {
mailchimp_ecommerce_log_error_message('Unable to delete a cart line: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
/**
* Gets an order from the current Mailchimp store.
*
* @param string $order_id
* The order ID.
*
* @return object|null
* The order.
*/
function mailchimp_ecommerce_get_order($order_id) {
try {
$store_id = mailchimp_ecommerce_get_store_id();
if (empty($store_id)) {
throw new Exception('Cannot get an order without a store ID.');
}
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
$order = $mc_ecommerce
->getOrder($store_id, $order_id);
return $order;
} catch (Exception $e) {
if ($e
->getCode() == 404) {
// Order doesn't exist in the store; no need to log an error.
}
else {
mailchimp_ecommerce_log_error_message('Unable to get order: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
return NULL;
}
/**
* Gets a cart from the current Mailchimp store.
*
* @param string $cart_id
* The cart ID.
*
* @return object|null
* The cart.
*/
function mailchimp_ecommerce_get_cart($cart_id) {
try {
$store_id = mailchimp_ecommerce_get_store_id();
if (empty($store_id)) {
throw new Exception('Cannot get a cart without a store ID.');
}
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
$order = $mc_ecommerce
->getCart($store_id, $cart_id);
return $order;
} catch (Exception $e) {
if ($e
->getCode() == 404) {
// Order doesn't exist in the store; no need to log an error.
}
else {
mailchimp_ecommerce_log_error_message('Unable to get cart: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
return NULL;
}
/**
* Adds a new order to the current Mailchimp store.
*
* @param string $order_id
* The order ID.
* @param array $customer
* Associative array of customer information.
* - id (string): A unique identifier for the customer.
* @param array $order
* Associative array of order information.
* - currency_code (string): The three-letter ISO 4217 currency code.
* - order_total (float): The total for the order.
* - lines (array): An array of the order's line items.
*
* @see http://developer.mailchimp.com/documentation/mailchimp/reference/ecommerce/stores/orders/#create-post_ecommerce_stores_store_id_orders
*/
function mailchimp_ecommerce_add_order($order_id, array $customer, array $order) {
try {
$store_id = mailchimp_ecommerce_get_store_id();
if (empty($store_id)) {
throw new Exception('Cannot add an order without a store ID.');
}
if (!mailchimp_ecommerce_validate_customer($customer)) {
// A user not existing in the store's Mailchimp list/audience is not an error, so
// don't throw an exception.
return;
}
$campaign_id = mailchimp_ecommerce_get_campaign_id();
if (!empty($campaign_id)) {
$order['campaign_id'] = $campaign_id;
$order['landing_site'] = isset($_SESSION['mc_landing_site']) ? $_SESSION['mc_landing_site'] : '';
}
if (mailchimp_ecommerce_use_queue()) {
mailchimp_ecommerce_create_queue_item([
'op' => 'addOrder',
'store_id' => $store_id,
'order_id' => $order_id,
'customer' => $customer,
'order' => $order,
]);
}
else {
$list_id = mailchimp_ecommerce_get_list_id();
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
// Pull member information to get member status.
$memberinfo = mailchimp_get_memberinfo($list_id, $customer['email_address'], TRUE);
$customer['opt_in_status'] = isset($memberinfo->status) && $memberinfo->status == 'subscribed' ? TRUE : FALSE;
// Increment customer totals
$remote_customer = mailchimp_ecommerce_get_customer($customer['id']);
// Customer doesn't exist in the store.
if (!$remote_customer) {
return;
}
$customer['orders_count'] = $remote_customer->orders_count + 1;
$customer['total_spent'] = $remote_customer->total_spent + $order['order_total'];
$mc_ecommerce
->addOrder($store_id, $order_id, $customer, $order);
}
} catch (Exception $e) {
mailchimp_ecommerce_log_error_message('Unable to add an order: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
/**
* Updates an existing order in the current Mailchimp store.
*
* @param string $order_id
* The order ID.
* @param array $order
* Associative array of order information.
* - currency_code (string): The three-letter ISO 4217 currency code.
* - order_total (float): The total for the order.
* - lines (array): An array of the order's line items.
*
* @see http://developer.mailchimp.com/documentation/mailchimp/reference/ecommerce/stores/orders/#edit-patch_ecommerce_stores_store_id_orders_order_id
*/
function mailchimp_ecommerce_update_order($order_id, array $order) {
try {
$store_id = mailchimp_ecommerce_get_store_id();
if (empty($store_id)) {
throw new Exception('Cannot update an order without a store ID.');
}
if (mailchimp_ecommerce_use_queue()) {
mailchimp_ecommerce_create_queue_item([
'op' => 'updateOrder',
'order_id' => $order_id,
'store_id' => $store_id,
'order' => $order,
]);
}
else {
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
$mc_ecommerce
->updateOrder($store_id, $order_id, $order);
}
} catch (Exception $e) {
mailchimp_ecommerce_log_error_message('Unable to update an order: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
/**
* Deletes an Order from the current Mailchimp store.
*
* @param string $order_id
* The Order ID.
*/
function mailchimp_ecommerce_delete_order($order_id) {
try {
$store_id = mailchimp_ecommerce_get_store_id();
if (empty($store_id)) {
throw new Exception('Cannot delete an order without a store ID.');
}
// Get customer and order arrays.
$order = commerce_order_load($order_id);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$mc_order = _mailchimp_ecommerce_commerce_build_order($order_wrapper);
$customer = $mc_order['customer'];
$order = $mc_order['order_data'];
if (mailchimp_ecommerce_use_queue()) {
mailchimp_ecommerce_create_queue_item([
'op' => 'deleteOrder',
'order_id' => $order_id,
'store_id' => $store_id,
'customer' => $customer,
'order' => $order,
]);
}
else {
$list_id = mailchimp_ecommerce_get_list_id();
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
$mc_ecommerce
->deleteOrder($store_id, $order_id);
// Pull member information to get member status.
$order = $mc_ecommerce
->getOrder($store_id, $order_id);
// Decrement customer totals.
$remote_customer = mailchimp_ecommerce_get_customer($order->customer->id);
// Customer doesn't exist in the store.
if (!$remote_customer) {
return;
}
$customer['orders_count'] = $remote_customer->orders_count - 1;
$customer['total_spent'] = $remote_customer->total_spent - $order['order_total'];
$mc_ecommerce
->updateCustomer($store_id, $customer);
}
} catch (Exception $e) {
if ($e
->getCode() == 404) {
// Order doesn't exist; no need to log an error.
}
else {
mailchimp_ecommerce_log_error_message('Unable to delete an order: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
}
/**
* Adds a product to Mailchimp.
*
* Adds a product variant if a product with the given ID exists. Gracefully
* handles updating an existing variant.
*
* In Mailchimp, each product requires at least one product variant. This
* function will create a single product variant when creating new products.
*
* A product variant is contained within a product and can be used to
* represent shirt size, color, etc.
*
* @param string $product_id
* Unique ID of the product.
* @param string $product_variant_id
* ID of the product variant.
* May be identical to $product_id for single products.
* @param string $title
* The product title.
* @param string $description
* The product description.
* @param string $type
* The product type.
* @param string $sku
* The product SKU.
* @param string $url
* The product URL.
* @param float $price
* The product price.
* @param string $image_url
* A URL to a representative product Image.
* @param int $stock
* If enabled, the current active inventory.
*/
function mailchimp_ecommerce_add_product($product_id, $product_variant_id, $title, $description = '', $type, $sku, $url, $price, $image_url = '', $stock = 1) {
try {
$store_id = mailchimp_ecommerce_get_store_id();
if (empty($store_id)) {
throw new Exception('Cannot add a product without a store ID.');
}
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
$variant = [
'id' => $product_variant_id,
'title' => $title,
'sku' => $sku,
'url' => $url,
'price' => $price,
'image_url' => $image_url,
'inventory_quantity' => (int) $stock,
];
// Create Mailchimp product from product type.
$mc_ecommerce
->addProduct($store_id, $product_id, $title, $url, [
$variant,
], [
'title' => $title,
'description' => $description,
'type' => $type,
'sku' => $sku,
'url' => $url,
'price' => $price,
'image_url' => $image_url,
'inventory_quantity' => (int) $stock,
]);
} catch (Exception $e) {
// Product already exists, so try adding a variant.
if ($e
->getCode() == 400) {
try {
$mc_ecommerce
->addProductVariant($store_id, $product_id, [
'id' => $product_variant_id,
'description' => $description,
'title' => $title,
'sku' => $sku,
'price' => $price,
'url' => $url,
'image_url' => $image_url,
'inventory_quantity' => (int) $stock,
]);
} catch (Exception $e) {
// If the variant already exists, update it.
if ($e
->getCode() == 400) {
try {
$mc_ecommerce
->updateProductVariant($store_id, $product_id, $product_variant_id, [
'description' => $description,
'type' => $type,
'title' => $title,
'sku' => $sku,
'url' => $url,
'price' => $price,
'image_url' => $image_url,
]);
} catch (Exception $e) {
mailchimp_ecommerce_log_error_message('Unable to update a product variant: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
else {
mailchimp_ecommerce_log_error_message('Unable to add a product variant: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
}
if ($e
->getCode() != 404 && $e
->getCode() != 400) {
// TODO: check if product has adjustments with additional SKUs defined. Add these as variants instead of default
// No existing product; create new product with default variant.
mailchimp_ecommerce_log_error_message('Unable to add a product: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
}
/**
* Updates an existing product in Mailchimp.
*
* Mailchimp only allows for product variants to be updated. The parent
* product cannot be changed once created. This function will update the
* variant associated with the given product ID and SKU.
*
* @param string $product_id
* Unique ID of the product.
* @param string $product_variant_id
* ID of the product variant.
* May be identical to $product_id for single products.
* @param string $title
* The product title.
* @param string $sku
* The product SKU.
* @param float $price
* The product price.
* @param string $image_url
* A URL to a representative product Image.
* @param int $stock
* If enabled, the current active inventory.
*/
function mailchimp_ecommerce_update_product($product_id, $product_variant_id, $title, $description = '', $sku, $url, $price, $image_url = '', $stock = 1) {
try {
$store_id = mailchimp_ecommerce_get_store_id();
if (empty($store_id)) {
throw new Exception('Cannot update a product without a store ID.');
}
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
$variant = [
'id' => $product_variant_id,
'title' => $title,
'sku' => $sku,
'url' => $url,
'price' => $price,
'image_url' => $image_url,
'inventory_quantity' => (int) $stock,
];
// This code only runs if the 404 isn't returned on get product.
$mc_ecommerce
->updateProduct($store_id, $product_id, [
$variant,
], [
'title' => $title,
'description' => $description,
'sku' => $sku,
'url' => $url,
'price' => $price,
'image_url' => $image_url,
'inventory_quantity' => (int) $stock,
]);
} catch (Exception $e) {
mailchimp_ecommerce_log_error_message('Unable to add a product: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
/**
* Deletes a product in Mailchimp.
*
* @param string $product_id
* Unique ID of the product.
*/
function mailchimp_ecommerce_delete_product($product_id) {
try {
$store_id = mailchimp_ecommerce_get_store_id();
if (empty($store_id)) {
throw new Exception('Cannot delete a product without a store ID.');
}
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
$mc_ecommerce
->deleteProduct($store_id, $product_id);
} catch (Exception $e) {
mailchimp_ecommerce_log_error_message('Unable to delete product: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
/**
* Deletes a product variant in Mailchimp.
*
* Automatically deletes the product if the only product variant is removed.
*
* @param string $product_id
* Unique ID of the product.
* @param string $product_variant_id
* ID of the product variant.
* Can be identical to $product_id for single products.
*/
function mailchimp_ecommerce_delete_product_variant($product_id, $product_variant_id) {
try {
$store_id = mailchimp_ecommerce_get_store_id();
if (empty($store_id)) {
throw new Exception('Cannot delete a product variant without a store ID.');
}
/* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
$mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
try {
$variants = $mc_ecommerce
->getProductVariants($store_id, $product_id);
// Delete the variant if the product contains multiple variants.
if ($variants->total_items > 1) {
$mc_ecommerce
->deleteProductVariant($store_id, $product_id, $product_variant_id);
}
else {
// Delete the product if the product has only one variant.
$mc_ecommerce
->deleteProduct($store_id, $product_id);
}
} catch (Exception $e) {
if ($e
->getCode() == 404) {
// This product isn't in Mailchimp.
return;
}
else {
// An actual error occurred; pass on the exception.
throw new Exception($e
->getMessage(), $e
->getCode(), $e);
}
}
} catch (Exception $e) {
mailchimp_ecommerce_log_error_message('Unable to delete product variant: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
/**
* Generates a unique ID used to identify a store integration to Mailchimp.
*
* @return string
* The unique store ID.
*/
function mailchimp_ecommerce_generate_store_id() {
return uniqid();
}
/**
* Gets the store ID of the Mailchimp eCommerce integration.
*
* @return string
* The store ID.
*/
function mailchimp_ecommerce_get_store_id() {
return variable_get('mailchimp_ecommerce_store_id', NULL);
}
/**
* Gets the campaign ID from the current user's session.
*
* @return string
* The campaign ID.
*/
function mailchimp_ecommerce_get_campaign_id() {
$session_campaign = isset($_SESSION['mc_cid']) ? check_plain($_SESSION['mc_cid']) : '';
$campaign_id = '';
/* @var \Mailchimp\MailchimpCampaigns $mc_campaigns */
$mc_campaigns = mailchimp_get_api_object('MailchimpCampaigns');
// Check to see if this is a valid Mailchimp campaign.
try {
if (!empty($session_campaign)) {
$campaign = $mc_campaigns
->getCampaign($session_campaign);
$campaign_id = $campaign->id;
}
} catch (Exception $e) {
if ($e
->getCode() == 404) {
// Campaign doesn't exist; no need to log an error.
}
else {
mailchimp_ecommerce_log_error_message('Unable to get campaign: ' . $e
->getMessage());
mailchimp_ecommerce_show_error($e
->getMessage());
}
}
return $campaign_id;
}
/**
* Determines if customer data is valid.
*
* @param array $customer
* Array of customer data.
*
* @return bool
* TRUE if customer data is valid.
*/
function mailchimp_ecommerce_validate_customer(array $customer) {
return isset($customer['id']) && !empty($customer['id']);
}
/**
* Get the List ID being used.
*
* @return string
* The List/Audience ID.
*/
function mailchimp_ecommerce_get_list_id() {
return variable_get('mailchimp_ecommerce_list_id', '');
}
/**
* Returns currency codes from the xml file.
*
* This is used if Drupal Commerce is not available.
*
* @return array
* Array of currency codes.
*/
function mailchimp_ecommerce_get_currency_codes() {
$currencyfile = drupal_get_path('module', 'mailchimp_ecommerce') . '/' . 'currency-codes-iso4217.xml';
$currencydata = simplexml_load_file($currencyfile);
$json_string = json_encode($currencydata);
$result_array = json_decode($json_string, TRUE);
$currencycodes = [];
foreach ($result_array['CcyTbl']['CcyNtry'] as $item) {
if (!empty($item['Ccy'])) {
$currencycodes[$item['Ccy']] = $item['CcyNm'] . ' (' . $item['Ccy'] . ')';
}
}
return $currencycodes;
}
/**
* Logs an error message using watchdog, if enabled.
*
* @param string $message
* The error message to log.
*/
function mailchimp_ecommerce_log_error_message($message) {
if (function_exists('watchdog')) {
watchdog('mailchimp_ecommerce', '%message', [
'%message' => $message,
], WATCHDOG_ERROR);
}
}
/**
* @inheritdoc
*/
function _mailchimp_ecommerce_get_local_customer($email) {
// Load an existing customer using the order email.
$result = db_query("SELECT mailchimp_customer_id FROM {mailchimp_ecommerce_customer} WHERE mail = :mail", [
':mail' => $email,
]);
$customer_id = NULL;
$customer = $result
->fetchAssoc();
if (!empty($customer)) {
$customer_id = $customer['mailchimp_customer_id'];
}
if (empty($customer_id)) {
// Create a new local customer.
$customer_id = db_insert('mailchimp_ecommerce_customer')
->fields([
'mail' => $email,
])
->execute();
}
return $customer_id;
}
/**
* Increment order totals
*/
function _mailchimp_ecommerce_increment_order_total($email_address, $total_spent, $orders_count = 1) {
$query = $this->database
->select('mailchimp_ecommerce_customer', 'c')
->fields('c', [
'mailchimp_customer_id',
'orders_count',
'total_spent',
])
->condition('mail', $email_address);
$result = $query
->execute()
->fetch();
if (!empty($result)) {
$customer_id = $result->mailchimp_customer_id;
$new_orders_count = $result->orders_count + $orders_count;
$new_total_spent = $result->total_spent + $total_spent;
$this->database
->update('mailchimp_ecommerce_customer')
->fields([
'orders_count' => $new_orders_count,
'total_spent' => $new_total_spent,
])
->condition('mailchimp_customer_id', $customer_id)
->execute();
return TRUE;
}
return FALSE;
}
/**
* Helper function to show an error message for admin users.
*/
function mailchimp_ecommerce_show_error($message) {
if (user_access('administer mailchimp')) {
drupal_set_message($message, 'error');
}
}
/**
* Get the human readable name of a node type by the slug.
*
* @param $type_slug
* slug of a node type
*
* @return string|false
* String for the name of the type if it exists, otherwise FALSE
*/
function mailchimp_ecommerce_get_node_type_name($type_slug) {
$all_types = node_type_get_names();
$type_name = FALSE;
if (isset($all_types[$type_slug])) {
$type_name = $all_types[$type_slug];
}
return $type_name;
}
/**
* Helper function to get order statuses in correct order.
*
* Taken from commerce_order_handler_filter_order_status->get_value_options().
*/
function mailchimp_ecommerce_get_order_statuses() {
$order_statuses = array();
foreach (commerce_order_state_get_title() as $name => $title) {
foreach (commerce_order_statuses(array(
'state' => $name,
)) as $order_status) {
$order_statuses[$order_status['name']] = $order_status['title'];
}
}
return $order_statuses;
}
/**
* Helper function to get Mailchimp order status.
*
* @url http://developer.mailchimp.com/documentation/mailchimp/guides/getting-started-with-ecommerce/#order-notifications
*/
function mailchimp_ecommerce_get_mc_order_statuses($order_status) {
$mc_order_statuses = array(
'financial_status' => '',
'fulfillment_status' => '',
);
$order_statuses = mailchimp_ecommerce_get_order_statuses();
// Skip if empty.
if (empty($order_statuses)) {
return $mc_order_statuses;
}
foreach ($order_statuses as $key => $title) {
// Skip if not a match.
if ($key != $order_status) {
continue;
}
$order_notification_key_value = variable_get('mailchimp_ecommerce_order_notifications_' . $key, '');
// Skip if none.
if (empty($order_notification_key_value)) {
continue;
}
$order_notification_key_value = explode('__', $order_notification_key_value);
$order_notification_key = $order_notification_key_value[0];
$order_notification_value = $order_notification_key_value[1];
$mc_order_statuses[$order_notification_key] = $order_notification_value;
}
return $mc_order_statuses;
}
Functions
Name | Description |
---|---|
mailchimp_ecommerce_add_cart | Adds a new cart to the current Mailchimp store. |
mailchimp_ecommerce_add_cart_line | Adds a line to a cart in the current Mailchimp store. |
mailchimp_ecommerce_add_customer | Add a new customer to Mailchimp. |
mailchimp_ecommerce_add_order | Adds a new order to the current Mailchimp store. |
mailchimp_ecommerce_add_product | Adds a product to Mailchimp. |
mailchimp_ecommerce_add_store | Add a new store to Mailchimp. |
mailchimp_ecommerce_create_queue_item | Callback to create a queue item. |
mailchimp_ecommerce_cron_queue_info | Implements hook_queue_info(). |
mailchimp_ecommerce_delete_cart | Deletes a cart in the current Mailchimp store. |
mailchimp_ecommerce_delete_cart_line | Deletes a line in a cart in the current Mailchimp store. |
mailchimp_ecommerce_delete_customer | Delete a customer from Mailchimp. |
mailchimp_ecommerce_delete_order | Deletes an Order from the current Mailchimp store. |
mailchimp_ecommerce_delete_product | Deletes a product in Mailchimp. |
mailchimp_ecommerce_delete_product_variant | Deletes a product variant in Mailchimp. |
mailchimp_ecommerce_generate_store_id | Generates a unique ID used to identify a store integration to Mailchimp. |
mailchimp_ecommerce_get_campaign_id | Gets the campaign ID from the current user's session. |
mailchimp_ecommerce_get_cart | Gets a cart from the current Mailchimp store. |
mailchimp_ecommerce_get_currency_codes | Returns currency codes from the xml file. |
mailchimp_ecommerce_get_customer | Read a customer from Mailchimp. |
mailchimp_ecommerce_get_list_id | Get the List ID being used. |
mailchimp_ecommerce_get_mc_order_statuses | Helper function to get Mailchimp order status. |
mailchimp_ecommerce_get_node_type_name | Get the human readable name of a node type by the slug. |
mailchimp_ecommerce_get_order | Gets an order from the current Mailchimp store. |
mailchimp_ecommerce_get_order_statuses | Helper function to get order statuses in correct order. |
mailchimp_ecommerce_get_store | Return information about the store from the supplied id. |
mailchimp_ecommerce_get_store_id | Gets the store ID of the Mailchimp eCommerce integration. |
mailchimp_ecommerce_log_error_message | Logs an error message using watchdog, if enabled. |
mailchimp_ecommerce_menu | Implements hook_menu(). |
mailchimp_ecommerce_page_build | Implements hook_page_build(). |
mailchimp_ecommerce_queue_process | Worker function to process a Mailchimp eCommerce queue item. |
mailchimp_ecommerce_show_error | Helper function to show an error message for admin users. |
mailchimp_ecommerce_update_cart | Updates an existing cart in the current Mailchimp store. |
mailchimp_ecommerce_update_cart_line | Updates an existing line in a cart in the current Mailchimp store. |
mailchimp_ecommerce_update_customer | Update a customer record in Mailchimp. |
mailchimp_ecommerce_update_order | Updates an existing order in the current Mailchimp store. |
mailchimp_ecommerce_update_product | Updates an existing product in Mailchimp. |
mailchimp_ecommerce_update_store | Update a store name or currency code. |
mailchimp_ecommerce_use_queue | |
mailchimp_ecommerce_validate_customer | Determines if customer data is valid. |
_mailchimp_ecommerce_get_local_customer | @inheritdoc |
_mailchimp_ecommerce_increment_order_total | Increment order totals |