Skip to content
Snippets Groups Projects
Commit ae2f052c authored by ayduns's avatar ayduns Committed by mattwire
Browse files

Replace direct sql to stripe_customers table with APIv4 calls

parent b6390142
Branches
Tags
1 merge request!2096.8
......@@ -36,15 +36,14 @@ class CRM_Stripe_Customer {
if (empty($params['contact_id'])) {
throw new PaymentProcessorException('Stripe Customer (find): contact_id is required');
}
$queryParams = [
1 => [$params['contact_id'], 'String'],
2 => [$params['processor_id'], 'Positive'],
];
$result = \Civi\Api4\StripeCustomer::get()
->addWhere('contact_id', '=', $params['contact_id'])
->addWhere('processor_id', '=', $params['processor_id'])
->addSelect('id')
->execute();
return CRM_Core_DAO::singleValueQuery("SELECT id
FROM civicrm_stripe_customers
WHERE contact_id = %1 AND processor_id = %2", $queryParams);
return $result->count() ? $result->first()['id'] : NULL;
}
/**
......@@ -55,18 +54,14 @@ class CRM_Stripe_Customer {
* @return array|null
*/
public static function getParamsForCustomerId($stripeCustomerId) {
$queryParams = [
1 => [$stripeCustomerId, 'String'],
];
$result = \Civi\Api4\StripeCustomer::get()
->addWhere('id', '=', $stripeCustomerId)
->addSelect('contact_id', 'processor_id')
->execute()
->first();
$dao = CRM_Core_DAO::executeQuery("SELECT contact_id, processor_id
FROM civicrm_stripe_customers
WHERE id = %1", $queryParams);
$dao->fetch();
return [
'contact_id' => $dao->contact_id,
'processor_id' => $dao->processor_id,
];
// Not sure whether this return for no match is needed, but that's what was being returned previously
return $result ? $result : ['contact_id' => NULL, 'processor_id' => NULL];
}
/**
......@@ -77,26 +72,10 @@ class CRM_Stripe_Customer {
* @return array|null
*/
public static function getAll($processorId, $options = []) {
$queryParams = [
1 => [$processorId, 'Integer'],
];
$limitClause = '';
if ($limit = CRM_Utils_Array::value('limit', $options)) {
$limitClause = "LIMIT $limit";
if ($offset = CRM_Utils_Array::value('offset', $options)) {
$limitClause .= " OFFSET $offset";
}
}
$customerIds = [];
$dao = CRM_Core_DAO::executeQuery("SELECT id
FROM civicrm_stripe_customers
WHERE processor_id = %1 {$limitClause}", $queryParams);
while ($dao->fetch()) {
$customerIds[] = $dao->id;
}
return $customerIds;
return civicrm_api4('StripeCustomer', 'get', [
'select' => ['id'],
'where' => [['processor_id', '=', $processorId]],
] + $options, ['id']);
}
/**
......@@ -107,6 +86,9 @@ class CRM_Stripe_Customer {
* @throws \Civi\Payment\Exception\PaymentProcessorException
*/
public static function add($params) {
// This should work, but fails because 'id' is a special param in DAOCreateAction
// return civicrm_api4('StripeCustomer', 'create', ['values' => $params]);
$requiredParams = ['contact_id', 'id', 'processor_id'];
foreach ($requiredParams as $required) {
if (empty($params[$required])) {
......@@ -211,7 +193,7 @@ class CRM_Stripe_Customer {
'name' => $contactDisplayName,
// Stripe does not include the Customer Name when exporting payments, just the customer
// description, so we stick the name in the description.
'description' => $contactDisplayName . ' (CiviCRM)',
'description' => $contactDisplayName . ' (CiviCRM)',
'email' => $params['email'] ?? '',
'metadata' => [
'CiviCRM Contact ID' => $params['contact_id'],
......@@ -244,39 +226,36 @@ class CRM_Stripe_Customer {
throw new PaymentProcessorException('Stripe Customer (delete): Missing required parameter: contact_id or id');
}
$delete = \Civi\Api4\StripeCustomer::delete()
->addWhere('processor_id', '=', $params['processor_id']);
if (!empty($params['id'])) {
$queryParams = [
1 => [$params['id'], 'String'],
2 => [$params['processor_id'], 'Integer'],
];
$sql = "DELETE FROM civicrm_stripe_customers
WHERE id = %1 AND processor_id = %2";
$delete = $delete->addWhere('id', '=', $params['id']);
}
else {
$queryParams = [
1 => [$params['contact_id'], 'String'],
2 => [$params['processor_id'], 'Integer'],
];
$sql = "DELETE FROM civicrm_stripe_customers
WHERE contact_id = %1 AND processor_id = %2";
$delete = $delete->addWhere('contact_id', '=', $params['contact_id']);
}
CRM_Core_DAO::executeQuery($sql, $queryParams);
$delete->execute();
}
/**
* Update the metadata at Stripe for a given contactid
*
* @param int $contactId
* @param int $processorId optional
* @return void
*/
public static function updateMetadataForContact(int $contactId): void {
public static function updateMetadataForContact(int $contactId, int $processorId = NULL): void {
$customers = \Civi\Api4\StripeCustomer::get()
->addWhere('contact_id', '=', $contactId)
->execute();
->addWhere('contact_id', '=', $contactId);
if ($processorId) {
$customers = $customers->addWhere('processor_id', '=', $processorId);
}
$customers = $customers->execute();
// Could be multiple customer_id's and/or stripe processors
foreach ($customers as $customer) {
$stripe = new CRM_Core_Payment_Stripe(null, $customer['processor_id']);
$stripe = new CRM_Core_Payment_Stripe(NULL, $customer['processor_id']);
CRM_Stripe_Customer::updateMetadata(
['contact_id' => $contactId, 'processor_id' => $customer['processor_id']],
$stripe,
......
......@@ -50,7 +50,7 @@ function civicrm_api3_stripe_importcustomers($params) {
'imported' => [],
'skipped' => [],
'errors' => [],
'continue_after' => NULL
'continue_after' => NULL,
];
// Get customers from Stripe
......@@ -68,43 +68,51 @@ function civicrm_api3_stripe_importcustomers($params) {
// Search the customers in CiviCRM
$customer_ids = array_map(
function ($customer) { return $customer->id; },
function ($customer) {
return $customer->id;
},
$customers_stripe->data
);
$customers_stripe_clean = $customers_stripe->data;
$escaped_customer_ids = CRM_Utils_Type::escapeAll($customer_ids, 'String');
$filter_item = array_map(
function ($customer_id) { return "'$customer_id'"; },
$escaped_customer_ids
);
// $escaped_customer_ids = CRM_Utils_Type::escapeAll($customer_ids, 'String');
// $filter_item = array_map(
// function ($customer_id) { return "'$customer_id'"; },
// $escaped_customer_ids
// );
if (count($customer_ids)) {
$customers_in_civicrm = \Civi\Api4\StripeCustomer::get()
->addSelect('*')
->addWhere('id', 'IN', $customer_ids)
->addWhere('contact_id', 'IS NOT NULL')
->execute()
->indexBy('id');
if (count($filter_item)) {
$select = "SELECT sc.*
FROM civicrm_stripe_customers AS sc
WHERE
sc.id IN (" . join(', ', $filter_item) . ") AND
sc.contact_id IS NOT NULL";
$dao = CRM_Core_DAO::executeQuery($select);
$customers_in_civicrm = $dao->fetchAll();
$customer_ids = array_map(
function ($customer) { return $customer['id']; },
$customers_in_civicrm
);
} else {
$customers_in_civicrm = $customer_ids = [];
// $select = "SELECT sc.*
// FROM civicrm_stripe_customers AS sc
// WHERE
// sc.id IN (" . join(', ', $filter_item) . ") AND
// sc.contact_id IS NOT NULL";
// $dao = CRM_Core_DAO::executeQuery($select);
// $customers_in_civicrm = $dao->fetchAll();
// $customer_ids = array_map(
// function ($customer) { return $customer['id']; },
// $customers_in_civicrm
// );
}
else {
$customers_in_civicrm = [];
}
foreach ($customers_stripe_clean as $customer) {
$results['continue_after'] = $customer->id;
// Return if contact was found
if (array_search($customer->id, $customer_ids) !== FALSE) {
$customer_in_civicrm = array_filter($customers_in_civicrm,
function ($record) use($customer) { return $record['id'] == $customer->id; }
);
if (isset($customers_in_civicrm[$customer->id])) {
$results['skipped'][] = [
'contact_id' => end($customer_in_civicrm)['contact_id'],
'contact_id' => $customers_in_civicrm[$customer->id]['contact_id'],
'email' => $customer->email,
'stripe_id' => $customer->id,
];
......
......@@ -42,41 +42,43 @@ function _civicrm_api3_stripe_customer_get_spec(&$spec) {
* @throws \CiviCRM_API3_Exception
*/
function civicrm_api3_stripe_customer_get($params) {
$index = 1;
foreach ($params as $key => $value) {
switch ($key) {
case 'id':
$where[$index] = "{$key}=%{$index}";
$whereParam[$index] = [$value, 'String'];
$index++;
break;
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params, TRUE, 'StripeCustomer');
case 'contact_id':
case 'processor_id':
$where[$index] = "{$key}=%{$index}";
$whereParam[$index] = [$value, 'Integer'];
$index++;
break;
// $index = 1;
// foreach ($params as $key => $value) {
// switch ($key) {
// case 'id':
// $where[$index] = "{$key}=%{$index}";
// $whereParam[$index] = [$value, 'String'];
// $index++;
// break;
}
}
// case 'contact_id':
// case 'processor_id':
// $where[$index] = "{$key}=%{$index}";
// $whereParam[$index] = [$value, 'Integer'];
// $index++;
// break;
$query = "SELECT * FROM civicrm_stripe_customers ";
if (count($where)) {
$whereClause = implode(' AND ', $where);
$query .= "WHERE {$whereClause}";
}
$dao = CRM_Core_DAO::executeQuery($query, $whereParam);
// }
// }
while ($dao->fetch()) {
$result = [
'id' => $dao->id,
'contact_id' => $dao->contact_id,
'processor_id' => $dao->processor_id,
];
$results[] = $result;
}
return civicrm_api3_create_success($results ?? []);
// $query = "SELECT * FROM civicrm_stripe_customers ";
// if (count($where)) {
// $whereClause = implode(' AND ', $where);
// $query .= "WHERE {$whereClause}";
// }
// $dao = CRM_Core_DAO::executeQuery($query, $whereParam);
// while ($dao->fetch()) {
// $result = [
// 'id' => $dao->id,
// 'contact_id' => $dao->contact_id,
// 'processor_id' => $dao->processor_id,
// ];
// $results[] = $result;
// }
// return civicrm_api3_create_success($results ?? []);
}
/**
......@@ -152,55 +154,56 @@ function civicrm_api3_stripe_customer_create($params) {
* @return array
* @throws \CiviCRM_API3_Exception
*/
function civicrm_api3_stripe_customer_updatecontactids($params) {
$dao = CRM_Core_DAO::executeQuery('SELECT email, id FROM civicrm_stripe_customers WHERE contact_id IS NULL');
$counts = [
'updated' => 0,
'failed' => 0,
];
while ($dao->fetch()) {
$contactId = NULL;
try {
$contactId = civicrm_api3('Contact', 'getvalue', [
'return' => "id",
'email' => $dao->email,
]);
}
catch (Exception $e) {
// Most common problem is duplicates.
if(preg_match("/Expected one Contact but found/", $e->getMessage())) {
// Still no luck. Now get desperate.
$sql = "SELECT c.id
FROM civicrm_contact c JOIN civicrm_email e ON c.id = e.contact_id
JOIN civicrm_contribution cc ON c.id = cc.contact_id
WHERE e.email = %0 AND c.is_deleted = 0 AND is_test = 0 AND
trxn_id LIKE 'ch_%' AND contribution_status_id = 1
ORDER BY receive_date DESC LIMIT 1";
$dao_contribution = CRM_Core_DAO::executeQuery($sql, [0 => [$dao->email, 'String']]);
$dao_contribution->fetch();
if ($dao_contribution->id) {
$contactId = $dao_contribution->id;
}
}
if (empty($contactId)) {
// Still no luck. Log it and move on.
Civi::log()->debug('Stripe Upgrader: No contact ID found for stripe customer with email: ' . $dao->email);
$counts['failed']++;
continue;
}
}
// Obsolete - email column has been dropped.
// function civicrm_api3_stripe_customer_updatecontactids($params) {
// $dao = CRM_Core_DAO::executeQuery('SELECT email, id FROM civicrm_stripe_customers WHERE contact_id IS NULL');
// $counts = [
// 'updated' => 0,
// 'failed' => 0,
// ];
// while ($dao->fetch()) {
// $contactId = NULL;
// try {
// $contactId = civicrm_api3('Contact', 'getvalue', [
// 'return' => "id",
// 'email' => $dao->email,
// ]);
// }
// catch (Exception $e) {
// // Most common problem is duplicates.
// if(preg_match("/Expected one Contact but found/", $e->getMessage())) {
// // Still no luck. Now get desperate.
// $sql = "SELECT c.id
// FROM civicrm_contact c JOIN civicrm_email e ON c.id = e.contact_id
// JOIN civicrm_contribution cc ON c.id = cc.contact_id
// WHERE e.email = %0 AND c.is_deleted = 0 AND is_test = 0 AND
// trxn_id LIKE 'ch_%' AND contribution_status_id = 1
// ORDER BY receive_date DESC LIMIT 1";
// $dao_contribution = CRM_Core_DAO::executeQuery($sql, [0 => [$dao->email, 'String']]);
// $dao_contribution->fetch();
// if ($dao_contribution->id) {
// $contactId = $dao_contribution->id;
// }
// }
// if (empty($contactId)) {
// // Still no luck. Log it and move on.
// Civi::log()->debug('Stripe Upgrader: No contact ID found for stripe customer with email: ' . $dao->email);
// $counts['failed']++;
// continue;
// }
// }
$sqlParams = [
1 => [$contactId, 'Integer'],
2 => [$dao->email, 'String'],
];
$sql = 'UPDATE civicrm_stripe_customers SET contact_id=%1 WHERE email=%2';
CRM_Core_DAO::executeQuery($sql, $sqlParams);
$counts['updated']++;
}
// $sqlParams = [
// 1 => [$contactId, 'Integer'],
// 2 => [$dao->email, 'String'],
// ];
// $sql = 'UPDATE civicrm_stripe_customers SET contact_id=%1 WHERE email=%2';
// CRM_Core_DAO::executeQuery($sql, $sqlParams);
// $counts['updated']++;
// }
return civicrm_api3_create_success($counts);
}
// return civicrm_api3_create_success($counts);
// }
/**
* @param array $spec
......@@ -255,7 +258,8 @@ function civicrm_api3_stripe_customer_updatestripemetadata($params) {
// Get the stripe customer from stripe
try {
$paymentProcessor->stripeClient->customers->retrieve($customerId);
} catch (Exception $e) {
}
catch (Exception $e) {
$err = CRM_Core_Payment_Stripe::parseStripeException('retrieve_customer', $e);
throw new PaymentProcessorException('Failed to retrieve Stripe Customer: ' . $err['code']);
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment