StripeCustomer.php 9.86 KB
Newer Older
1 2 3 4 5 6 7
<?php

/**
 * Stripe Customer API
 *
 */

8 9
use CRM_Stripe_ExtensionUtil as E;

10
/**
11 12 13 14 15 16 17
 * StripeCustomer.Get API specification
 *
 * @param array $spec description of fields supported by this API call
 * @return void
 * @see http://wiki.civicrm.org/confluence/display/CRMDOC/API+Architecture+Standards
 */
function _civicrm_api3_stripe_customer_get_spec(&$spec) {
mattwire's avatar
mattwire committed
18 19
  $spec['customer_id']['title'] = ts("Stripe Customer ID");
  $spec['customer_id']['type'] = CRM_Utils_Type::T_STRING;
20 21 22 23 24 25 26 27
  $spec['contact_id']['title'] = ts("CiviCRM Contact ID");
  $spec['contact_id']['type'] = CRM_Utils_Type::T_INT;
  $spec['processor_id']['title'] = ts("Payment Processor ID");
  $spec['processor_id']['type'] = CRM_Utils_Type::T_INT;
}

/**
 * StripeCustomer.Get API
mattwire's avatar
mattwire committed
28
 *  This api will get a customer from the civicrm_stripe_customers table
29 30 31 32 33 34 35
 *
 * @param array $params
 * @see civicrm_api3_create_success
 *
 * @return array
 */
function civicrm_api3_stripe_customer_get($params) {
mattwire's avatar
mattwire committed
36
  $index = 1;
37 38
  foreach ($params as $key => $value) {
    switch ($key) {
mattwire's avatar
mattwire committed
39
      case 'customer_id':
40 41 42 43 44 45
        $where[$index] = "{$key}=%{$index}";
        $whereParam[$index] = [$value, 'String'];
        $index++;
        break;

      case 'contact_id':
46
      case 'processor_id':
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
        $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 = [
mattwire's avatar
mattwire committed
64
      'customer_id' => $dao->id,
65 66 67 68 69 70 71 72 73 74 75
      'contact_id' => $dao->contact_id,
      'processor_id' => $dao->processor_id,
    ];
    if ($dao->email) {
      $result['email'] = $dao->email;
    }
    $results[] = $result;
  }
  return civicrm_api3_create_success($results);
}

76
/**
77
 * StripeCustomer.delete API specification
78 79 80 81 82 83
 *
 * @param array $spec description of fields supported by this API call
 * @return void
 * @see http://wiki.civicrm.org/confluence/display/CRMDOC/API+Architecture+Standards
 */
function _civicrm_api3_stripe_customer_delete_spec(&$spec) {
mattwire's avatar
mattwire committed
84 85
  $spec['customer_id']['title'] = ts("Stripe Customer ID");
  $spec['customer_id']['type'] = CRM_Utils_Type::T_STRING;
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
  $spec['contact_id']['title'] = ts("CiviCRM Contact ID");
  $spec['contact_id']['type'] = CRM_Utils_Type::T_INT;
  $spec['processor_id']['title'] = ts("Payment Processor ID");
  $spec['processor_id']['type'] = CRM_Utils_Type::T_INT;
  $spec['processor_id']['api.required'] = TRUE;
}

/**
 * StripeCustomer.delete API
 *  This api will delete a stripe customer from CiviCRM
 *
 * @param array $params
 * @see civicrm_api3_create_success
 *
 * @throws \Civi\Payment\Exception\PaymentProcessorException
 * @return array
 */
function civicrm_api3_stripe_customer_delete($params) {
  CRM_Stripe_Customer::delete($params);
  return civicrm_api3_create_success([]);
}

108 109 110 111 112 113 114 115
/**
 * StripeCustomer.create API specification
 *
 * @param array $spec description of fields supported by this API call
 * @return void
 * @see http://wiki.civicrm.org/confluence/display/CRMDOC/API+Architecture+Standards
 */
function _civicrm_api3_stripe_customer_create_spec(&$spec) {
mattwire's avatar
mattwire committed
116 117 118
  $spec['customer_id']['title'] = ts("Stripe Customer ID");
  $spec['customer_id']['type'] = CRM_Utils_Type::T_STRING;
  $spec['customer_id']['api.required'] = TRUE;
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
  $spec['contact_id']['title'] = ts("CiviCRM Contact ID");
  $spec['contact_id']['type'] = CRM_Utils_Type::T_INT;
  $spec['contact_id']['api.required'] = TRUE;
  $spec['processor_id']['title'] = ts("Payment Processor ID");
  $spec['processor_id']['type'] = CRM_Utils_Type::T_INT;
  $spec['processor_id']['api.required'] = TRUE;
}

/**
 * StripeCustomer.create API
 *  This api will add a stripe customer to CiviCRM
 *
 * @param array $params
 * @see civicrm_api3_create_success
 *
 * @throws \Civi\Payment\Exception\PaymentProcessorException
 * @return array
 */
function civicrm_api3_stripe_customer_create($params) {
  CRM_Stripe_Customer::add($params);
  return civicrm_api3_create_success([]);
}


143 144
/**
 * Stripe.Customer.Updatecontactids API
145 146 147 148 149 150 151
 *  This api will update the civicrm_stripe_customers table and add contact IDs for all known email addresses
 *
 * @param array $params
 * @see civicrm_api3_create_success
 *
 * @return array
 */
152
function civicrm_api3_stripe_customer_updatecontactids($params) {
153
  $dao = CRM_Core_DAO::executeQuery('SELECT email, id FROM civicrm_stripe_customers WHERE contact_id IS NULL');
154 155 156 157 158
  $counts = [
    'updated' => 0,
    'failed' => 0,
  ];
  while ($dao->fetch()) {
159
    $contactId = NULL;
160 161 162 163 164
    try {
      $contactId = civicrm_api3('Contact', 'getvalue', [
        'return' => "id",
        'email' => $dao->email,
      ]);
165 166
    }
    catch (Exception $e) {
167 168 169 170 171 172 173
      // Most common problem is duplicates.
      if(preg_match("/Expected one Contact but found/", $e->getMessage())) {
        // If we find more than one, first try to find it via a related subscription record
        // using the customer id.
        $sql = "SELECT c.id
          FROM civicrm_contribution_recur rc
            JOIN civicrm_stripe_subscriptions sc ON
174
              rc.id = sc.contribution_recur_id
175 176 177
            JOIN civicrm_contact c ON c.id = rc.contact_id
          WHERE c.is_deleted = 0 AND customer_id = %0
          ORDER BY start_date DESC LIMIT 1";
178
        $dao_contribution = CRM_Core_DAO::executeQuery($sql, [0 => [$dao->id, 'String']]);
179 180 181 182 183 184 185 186 187 188 189 190
        $dao_contribution->fetch();
        if ($dao_contribution->id) {
          $contactId = $dao_contribution->id;
        }
        if (empty($contactId)) {
          // 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";
191
          $dao_contribution = CRM_Core_DAO::executeQuery($sql, [0 => [$dao->email, 'String']]);
192 193 194 195 196 197 198 199
          $dao_contribution->fetch();
          if ($dao_contribution->id) {
            $contactId = $dao_contribution->id;
          }
        }
      }
      if (empty($contactId)) {
        // Still no luck. Log it and move on.
200
        Civi::log()->debug('Stripe Upgrader: No contact ID found for stripe customer with email: ' . $dao->email);
201 202 203
        $counts['failed']++;
        continue;
      }
204
    }
205 206 207 208 209 210 211

    $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);
212
    $counts['updated']++;
213
  }
214

215 216
  return civicrm_api3_create_success($counts);
}
217 218

