--- old/commerce_civicrm/commerce_civicrm.module	2014-10-17 14:16:00.000000000 +0800
+++ commerce_civicrm/commerce_civicrm.module	2014-10-17 15:02:40.000000000 +0800
@@ -185,8 +185,10 @@ function commerce_civicrm_prefill_order_
   $form_state['commerce_order']->data['cid'] = $cid;
 
   // Get the CiviCRM Contact object.
-  $params = array('id' => $cid, 'version' => 3, 'sequential' => 0);
-  $result = civicrm_api('contact', 'get', $params);
+  $params = array(
+    'id' => $cid,
+  );
+  $result = civicrm_api3('contact', 'get', $params);
   $contact = $result['values'][$cid];
 
   // Set the order primary mail to the contacts email
@@ -252,7 +254,6 @@ function commerce_civicrm_display_contac
   return;
 }
 
-
 /**
  * Admin form configuration.
  */
@@ -260,25 +261,31 @@ function commerce_civicrm_admin() {
   if (!civicrm_initialize()) {
     return;
   }
-  require_once 'api/v2/Group.php';
   require_once 'CRM/Core/Config.php';
 
-  $params = array();
-  $groups = civicrm_group_get($params);
   $options = array();
-  foreach ($groups as $group) {
-    $options[$group['id']] = $group['title'];
-  }
-  natsort($options);
+  try {
+    // Get groups.
+    $params = array();
+    $result = civicrm_api3('Group', 'get', $params);
+    if ($result['values']) {
+      foreach ($result['values'] as $group) {
+        $options[$group['id']] = $group['title'];
+      }
+    }
 
-  // Get contribution types.
-  // Note, no {} on table name because it's in civicrm db.
-  $sql = "SELECT id, name FROM civicrm_contribution_type WHERE is_active = 1";
-  $dao =& CRM_Core_DAO::executeQuery($sql, array());
-  $types = array(0 => t('Select a type...'));
-  while ($dao->fetch()) {
-    $types[$dao->id] = $dao->name;
+    // Get contribution types.
+    $sql = 'SELECT id, name FROM civicrm_financial_type';
+    $dao =& CRM_Core_DAO::executeQuery($sql, array());
+    $types = array(0 => t('Select a type...'));
+    while ($dao->fetch()) {
+      $types[$dao->id] = $dao->name;
+    }
+  }
+  catch (Exception $e) {
+    drupal_set_message(t('CiviCRM API error: %message', array('%message' => $e->getMessage())), 'error');
   }
+  natsort($options);
 
   $form = array();
   $form['commerce_civicrm_contribution_type'] = array(
@@ -299,7 +306,6 @@ function commerce_civicrm_admin() {
   return system_settings_form($form);
 }
 
-
 /**
  * Called when the an order is created or changed. Creates a new order or
  * updates an existing one.
@@ -353,25 +359,31 @@ function _commerce_civicrm_get_mail_from
  *   CRM_Contact_BAO_Group object describing the contact to add
  */
 function _commerce_civicrm_add_to_groups($cid) {
-  require_once 'api/v2/GroupContact.php';
 
   $groups = variable_get('commerce_civicrm_groups', '');
   if (empty($groups)) {
     return;
   }
 
-  foreach ($groups as $id => $key) {
-    if ($key != 0) {
-      $params = array('contact_id' => $cid, 'group_id' => $key);
-      $result = civicrm_group_contact_add($params);
-      if (!empty($result['is_error'])) {
-        watchdog('commerce_civicrm', 'Error adding contact to group: %error', array('%error' => $result['error_message']), WATCHDOG_ERROR);
+  try {
+    foreach ($groups as $id => $key) {
+      if ($key != 0) {
+        $params = array(
+			'contact_id' => $cid, 
+			'group_id' => $key
+		);
+        $result = civicrm_api3('GroupContact', 'create', $params);
+        if (!empty($result['is_error'])) {
+          watchdog('commerce_civicrm', 'Error adding contact to group: %error', array('%error' => $result['error_message']), WATCHDOG_ERROR);
+        }
       }
     }
   }
+  catch (Exception $e) {
+     watchdog('commerce_civicrm', 'civicrm_contact_search(): %error', array('%error' => $e->getMessage()), WATCHDOG_ERROR);
+  }
 }
 
-
 /**
  * Get contact id for the customer.
  *
@@ -386,9 +398,6 @@ function _commerce_civicrm_get_cid($orde
     return;
   }
 
-  require_once 'CRM/Core/BAO/UFMatch.php';
-  require_once 'api/v2/Contact.php';
-
   // Order created from CiviCRM
   if (isset($order->data['cid'])) {
     return $order->data['cid'];
@@ -396,31 +405,38 @@ function _commerce_civicrm_get_cid($orde
 
   $mail = _commerce_civicrm_get_mail_from_order($order);
 
-  // Logged in user.
-  if ($order->uid) {
-    global $user;
-    $match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $order->uid,  $mail, 'Drupal', FALSE, 'Individual');
-    if (!is_object($match)) {
-      return FALSE;
-    }
-    return $match->contact_id;
-  }
-
-  // Anonymous user.
-  // Try to find a match based on email.
-  $contact_search_results = civicrm_api('contact', 'get', array(
-    'email' => $mail,
-    'version' => 3,
-    'return' => array(
-      'contact_id',
-      'contact_source',
-    )
-  ));
-  if (!empty($contact_search_results['is_error'])) {
-    watchdog('commerce_civicrm', 'civicrm_contact_search(): %error', array('%error' => $contact_search_results['error_message']), WATCHDOG_ERROR);
-    return FALSE;
+  try {
+    // Logged in user.
+    if ($order->uid) {
+      $params = array(
+        'uf_id' => $order->uid,
+      );
+	  $result = civicrm_api3('UFMatch', 'get', $params);
+      if (!empty($results['values'])) {
+         $match = reset($result['values']);
+         return $match['contact_id'];
+      }
+    }
+
+    // Anonymous user.
+    // Look in the CiviCRM contacts table for a contact that matches the primary email.
+	$params = array(
+      'email' => $order->mail,
+      'return.contact_id' => TRUE
+	);
+    $result = civicrm_api3('Contact', 'get', $params);
+    if (!empty($result['values'])) {
+      $match = reset($result['values']);
+      return $match['contact_id'];
+    }
+  }
+  catch (Exception $e) {
+    watchdog('commerce_civicrm', 'civicrm_contact_search(): %error', array('%error' => $e->getMessage()), WATCHDOG_ERROR);
   }
+  return 0;
 
+/*
+	// may be needed for results from email
   switch (count($contact_search_results['values'])) {
     case 0:
       return 0;
@@ -434,6 +450,7 @@ function _commerce_civicrm_get_cid($orde
       }
       return 0;
   }
+  */
 }
 
 
@@ -443,62 +460,72 @@ function _commerce_civicrm_get_cid($orde
  * @params $order Drupal order object
  */
 function _commerce_civicrm_update_contact($cid, $order) {
-  if (!civicrm_initialize()) {
-    return;
-  }
-
-  // Needed for civicrm_location_update
-  require_once 'api/v2/Location.php';
-
-  // Ensure we have a contact
-  if (!$cid) {
-    return;
-  }
-
-  // Get the contact object from the contact id
-  $result = civicrm_api('contact', 'get', array('id' => $cid, 'version' => 3, 'sequential' => 0));
-  $contact = $result['values'][$result['id']];
+  try {
+    if (!civicrm_initialize()) {
+      return;
+    }
+  
+    // Ensure we have a contact
+    if (!$cid) {
+      throw(new ErrorException('Contact id required to update contact.'));
+    }
+  
+    // Get the contact object from the contact id
+	$params = array(
+		'id' => $cid,
+	);
+    $result = civicrm_api3('contact', 'get', $params);
+    $contact = $result['values'][$result['id']];
+  
+    // Get customer profile information.
+    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
+    $billing_profile = $order_wrapper->commerce_customer_billing->value();
+    $billing_profile_wrapper = entity_metadata_wrapper('commerce_customer_profile', $billing_profile);
+    $billing_address = $billing_profile_wrapper->commerce_customer_address->value();
+  
+    // If we have a full name field, split it.
+    if (!empty($billing_address['name_line'])) {
+      $contact['display_name'] = $billing_address['name_line'];
+      // Assumes user only has one first name and one surname... not ideal.
+      $names = preg_split('/\s+/', $billing_address['name_line'], 2);
+      $first_name = $names[0];
+      $last_name = !empty($names[1]) ? $names[1] : '';
+    }
+    // Otherwise just pull out the first and last names.
+    else {
+      $first_name = $billing_address['first_name'];
+      $last_name = $billing_address['last_name'];
+      $contact['display_name'] = $first_name .' '. $last_name;
+    }
+  
+    // Prepare array to update contact via Civi API.
+    $contact['last_name'] = $last_name;
+    $contact['first_name'] = $first_name;
+    $contact['sort_name'] = "{$last_name}, {$first_name}";
+    $contact['display_name'] = $billing_address['first_name'] . ' ' . $billing_address['last_name'];
+    $contact['email'] = _commerce_civicrm_get_mail_from_order($order);
+    if (empty($contact['source'])) {
+      $contact['source'] = t('Drupal Commerce purchase');
+    }
+  
+    // Update the contact object
+    $result = civicrm_api3('contact', 'create', $contact);
+  
+    // Get location type. This could be configurable, but for now we'll
+    // presume 'Billing'.
+    $params = array(
+      'name' => 'Billing',
+    );
+    $result = civicrm_api3('LocationType', 'get', $params);
+    if (!empty($result['values'])) {
+      $location_type = reset($result['values']);
+      $location_type_id = $location_type['id'];
+    }
 
-  // Get customer profile information.
-  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
-  $billing_profile = $order_wrapper->commerce_customer_billing->value();
-  $billing_profile_wrapper = entity_metadata_wrapper('commerce_customer_profile', $billing_profile);
-  $billing_address = $billing_profile_wrapper->commerce_customer_address->value();
-
-  // If we have a full name field, split it.
-  if (!empty($billing_address['name_line'])) {
-    $contact['display_name'] = $billing_address['name_line'];
-    // Assumes user only has one first name and one surname... not ideal.
-    $names = preg_split('/\s+/', $billing_address['name_line'], 2);
-    $first_name = $names[0];
-    $last_name = !empty($names[1]) ? $names[1] : '';
-  }
-  // Otherwise just pull out the first and last names.
-  else {
-    $first_name = $billing_address['first_name'];
-    $last_name = $billing_address['last_name'];
-    $contact['display_name'] = $first_name .' '. $last_name;
-  }
-
-  // Prepare array to update contact via Civi API.
-  $contact['last_name'] = $last_name;
-  $contact['first_name'] = $first_name;
-  $contact['sort_name'] = "{$last_name}, {$first_name}";
-  $contact['display_name'] = $billing_address['first_name'] . ' ' . $billing_address['last_name'];
-  $contact['email'] = _commerce_civicrm_get_mail_from_order($order);
-  if (empty($contact['source'])) {
-    $contact['source'] = t('Drupal Commerce purchase');
-  }
-
-  // Update the contact object
-  $contact['version'] = 3;
-  $contact['sequential'] = 0;
-  $result = civicrm_api('contact', 'update', $contact);
-
-  // Billing location.
-  $address = array(
-    1 => array(
-      'location_type'          => 'Billing',
+    // Billing location.
+    $params = array(
+	  'contact_id'             => $cid,
+	  'location_type_id'       => $location_type_id,
       'is_primary'             => TRUE,
       'city'                   => $billing_address['locality'],
       'state_province'         => $billing_address['administrative_area'],
@@ -506,33 +533,38 @@ function _commerce_civicrm_update_contac
       'street_address'         => $billing_address['thoroughfare'],
       'supplemental_address_1' => $billing_address['premise'],
       'country'                => $billing_address['country'],
-    )
-  );
-
-  // TODO Phone @see hook_commerce_civicrm_params() for example.
-
-  // Add / update the location.
-  $params = array('version' => '3.0', 'contact_id' => $cid, 'address' => $address);
-
-  // Allow other modules to alter the data before being sent to CiviCRM.
-  foreach (module_implements('commerce_civicrm_params') as $module) {
-    $function = $module . '_commerce_civicrm_params';
-    $function($params, $order, $cid);
-  }
-
-  $new_location = civicrm_location_update($params);
-  if ($new_location['is_error'] && strpos($new_location['error_message'], "Invalid Location Type(s)") !== FALSE) {
-    $new_location = civicrm_location_add($params);
-  }
-
-  // Check if we have shipping information.
-  if ($shipping_profile = $order_wrapper->commerce_customer_shipping->value()) {
-    $shipping_profile_wrapper = entity_metadata_wrapper('commerce_customer_profile', $shipping_profile);
-    $shipping_address = $shipping_profile_wrapper->commerce_customer_address->value();
-
-    // Shipping location.
-    $address = array(
-      1 => array(
+    );
+     civicrm_api3('Address', 'create', $params);
+  
+    // TODO Phone @see hook_commerce_civicrm_params() for example.
+  
+    // Allow other modules to alter the data before being sent to CiviCRM.
+    foreach (module_implements('commerce_civicrm_params') as $module) {
+      $function = $module . '_commerce_civicrm_params';
+      $function($params, $order, $cid);
+    }
+  
+    // Check if we have shipping information.
+    if (!empty($order_wrapper->commerce_customer_shipping)) {
+      $shipping_profile = $order_wrapper->commerce_customer_shipping->value();
+      $shipping_profile_wrapper = entity_metadata_wrapper('commerce_customer_profile', $shipping_profile);
+      $shipping_address = $shipping_profile_wrapper->commerce_customer_address->value();
+
+      // Get location type. This could be configurable, but for now we'll
+      // presume 'Home'.
+      $params = array(
+        'name' => 'Home',
+      );
+      $result = civicrm_api3('LocationType', 'get', $params);
+      if (!empty($result['values'])) {
+        $location_type = reset($result['values']);
+        $location_type_id = $location_type['id'];
+      }
+  
+      // Shipping location.
+      $address = array(
+        'contact_id'             => $cid,
+        'location_type_id'       => $location_type_id,
         'location_type'          => 'Home',
         'is_primary'             => TRUE,
         'city'                   => $shipping_address['locality'],
@@ -541,20 +573,11 @@ function _commerce_civicrm_update_contac
         'street_address'         => $shipping_address['thoroughfare'],
         'supplemental_address_1' => $shipping_address['premise'],
         'country'                => $shipping_address['country'],
-      )
-    );
-
-    // Add / update the location.
-    $params = array('version' => '3.0', 'contact_id' => $cid, 'address' => $address);
-    $new_location = civicrm_location_update($params);
-    if ($new_location['is_error'] && strpos($new_location['error_message'], "Invalid Location Type(s) : Home") !== FALSE) {
-      $new_location = civicrm_location_add($params);
+      );
     }
   }
-
-  // Log the error, but continue.
-  if (civicrm_error($new_location)) {
-    watchdog('commerce_civicrm', 'civicrm_location_update(): %error', array('%error' => $new_location['error_message']), WATCHDOG_ERROR);
+  catch (Exception $e) {
+    watchdog('commerce_civicrm', 'civicrm_location_update(): %error', array('%error' => $e->getMessage()), WATCHDOG_ERROR);
   }
 }
 
@@ -568,50 +591,60 @@ function _commerce_civicrm_create_custom
     return;
   }
 
-  require_once 'CRM/Core/Config.php';
-  require_once 'api/v2/CustomGroup.php';
-
-  // First we need to check if the Sales Tax and Shipping custom fields have
-  // already been created.
-  $params = array(
-    'title'            => 'Drupal Commerce Purchases',
-    'name'             => 'commerce_purchases',
-    'extends'          => array('Contribution'),
-    'weight'           => 1,
-    'collapse_display' => 0,
-    'is_active'        => 1,
-  );
-  $custom_group = civicrm_custom_group_create($params);
-  variable_set('commerce_civicrm_contribution_group_id', $custom_group['id']);
-
-  $params = array(
-    'custom_group_id' => $custom_group['id'],
-    'label'           => 'Sales Tax',
-    'html_type'       => 'Text',
-    'data_type'       => 'String',
-    'weight'          => 1,
-    'is_required'     => 0,
-    'is_searchable'   => 0,
-    'is_active'       => 1,
-  );
-  $tax_field = civicrm_custom_field_create($params);
-  variable_set('commerce_civicrm_tax_field_id', $tax_field['result']['customFieldId']);
+  try {
+    // First we need to check if the Sales Tax and Shipping custom fields have
+    // already been created.
+    $params = array(
+      'title'            => 'Drupal Commerce Purchases',
+      'name'             => 'commerce_purchases',
+      'extends'          => array('Contribution'),
+      'weight'           => 1,
+      'collapse_display' => 0,
+      'is_active'        => 1,
+    );
+    $result = civicrm_api3('CustomGroup', 'create', $params);
+    if (!empty($result['values'])) {
+      $custom_group = reset($result['values']);
+      variable_set('commerce_civicrm_contribution_group_id', $custom_group['id']);
+
+      $params = array(
+        'custom_group_id' => $custom_group['id'],
+        'label'           => 'Sales Tax',
+        'html_type'       => 'Text',
+        'data_type'       => 'String',
+        'weight'          => 1,
+        'is_required'     => 0,
+        'is_searchable'   => 0,
+        'is_active'       => 1,
+      );
+      $result = civicrm_api3('CustomField', 'create', $params);
+      if (!empty($result['values'])) {
+        $tax_field = reset($result['values']);
+        variable_set('commerce_civicrm_tax_field_id', $tax_field['id']);
+      }
 
-  $params = array(
-    'custom_group_id' => $custom_group['id'],
-    'label'           => 'Shipping Cost',
-    'html_type'       => 'Text',
-    'data_type'       => 'String',
-    'weight'          => 2,
-    'is_required'     => 0,
-    'is_searchable'   => 0,
-    'is_active'       => 1,
-  );
-  $shipping_field = civicrm_custom_field_create($params);
-  variable_set('commerce_civicrm_shipping_field_id', $shipping_field['result']['customFieldId']);
+      $params = array(
+        'custom_group_id' => $custom_group['id'],
+        'label'           => 'Shipping Cost',
+        'html_type'       => 'Text',
+        'data_type'       => 'String',
+        'weight'          => 2,
+        'is_required'     => 0,
+        'is_searchable'   => 0,
+        'is_active'       => 1,
+      );
+      $result = civicrm_api3('CustomField', 'create', $params);
+      if (!empty($result['values'])) {
+        $shipping_field = reset($result['values']);
+        variable_set('commerce_civicrm_shipping_field_id', $shipping_field['id']);
+      }
+    }
+  }
+  catch (Exception $e) {
+    watchdog('commerce_civicrm', 'civicrm_location_update(): %error', array('%error' => $e->getMessage()), WATCHDOG_ERROR);
+  }
 }
 
-
 /**
  * Process transactions on an order.
  *
@@ -653,42 +686,42 @@ function _commerce_civicrm_add_contribut
   // TODO: figure out where to get the shipping total from.
   $shipping_total = 0 * $transaction->amount / $total;
 
-  $params = array(
-    'version' => 3,
-    'contact_id' => $cid,
-    'receive_date' => date('Y-m-d h:i:s'),
-    'total_amount' => $transaction->amount / 100,
-    'financial_type_id' => variable_get('commerce_civicrm_contribution_type', ''), // @FIXME this needs a sensible default
-    'payment_instrument_id' => _commerce_civicrm_map_payment_instrument($transaction->payment_method),
-    'non_deductible_amount' => 00.00,
-    'fee_amount' => 00.00,
-    'net_amount' => $transaction->amount / 100,
-    'trxn_id' => $transaction->transaction_id . '_dc',
-    'invoice_id' => $transaction->transaction_id . '_dc',
-    'source' => variable_get('commerce_civicrm_source_name', 'Drupal Commerce'),
-    'contribution_status_id' => _commerce_civicrm_map_contribution_status($transaction->status),
-    'note' => _commerce_civicrm_create_detail_string($order_wrapper),
-  );
-
-  if (!empty($tax_field_id)) {
-    $params['custom_' . $tax_field_id] = $transaction_tax;
-  }
-
-  if (!empty($shipping_field_id)) {
-    $params['custom_' . $shipping_field_id] = $shipping_total;
-  }
-
-  // Allow other modules to alter the contribution data before being sent to CiviCRM.
-  foreach (module_implements('commerce_civicrm_contribution_params') as $module) {
-    $function = $module . '_commerce_civicrm_contribution_params';
-    $function($params, $order, $cid, $transaction);
+  try {
+    $params = array(
+      'contact_id' => $cid,
+      'receive_date' => date('Y-m-d h:i:s'),
+      'total_amount' => $transaction->amount / 100,
+      'financial_type_id' => variable_get('commerce_civicrm_contribution_type', ''), // @FIXME this needs a sensible default
+      'payment_instrument_id' => _commerce_civicrm_map_payment_instrument($transaction->payment_method),
+      'non_deductible_amount' => 00.00,
+      'fee_amount' => 00.00,
+      'net_amount' => $transaction->amount / 100,
+      'trxn_id' => $transaction->transaction_id . '_dc',
+      'invoice_id' => $transaction->transaction_id . '_dc',
+      'source' => variable_get('commerce_civicrm_source_name', 'Drupal Commerce'),
+      'contribution_status_id' => _commerce_civicrm_map_contribution_status($transaction->status),
+      'note' => _commerce_civicrm_create_detail_string($order_wrapper),
+    );
+  
+    if (!empty($tax_field_id)) {
+      $params['custom_' . $tax_field_id] = $transaction_tax;
+    }
+  
+    if (!empty($shipping_field_id)) {
+      $params['custom_' . $shipping_field_id] = $shipping_total;
+    }
+  
+    // Allow other modules to alter the contribution data before being sent to CiviCRM.
+    foreach (module_implements('commerce_civicrm_contribution_params') as $module) {
+      $function = $module . '_commerce_civicrm_contribution_params';
+      $function($params, $order, $cid, $transaction);
+    }
+  
+    $contribution = civicrm_api3('Contribution', 'create', $params);
+  
   }
-
-  $contribution = civicrm_api('contribution', 'create', $params);
-
-  // Log any error.
-  if (civicrm_error($contribution)) {
-    watchdog('commerce_civicrm', 'civicrm_contribution_add(): %error', array('%error' => $contribution['error_message']), WATCHDOG_ERROR);
+  catch (Exception $e) {
+    watchdog('commerce_civicrm', 'CiviCRM API error: %error', array('%error' => $e->getMessage()), WATCHDOG_ERROR);
   }
 }
 
@@ -723,7 +756,6 @@ function _commerce_civicrm_map_payment_i
   return $id;
 }
 
-
 /**
  * Maps a Drupal Commerce order status to a corresponding CiviCRM contribution status.
  *
@@ -752,7 +784,6 @@ function _commerce_civicrm_map_contribut
   return $id;
 }
 
-
 /**
  * Create string to insert for purchase activity details.
  */
@@ -807,4 +838,3 @@ function _commerce_civicrm_count_custome
     ->fetchField();
   return $count;
 }
-