function _civicrm_api3_stripe_customer_updatestripemetadata_spec(&$spec) {
mattwire's avatar
mattwire committed
219 220 221 222
  $spec['customer_id']['title'] = E::ts("Stripe Customer ID");
  $spec['customer_id']['description'] = E::ts('If set only this customer will be updated, otherwise we try and update ALL customers');
  $spec['customer_id']['type'] = CRM_Utils_Type::T_STRING;
  $spec['customer_id']['api.required'] = FALSE;
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
  $spec['dryrun']['api.required'] = TRUE;
  $spec['dryrun']['type'] = CRM_Utils_Type::T_BOOLEAN;
  $spec['processor_id']['api.required'] = FALSE;
  $spec['processor_id']['type'] = CRM_Utils_Type::T_INT;
}

/**
 * This allows us to update the metadata held by stripe about our CiviCRM payments
 * Older versions of stripe extension did not set anything useful in stripe except email
 * Now we set a description including the name + metadata holding contact id.
 *
 * @param $params
 *
 * @return array
 * @throws \CiviCRM_API3_Exception
 * @throws \Civi\Payment\Exception\PaymentProcessorException
 */
function civicrm_api3_stripe_customer_updatestripemetadata($params) {
  if (!isset($params['dryrun'])) {
    throw new CiviCRM_API3_Exception('Missing required parameter dryrun');
  }
  // Check params
mattwire's avatar
mattwire committed
245
  if (empty($params['customer_id'])) {
246
    // We're doing an update on all stripe customers
247 248
    if (!isset($params['processor_id'])) {
      throw new CiviCRM_API3_Exception('Missing required parameters processor_id when using without a customer id');
249
    }
250
    $customerIds = CRM_Stripe_Customer::getAll($params['processor_id'], $params['options']);
251 252
  }
  else {
mattwire's avatar
mattwire committed
253
    $customerIds = [$params['customer_id']];
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
  }
  foreach ($customerIds as $customerId) {
    $customerParams = CRM_Stripe_Customer::getParamsForCustomerId($customerId);
    if (empty($customerParams['contact_id'])) {
      throw new CiviCRM_API3_Exception('Could not find contact ID for stripe customer: ' . $customerId);
    }

    $paymentProcessor = \Civi\Payment\System::singleton()
      ->getById($customerParams['processor_id']);
    $paymentProcessor->setAPIParams();

    // Get the stripe customer from stripe
    try {
      $stripeCustomer = \Stripe\Customer::retrieve($customerId);
    } catch (Exception $e) {
      $err = CRM_Core_Payment_Stripe::parseStripeException('retrieve_customer', $e, FALSE);
      $errorMessage = CRM_Core_Payment_Stripe::handleErrorNotification($err, NULL);
      throw new \Civi\Payment\Exception\PaymentProcessorException('Failed to retrieve Stripe Customer: ' . $errorMessage);
    }

    // Get the contact display name
    $contactDisplayName = civicrm_api3('Contact', 'getvalue', [
      'return' => 'display_name',
      'id' => $customerParams['contact_id'],
    ]);

    // Currently we set the description and metadata
    $stripeCustomerParams = [
      'description' => $contactDisplayName . ' (CiviCRM)',
      'metadata' => ['civicrm_contact_id' => $customerParams['contact_id']],
    ];

    // Update the stripe customer object at stripe
    if (!$params['dryrun']) {
      \Stripe\Customer::update($customerId, $stripeCustomerParams);
      $results[] = $stripeCustomerParams;
    }
    else {
      $results[] = $stripeCustomerParams;
    }
  }
  return civicrm_api3_create_success($results, $params);
}