Stripe.php 37.7 KB
Newer Older
drastik's avatar
drastik committed
1
<?php
mattwire's avatar
mattwire committed
2
3
4
5
6
7
8
9
/*
 +--------------------------------------------------------------------+
 | Copyright CiviCRM LLC. All rights reserved.                        |
 |                                                                    |
 | This work is published under the GNU AGPLv3 license with some      |
 | permitted exceptions and without any warranty. For full license    |
 | and copyright information, see https://civicrm.org/licensing       |
 +--------------------------------------------------------------------+
drastik's avatar
drastik committed
10
 */
11

12
use CRM_Stripe_ExtensionUtil as E;
13
use Civi\Payment\PropertyBag;
14

mattwire's avatar
mattwire committed
15
16
17
/**
 * Class CRM_Core_Payment_Stripe
 */
drastik's avatar
drastik committed
18
class CRM_Core_Payment_Stripe extends CRM_Core_Payment {
19

20
  use CRM_Core_Payment_MJWTrait;
drastik's avatar
drastik committed
21
22
23
24

  /**
   * Constructor
   *
Joshua Walker's avatar
Joshua Walker committed
25
   * @param string $mode
26
   *   (deprecated) The mode of operation: live or test.
27
   * @param array $paymentProcessor
drastik's avatar
drastik committed
28
   */
29
  public function __construct($mode, $paymentProcessor) {
drastik's avatar
drastik committed
30
    $this->_paymentProcessor = $paymentProcessor;
31
    // @todo Remove once we drop support for CiviCRM < 5.27
32
    $this->_processorName = E::SHORT_NAME;
drastik's avatar
drastik committed
33
34
  }

mattwire's avatar
mattwire committed
35
36
37
38
39
40
  /**
   * @param array $paymentProcessor
   *
   * @return string
   */
  public static function getSecretKey($paymentProcessor) {
41
    return trim(CRM_Utils_Array::value('password', $paymentProcessor));
mattwire's avatar
mattwire committed
42
43
44
45
46
47
48
49
  }

  /**
   * @param array $paymentProcessor
   *
   * @return string
   */
  public static function getPublicKey($paymentProcessor) {
50
    return trim(CRM_Utils_Array::value('user_name', $paymentProcessor));
mattwire's avatar
mattwire committed
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
  }

  /**
   * Given a payment processor id, return the public key
   *
   * @param $paymentProcessorId
   *
   * @return string
   */
  public static function getPublicKeyById($paymentProcessorId) {
    try {
      $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', [
        'id' => $paymentProcessorId,
      ]);
      $key = self::getPublicKey($paymentProcessor);
    }
    catch (CiviCRM_API3_Exception $e) {
      return '';
    }
    return $key;
  }

  /**
   * Given a payment processor id, return the secret key
   *
   * @param $paymentProcessorId
   *
   * @return string
   */
  public static function getSecretKeyById($paymentProcessorId) {
    try {
      $paymentProcessor = civicrm_api3('PaymentProcessor', 'getsingle', [
        'id' => $paymentProcessorId,
      ]);
      $key = self::getSecretKey($paymentProcessor);
    }
    catch (CiviCRM_API3_Exception $e) {
      return '';
    }
    return $key;
  }

drastik's avatar
drastik committed
93
  /**
Joshua Walker's avatar
Joshua Walker committed
94
   * This function checks to see if we have the right config values.
drastik's avatar
drastik committed
95
   *
Matthew Wire's avatar
Matthew Wire committed
96
   * @return null|string
Joshua Walker's avatar
Joshua Walker committed
97
   *   The error message if any.
drastik's avatar
drastik committed
98
   */
99
  public function checkConfig() {
100
    $error = [];
drastik's avatar
drastik committed
101
102
103
104
105
106
107
108
109

    if (!empty($error)) {
      return implode('<p>', $error);
    }
    else {
      return NULL;
    }
  }

110
111
112
113
114
  /**
   * We can use the smartdebit processor on the backend
   * @return bool
   */
  public function supportsBackOffice() {
mattwire's avatar
mattwire committed
115
    return TRUE;
116
117
118
119
120
121
122
123
124
125
  }

  /**
   * We can edit smartdebit recurring contributions
   * @return bool
   */
  public function supportsEditRecurringContribution() {
    return FALSE;
  }

126
  public function supportsRecurring() {
127
    return TRUE;
128
129
  }

130
131
132
133
134
135
136
137
138
  /**
   * Does this payment processor support refund?
   *
   * @return bool
   */
  public function supportsRefund() {
    return TRUE;
  }

139
  /**
140
   * Can we set a future recur start date?  Stripe allows this but we don't (yet) support it.
141
142
143
144
145
146
   * @return bool
   */
  public function supportsFutureRecurStartDate() {
    return FALSE;
  }

147
148
149
150
151
152
153
154
155
  /**
   * Is an authorize-capture flow supported.
   *
   * @return bool
   */
  protected function supportsPreApproval() {
    return TRUE;
  }

mattwire's avatar
mattwire committed
156
157
158
159
160
161
162
163
164
165
166
167
  /**
   * Does this processor support cancelling recurring contributions through code.
   *
   * If the processor returns true it must be possible to take action from within CiviCRM
   * that will result in no further payments being processed.
   *
   * @return bool
   */
  protected function supportsCancelRecurring() {
    return TRUE;
  }

168
169
170
171
172
173
174
175
176
177
178
179
180
  /**
   * Does the processor support the user having a choice as to whether to cancel the recurring with the processor?
   *
   * If this returns TRUE then there will be an option to send a cancellation request in the cancellation form.
   *
   * This would normally be false for processors where CiviCRM maintains the schedule.
   *
   * @return bool
   */
  protected function supportsCancelRecurringNotifyOptional() {
    return FALSE;
  }

181
182
183
184
185
  /**
   * Get the currency for the transaction.
   *
   * Handle any inconsistency about how it is passed in here.
   *
186
   * @param array|PropertyBag $params
187
   *
188
   * @return string
189
   */
190
  public function getAmount($params = []): string {
191
    $amount = number_format((float) $params['amount'] ?? 0.0, CRM_Utils_Money::getCurrencyPrecision($this->getCurrency($params)), '.', '');
192
    // Stripe amount required in cents.
193
    $amount = preg_replace('/[^\d]/', '', strval($amount));
194
    return $amount;
195
196
  }

Joshua Walker's avatar
Joshua Walker committed
197
  /**
198
   * Set API parameters for Stripe (such as identifier, api version, api key)
199
   */
200
201
202
  public function setAPIParams() {
    // Set plugin info and API credentials.
    \Stripe\Stripe::setAppInfo('CiviCRM', CRM_Utils_System::version(), CRM_Utils_System::baseURL());
mattwire's avatar
mattwire committed
203
    \Stripe\Stripe::setApiKey(self::getSecretKey($this->_paymentProcessor));
204
    \Stripe\Stripe::setApiVersion(CRM_Stripe_Check::API_VERSION);
205
206
207
208
209
210
211
212
213
214
  }

  /**
   * Handle an error from Stripe API and notify the user
   *
   * @param array $err
   * @param string $bounceURL
   *
   * @return string errorMessage (or statusbounce if URL is specified)
   */
215
216
  public function handleErrorNotification($err, $bounceURL = NULL) {
    return self::handleError("{$err['type']} {$err['code']}", $err['message'], $bounceURL);
217
218
  }

219
220
221
222
223
224
225
226
  /**
   * Stripe exceptions contain a json object in the body "error". This function extracts and returns that as an array.
   * @param String $op
   * @param Exception $e
   * @param Boolean $log
   *
   * @return array $err
   */
227
228
  public static function parseStripeException($op, $e, $log = FALSE) {
    $body = $e->getJsonBody();
229
    if ($log) {
230
      Civi::log()->error("Stripe_Error {$op}: " . print_r($body, TRUE));
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
    }
    $err = $body['error'];
    if (!isset($err['code'])) {
      // A "fake" error code
      $err['code'] = 9000;
    }
    return $err;
  }

  /**
   * Create or update a Stripe Plan
   *
   * @param array $params
   * @param integer $amount
   *
   * @return \Stripe\Plan
   */
  public function createPlan($params, $amount) {
249
    $currency = $this->getCurrency($params);
250
    $planId = "every-{$params['recurFrequencyInterval']}-{$params['recurFrequencyUnit']}-{$amount}-" . strtolower($currency);
251

252
    if ($this->_paymentProcessor['is_test']) {
253
254
255
256
257
258
259
260
261
      $planId .= '-test';
    }

    // Try and retrieve existing plan from Stripe
    // If this fails, we'll create a new one
    try {
      $plan = \Stripe\Plan::retrieve($planId);
    }
    catch (Stripe\Error\InvalidRequest $e) {
262
      $err = self::parseStripeException('plan_retrieve', $e, FALSE);
263
264
      if ($err['code'] === 'resource_missing') {
        $formatted_amount = CRM_Utils_Money::formatLocaleNumericRoundedByCurrency(($amount / 100), $currency);
265
        $productName = "CiviCRM " . (isset($params['membership_name']) ? $params['membership_name'] . ' ' : '') . "every {$params['recurFrequencyInterval']} {$params['recurFrequencyUnit']}(s) {$currency}{$formatted_amount}";
266
        if ($this->_paymentProcessor['is_test']) {
267
268
          $productName .= '-test';
        }
269
        $product = \Stripe\Product::create([
270
271
          "name" => $productName,
          "type" => "service"
272
        ]);
273
        // Create a new Plan.
274
        $stripePlan = [
275
          'amount' => $amount,
276
          'interval' => $params['recurFrequencyUnit'],
277
278
279
          'product' => $product->id,
          'currency' => $currency,
          'id' => $planId,
280
          'interval_count' => $params['recurFrequencyInterval'],
281
        ];
282
283
284
285
286
287
        $plan = \Stripe\Plan::create($stripePlan);
      }
    }

    return $plan;
  }
Matthew Wire's avatar
Matthew Wire committed
288
289
  /**
   * Override CRM_Core_Payment function
Matthew Wire's avatar
Matthew Wire committed
290
291
   *
   * @return array
Matthew Wire's avatar
Matthew Wire committed
292
293
   */
  public function getPaymentFormFields() {
294
    return [];
Matthew Wire's avatar
Matthew Wire committed
295
296
297
298
299
300
301
302
303
304
305
  }

  /**
   * Return an array of all the details about the fields potentially required for payment fields.
   *
   * Only those determined by getPaymentFormFields will actually be assigned to the form
   *
   * @return array
   *   field metadata
   */
  public function getPaymentFormFieldsMetadata() {
306
    return [];
Matthew Wire's avatar
Matthew Wire committed
307
308
  }

309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
  /**
   * Get billing fields required for this processor.
   *
   * We apply the existing default of returning fields only for payment processor type 1. Processors can override to
   * alter.
   *
   * @param int $billingLocationID
   *
   * @return array
   */
  public function getBillingAddressFields($billingLocationID = NULL) {
    if ((boolean) \Civi::settings()->get('stripe_nobillingaddress')) {
      return [];
    }
    else {
      return parent::getBillingAddressFields($billingLocationID);
    }
  }

328
329
330
331
332
333
334
335
336
  /**
   * Get form metadata for billing address fields.
   *
   * @param int $billingLocationID
   *
   * @return array
   *    Array of metadata for address fields.
   */
  public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
337
338
    if ((boolean) \Civi::settings()->get('stripe_nobillingaddress')) {
      return [];
339
    }
340
341
342
343
344
345
346
347
    else {
      $metadata = parent::getBillingAddressFieldsMetadata($billingLocationID);
      if (!$billingLocationID) {
        // Note that although the billing id is passed around the forms the idea that it would be anything other than
        // the result of the function below doesn't seem to have eventuated.
        // So taking this as a param is possibly something to be removed in favour of the standard default.
        $billingLocationID = CRM_Core_BAO_LocationType::getBilling();
      }
348

349
350
351
352
353
354
355
356
357
      // Stripe does not require some of the billing fields but users may still choose to fill them in.
      $nonRequiredBillingFields = [
        "billing_state_province_id-{$billingLocationID}",
        "billing_postal_code-{$billingLocationID}"
      ];
      foreach ($nonRequiredBillingFields as $fieldName) {
        if (!empty($metadata[$fieldName]['is_required'])) {
          $metadata[$fieldName]['is_required'] = FALSE;
        }
358
      }
359

360
361
      return $metadata;
    }
362
363
  }

Peter Hartmann's avatar
Peter Hartmann committed
364
  /**
365
   * Set default values when loading the (payment) form
366
   *
367
   * @param \CRM_Core_Form $form
Peter Hartmann's avatar
Peter Hartmann committed
368
   */
369
  public function buildForm(&$form) {
370
    // Don't use \Civi::resources()->addScriptFile etc as they often don't work on AJAX loaded forms (eg. participant backend registration)
371
372
    $jsVars = [
      'id' => $form->_paymentProcessor['id'],
373
      'currency' => $this->getDefaultCurrencyForForm($form),
374
375
      'billingAddressID' => CRM_Core_BAO_LocationType::getBilling(),
      'publishableKey' => CRM_Core_Payment_Stripe::getPublicKeyById($form->_paymentProcessor['id']),
mattwire's avatar
mattwire committed
376
      'jsDebug' => (boolean) \Civi::settings()->get('stripe_jsdebug'),
377
      'paymentProcessorTypeID' => $form->_paymentProcessor['payment_processor_type_id'],
mattwire's avatar
mattwire committed
378
      'locale' => CRM_Core_I18n::getLocale(),
379
      'apiVersion' => CRM_Stripe_Check::API_VERSION,
380
      'csrfToken' => class_exists('\Civi\Firewall\Firewall') ? \Civi\Firewall\Firewall::getCSRFToken() : NULL,
mattwire's avatar
mattwire committed
381
      'country' => CRM_Core_BAO_Country::defaultContactCountry(),
382
    ];
mattwire's avatar
mattwire committed
383

mattwire's avatar
mattwire committed
384
    \Civi::resources()->addVars(E::SHORT_NAME, $jsVars);
385
386
    // Assign to smarty so we can add via Card.tpl for drupal webform because addVars doesn't work in that context
    $form->assign('stripeJSVars', $jsVars);
387

388
389
390
    // Enable JS validation for forms so we only (submit) create a paymentIntent when the form has all fields validated.
    $form->assign('isJsValidate', TRUE);

391
392
393
    // Add help and javascript
    CRM_Core_Region::instance('billing-block')->add(
      ['template' => 'CRM/Core/Payment/Stripe/Card.tpl', 'weight' => -1]);
394
    // Add CSS via region (it won't load on drupal webform if added via \Civi::resources()->addStyleFile)
mattwire's avatar
mattwire committed
395

396
    CRM_Core_Region::instance('billing-block')->add([
397
398
      'styleUrl' => \Civi::service('asset_builder')->getUrl(
        'elements.css',
mattwire's avatar
mattwire committed
399
400
401
402
        [
          'path' => \Civi::resources()->getPath(E::LONG_NAME, 'css/elements.css'),
          'mimetype' => 'text/css',
        ]
403
      ),
404
405
      'weight' => -1,
    ]);
406
    CRM_Core_Region::instance('billing-block')->add([
407
408
      'scriptUrl' => \Civi::service('asset_builder')->getUrl(
        'civicrmStripe.js',
mattwire's avatar
mattwire committed
409
410
411
412
        [
          'path' => \Civi::resources()->getPath(E::LONG_NAME, 'js/civicrm_stripe.js'),
          'mimetype' => 'application/javascript',
        ]
413
      )
414
    ]);
Peter Hartmann's avatar
Peter Hartmann committed
415
  }
416

417
418
419
420
421
422
423
424
425
426
427
428
429
  /**
   * Function to action pre-approval if supported
   *
   * @param array $params
   *   Parameters from the form
   *
   * This function returns an array which should contain
   *   - pre_approval_parameters (this will be stored on the calling form & available later)
   *   - redirect_url (if set the browser will be redirected to this.
   *
   * @return array
   */
  public function doPreApproval(&$params) {
430
431
432
    $preApprovalParams['paymentIntentID'] = CRM_Utils_Request::retrieve('paymentIntentID', 'String');
    $preApprovalParams['paymentMethodID'] = CRM_Utils_Request::retrieve('paymentMethodID', 'String');
    return ['pre_approval_parameters' => $preApprovalParams];
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
  }

  /**
   * Get any details that may be available to the payment processor due to an approval process having happened.
   *
   * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
   * result.
   *
   * @param array $storedDetails
   *
   * @return array
   */
  public function getPreApprovalDetails($storedDetails) {
    return $storedDetails;
  }

drastik's avatar
drastik committed
449
  /**
450
   * Process payment
drastik's avatar
drastik committed
451
452
   * Submit a payment using Stripe's PHP API:
   * https://stripe.com/docs/api?lang=php
453
   * Payment processors should set payment_status_id.
drastik's avatar
drastik committed
454
   *
455
   * @param array|PropertyBag $params
Joshua Walker's avatar
Joshua Walker committed
456
   *   Assoc array of input parameters for this transaction.
457
   * @param string $component
drastik's avatar
drastik committed
458
   *
459
460
461
   * @return array
   *   Result array
   *
462
463
   * @throws \CRM_Core_Exception
   * @throws \CiviCRM_API3_Exception
464
   * @throws \Civi\Payment\Exception\PaymentProcessorException
drastik's avatar
drastik committed
465
   */
466
  public function doPayment(&$params, $component = 'contribute') {
467
468
469
470
471
472
473
    /* @var \Civi\Payment\PropertyBag $paramsPb */
    $paramsPb = \Civi\Payment\PropertyBag::cast($params);
    $paramsPb = $this->beginDoPayment($paramsPb);

    if (($paramsPb->getIsRecur() && $this->getRecurringContributionId($params))
        || $this->isPaymentForEventAdditionalParticipants($paramsPb)) {
      $paramsPb = $this->getTokenParameter('paymentMethodID', $paramsPb, TRUE);
474
475
    }
    else {
476
      $paramsPb = $this->getTokenParameter('paymentIntentID', $paramsPb, TRUE);
477
    }
478

479
480
481
482
483
484
    // @todo From here on we are using the array instead of propertyBag. To be converted later...
    $params = $this->getPropertyBagAsArray($paramsPb);

    // We don't actually use this hook with Stripe, but useful to trigger so listeners can see raw params
    $newParams = [];
    CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $newParams);
drastik's avatar
drastik committed
485

486
    // Set our Stripe API parameters
487
488
    $this->setAPIParams();

489
    $amount = self::getAmount($params);
490
    $email = $this->getBillingEmail($params, $paramsPb->getContactID());
drastik's avatar
drastik committed
491

492
493
    // See if we already have a stripe customer
    $customerParams = [
494
      'contact_id' => $paramsPb->getContactID(),
495
496
      'processor_id' => $this->_paymentProcessor['id'],
      'email' => $email,
497
      // Include this to allow redirect within session on payment failure
498
      'error_url' => $params['error_url'],
499
    ];
500

501
502
503
504
    // Get the Stripe Customer:
    //   1. Look for an existing customer.
    //   2. If no customer (or a deleted customer found), create a new one.
    //   3. If existing customer found, update the metadata that Stripe holds for this customer.
505
    $stripeCustomerId = CRM_Stripe_Customer::find($customerParams);
506
    // Customer not in civicrm database.  Create a new Customer in Stripe.
507
    if (!isset($stripeCustomerId)) {
508
      $stripeCustomer = CRM_Stripe_Customer::create($customerParams, $this);
509
510
    }
    else {
511
      // Customer was found in civicrm database, fetch from Stripe.
512
513
      try {
        $stripeCustomer = \Stripe\Customer::retrieve($stripeCustomerId);
514
      } catch (Exception $e) {
515
        $err = self::parseStripeException('retrieve_customer', $e, FALSE);
516
        $errorMessage = $this->handleErrorNotification($err, $params['error_url']);
517
        throw new \Civi\Payment\Exception\PaymentProcessorException('Failed to retrieve Stripe Customer: ' . $errorMessage);
518
      }
mattwire's avatar
mattwire committed
519

520
      if ($stripeCustomer->isDeleted()) {
521
522
523
        // Customer doesn't exist, create a new one
        CRM_Stripe_Customer::delete($customerParams);
        try {
524
525
          $stripeCustomer = CRM_Stripe_Customer::create($customerParams, $this);
        } catch (Exception $e) {
526
          // We still failed to create a customer
527
          $errorMessage = $this->handleErrorNotification($stripeCustomer, $params['error_url']);
528
          throw new \Civi\Payment\Exception\PaymentProcessorException('Failed to create Stripe Customer: ' . $errorMessage);
529
530
        }
      }
531
532
533
      else {
        CRM_Stripe_Customer::updateMetadata($customerParams, $this, $stripeCustomer->id);
      }
drastik's avatar
drastik committed
534
535
    }

drastik's avatar
drastik committed
536
    // Prepare the charge array, minus Customer/Card details.
537
    if (empty($params['description'])) {
538
      $params['description'] = E::ts('Contribution: %1', [1 => $this->getPaymentProcessorLabel()]);
539
    }
540

541
    // Handle recurring payments in doRecurPayment().
542
    if ($paramsPb->getIsRecur() && $this->getRecurringContributionId($params)) {
543
544
      // We're processing a recurring payment - for recurring payments we first saved a paymentMethod via the browser js.
      // Now we use that paymentMethod to setup a stripe subscription and take the first payment.
545
546
547
548
549
550
551
552
      // This is where we save the customer card
      // @todo For a recurring payment we have to save the card. For a single payment we'd like to develop the
      //   save card functionality but should not save by default as the customer has not agreed.
      $paymentMethod = \Stripe\PaymentMethod::retrieve($params['paymentMethodID']);
      $paymentMethod->attach(['customer' => $stripeCustomer->id]);
      $stripeCustomer = \Stripe\Customer::retrieve($stripeCustomer->id);

      // We set payment status as pending because the IPN will set it as completed / failed
553
      $params['payment_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
554
555
      return $this->doRecurPayment($params, $amount, $stripeCustomer, $paymentMethod);
    }
556
    elseif ($this->isPaymentForEventAdditionalParticipants($paramsPb)) {
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
      // We're processing an event registration for multiple participants - because we did not know
      //   the amount until now we process via a saved paymentMethod.
      $paymentMethod = \Stripe\PaymentMethod::retrieve($params['paymentMethodID']);
      $paymentMethod->attach(['customer' => $stripeCustomer->id]);
      $stripeCustomer = \Stripe\Customer::retrieve($stripeCustomer->id);
      $intent = \Stripe\PaymentIntent::create([
        'payment_method' => $params['paymentMethodID'],
        'customer' => $stripeCustomer->id,
        'amount' => $amount,
        'currency' => $this->getCurrency($params),
        'confirmation_method' => 'automatic',
        'capture_method' => 'manual',
        // authorize the amount but don't take from card yet
        'setup_future_usage' => 'off_session',
        // Setup the card to be saved and used later
        'confirm' => true,
      ]);
      $params['paymentIntentID'] = $intent->id;
    }
576

577
578
    $intentParams = [
      'customer' => $stripeCustomer->id,
579
      'description' => $this->getDescription($params, 'description'),
580
    ];
581
582
    $intentParams['statement_descriptor_suffix'] = $this->getDescription($params, 'statement_descriptor_suffix');
    $intentParams['statement_descriptor'] = $this->getDescription($params, 'statement_descriptor');
583

584
    // This is where we actually charge the customer
585
    try {
mattwire's avatar
mattwire committed
586
      $intent = \Stripe\PaymentIntent::retrieve($params['paymentIntentID']);
587
      if ($intent->amount != $this->getAmount($params)) {
588
        $intentParams['amount'] = $this->getAmount($params);
589
      }
590
      $intent = \Stripe\PaymentIntent::update($intent->id, $intentParams);
drastik's avatar
drastik committed
591
    }
592
    catch (Exception $e) {
593
      $this->handleError($e->getCode(), $e->getMessage(), $params['error_url']);
drastik's avatar
drastik committed
594
    }
595

596
597
598
599
600
    list($params, $newParams) = $this->processPaymentIntent($params, $intent);

    // For a single charge there is no stripe invoice, we set OrderID to the ChargeID.
    if (empty($this->getPaymentProcessorOrderID())) {
      $this->setPaymentProcessorOrderID($this->getPaymentProcessorTrxnID());
601
602
    }

603
604
    // For contribution workflow we have a contributionId so we can set parameters directly.
    // For events/membership workflow we have to return the parameters and they might get set...
605
    return $this->endDoPayment($params, $newParams);
drastik's avatar
drastik committed
606
607
  }

608
  /**
609
610
   * @param \Civi\Payment\PropertyBag $params
   *
611
612
   * @return bool
   */
613
614
  private function isPaymentForEventAdditionalParticipants($params) {
    return !empty($params->getCustomProperty('additional_participants'));
615
616
  }

drastik's avatar
drastik committed
617
618
619
620
  /**
   * Submit a recurring payment using Stripe's PHP API:
   * https://stripe.com/docs/api?lang=php
   *
Joshua Walker's avatar
Joshua Walker committed
621
622
623
624
   * @param array $params
   *   Assoc array of input parameters for this transaction.
   * @param int $amount
   *   Transaction amount in USD cents.
625
   * @param \Stripe\Customer $stripeCustomer
Joshua Walker's avatar
Joshua Walker committed
626
   *   Stripe customer object generated by Stripe API.
627
   * @param \Stripe\PaymentMethod $stripePaymentMethod
drastik's avatar
drastik committed
628
   *
drastik's avatar
drastik committed
629
   * @return array
Joshua Walker's avatar
Joshua Walker committed
630
   *   The result in a nice formatted array (or an error object).
drastik's avatar
drastik committed
631
   *
Matthew Wire's avatar
Matthew Wire committed
632
   * @throws \CiviCRM_API3_Exception
633
   * @throws \CRM_Core_Exception
drastik's avatar
drastik committed
634
   */
635
  public function doRecurPayment($params, $amount, $stripeCustomer, $stripePaymentMethod) {
636
637
638
639
    $required = NULL;
    if (empty($this->getRecurringContributionId($params))) {
      $required = 'contributionRecurID';
    }
640
641
    if (!isset($params['recurFrequencyUnit'])) {
      $required = 'recurFrequencyUnit';
642
643
644
645
    }
    if ($required) {
      Civi::log()->error('Stripe doRecurPayment: Missing mandatory parameter: ' . $required);
      throw new CRM_Core_Exception('Stripe doRecurPayment: Missing mandatory parameter: ' . $required);
646
647
    }

648
649
    // Make sure recurFrequencyInterval is set (default to 1 if not)
    empty($params['recurFrequencyInterval']) ? $params['recurFrequencyInterval'] = 1 : NULL;
650

651
    // Create the stripe plan
652
    $planId = self::createPlan($params, $amount);
drastik's avatar
drastik committed
653

drastik's avatar
drastik committed
654
    // Attach the Subscription to the Stripe Customer.
655
    $subscriptionParams = [
656
      'prorate' => FALSE,
657
      'plan' => $planId,
658
      'default_payment_method' => $stripePaymentMethod,
659
660
      'metadata' => ['Description' => $params['description']],
      'expand' => ['latest_invoice.payment_intent'],
661
    ];
662

663
664
    // Create the stripe subscription for the customer
    $stripeSubscription = $stripeCustomer->subscriptions->create($subscriptionParams);
665
    $this->setPaymentProcessorSubscriptionID($stripeSubscription->id);
666
667

    $recurParams = [
668
      'id' =>     $this->getRecurringContributionId($params),
669
      'trxn_id' => $this->getPaymentProcessorSubscriptionID(),
670
671
      // FIXME processor_id is deprecated as it is not guaranteed to be unique, but currently (CiviCRM 5.9)
      //  it is required by cancelSubscription (where it is called subscription_id)
672
      'processor_id' => $this->getPaymentProcessorSubscriptionID(),
673
674
675
676
677
678
679
680
681
682
683
      'auto_renew' => 1,
      'cycle_day' => date('d'),
      'next_sched_contribution_date' => $this->calculateNextScheduledDate($params),
    ];
    if (!empty($params['installments'])) {
      // We set an end date if installments > 0
      if (empty($params['start_date'])) {
        $params['start_date'] = date('YmdHis');
      }
      if ($params['installments']) {
        $recurParams['end_date'] = $this->calculateEndDate($params);
684
        $recurParams['installments'] = $params['installments'];
685
686
      }
    }
687

688
689
690
691
    // Hook to allow modifying recurring contribution params
    CRM_Stripe_Hook::updateRecurringContribution($recurParams);
    // Update the recurring payment
    civicrm_api3('ContributionRecur', 'create', $recurParams);
692

693
694
695
696
697
    // Get the paymentIntent for the latest invoice
    $intent = $stripeSubscription->latest_invoice['payment_intent'];

    list($params, $newParams) = $this->processPaymentIntent($params, $intent);

698
699
    // Set the orderID (trxn_id) to the invoice ID
    // The IPN will change it to the charge_id
700
    $this->setPaymentProcessorOrderID($stripeSubscription->latest_invoice['id']);
701
702
703
704
705
706
707
708
709
710
711
712

    return $this->endDoPayment($params, $newParams);
  }

  /**
   * This performs the processing and recording of the paymentIntent for both recurring and non-recurring payments
   * @param array $params
   * @param \Stripe\PaymentIntent $intent
   *
   * @return array [$params, $newParams]
   */
  private function processPaymentIntent($params, $intent) {
713
    $contactId = $params['contactID'];
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
    $email = $this->getBillingEmail($params, $contactId);
    $newParams = [];

    try {
      if ($intent->status === 'requires_confirmation') {
        $intent->confirm();
      }

      switch ($intent->status) {
        case 'requires_capture':
          $intent->capture();
          // Return fees & net amount for Civi reporting.
          $stripeCharge = $intent->charges->data[0];
          try {
            $stripeBalanceTransaction = \Stripe\BalanceTransaction::retrieve($stripeCharge->balance_transaction);
          }
          catch (Exception $e) {
            $err = self::parseStripeException('retrieve_balance_transaction', $e, FALSE);
732
            $errorMessage = $this->handleErrorNotification($err, $params['error_url']);
733
734
            throw new \Civi\Payment\Exception\PaymentProcessorException('Failed to retrieve Stripe Balance Transaction: ' . $errorMessage);
          }
735
736
          if (($stripeCharge['currency'] !== $stripeBalanceTransaction->currency)
              && (!empty($stripeBalanceTransaction->exchange_rate))) {
737
            $newParams['fee_amount'] = CRM_Stripe_Api::currencyConversion($stripeBalanceTransaction->fee, $stripeBalanceTransaction['exchange_rate'], $stripeCharge['currency']);
738
739
          }
          else {
740
741
742
            // We must round to currency precision otherwise payments may fail because Contribute BAO saves but then
            // can't retrieve because it tries to use the full unrounded number when it only got saved with 2dp.
            $newParams['fee_amount'] = round($stripeBalanceTransaction->fee / 100, CRM_Utils_Money::getCurrencyPrecision($stripeCharge['currency']));
743
          }
744
745
          // Success!
          // Set the desired contribution status which will be set later (do not set on the contribution here!)
746
          $params['payment_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
747
748
749
750
751
752
753
754
755
756
757
758
759
760
          // Transaction ID is always stripe Charge ID.
          $this->setPaymentProcessorTrxnID($stripeCharge->id);

        case 'requires_action':
          // We fall through to this in requires_capture / requires_action so we always set a receipt_email
          if ((boolean) \Civi::settings()->get('stripe_oneoffreceipt')) {
            // Send a receipt from Stripe - we have to set the receipt_email after the charge has been captured,
            //   as the customer receives an email as soon as receipt_email is updated and would receive two if we updated before capture.
            \Stripe\PaymentIntent::update($intent->id, ['receipt_email' => $email]);
          }
          break;
      }
    }
    catch (Exception $e) {
761
      $this->handleError($e->getCode(), $e->getMessage(), $params['error_url']);
762
763
764
765
766
767
768
    }

    // Update the paymentIntent in the CiviCRM database for later tracking
    $intentParams = [
      'paymentintent_id' => $intent->id,
      'payment_processor_id' => $this->_paymentProcessor['id'],
      'status' => $intent->status,
769
      'contribution_id' => $params['contributionID'],
770
771
      'description' => $this->getDescription($params, 'description'),
      'identifier' => $params['qfKey'],
772
      'contact_id' => $params['contactID'],
773
774
775
776
777
778
779
    ];
    if (empty($intentParams['contribution_id'])) {
      $intentParams['flags'][] = 'NC';
    }
    CRM_Stripe_BAO_StripePaymentintent::create($intentParams);

    return [$params, $newParams];
780
781
  }

782
783
784
785
786
787
  /**
   * Submit a refund payment
   *
   * @param array $params
   *   Assoc array of input parameters for this transaction.
   *
788
   * @return array
789
790
   * @throws \Civi\Payment\Exception\PaymentProcessorException
   */
791
  public function doRefund(&$params) {
792
    $requiredParams = ['trxn_id', 'amount'];
793
794
795
796
797
798
799
800
    foreach ($requiredParams as $required) {
      if (!isset($params[$required])) {
        $message = 'Stripe doRefund: Missing mandatory parameter: ' . $required;
        Civi::log()->error($message);
        Throw new \Civi\Payment\Exception\PaymentProcessorException($message);
      }
    }
    $refundParams = [
801
      'charge' => $params['trxn_id'],
802
    ];
803
    $refundParams['amount'] = $this->getAmount($params);
804
805
806
807
808
809
810
    try {
      $refund = \Stripe\Refund::create($refundParams);
    }
    catch (Exception $e) {
      $this->handleError($e->getCode(), $e->getMessage());
      Throw new \Civi\Payment\Exception\PaymentProcessorException($e->getMessage());
    }
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835

    switch ($refund->status) {
      case 'pending':
        $refundStatus = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
        break;

      case 'succeeded':
        $refundStatus = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
        break;

      case 'failed':
        $refundStatus = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Failed');
        break;

      case 'canceled':
        $refundStatus = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Cancelled');
        break;
    }

    $refundParams = [
      'refund_trxn_id' => $refund->id,
      'refund_status_id' => $refundStatus,
      'processor_result' => $refund->jsonSerialize(),
    ];
    return $refundParams;
836
837
  }

838
839
840
841
842
843
844
845
846
847
  /**
   * Get a description field
   * @param array $params
   * @param string $type
   *   One of description, statement_descriptor, statement_descriptor_suffix
   *
   * @return string
   */
  private function getDescription($params, $type = 'description') {
    if (!isset(\Civi::$statics[__CLASS__]['description']['contact_contribution'])) {
848
      \Civi::$statics[__CLASS__]['description']['contact_contribution'] = $params['contactID'] . '-' . ($params['contributionID'] ?? 'XX');
849
850
851
852
853
854
855
856
857
858
859
860
861
    }
    switch ($type) {
      case 'statement_descriptor':
        return substr(\Civi::$statics[__CLASS__]['description']['contact_contribution'] . " " . $params['description'], 0, 22);

      case 'statement_descriptor_suffix':
        return \Civi::$statics[__CLASS__]['description']['contact_contribution'] . " " . substr($params['description'],0,7);

      default:
        return "{$params['description']} " . \Civi::$statics[__CLASS__]['description']['contact_contribution'] . " #" . CRM_Utils_Array::value('invoiceID', $params);
    }
  }

862
863
864
865
866
867
868
869
  /**
   * Calculate the end_date for a recurring contribution based on the number of installments
   * @param $params
   *
   * @return string
   * @throws \CRM_Core_Exception
   */
  public function calculateEndDate($params) {
870
    $requiredParams = ['start_date', 'installments', 'recurFrequencyInterval', 'recurFrequencyUnit'];
871
872
873
874
875
876
877
878
    foreach ($requiredParams as $required) {
      if (!isset($params[$required])) {
        $message = 'Stripe calculateEndDate: Missing mandatory parameter: ' . $required;
        Civi::log()->error($message);
        throw new CRM_Core_Exception($message);
      }
    }

879
    switch ($params['recurFrequencyUnit']) {
880
881
882
883
884
885
886
      case 'day':
        $frequencyUnit = 'D';
        break;

      case 'week':
        $frequencyUnit = 'W';
        break;
887

888
889
890
891
892
893
894
895
896
      case 'month':
        $frequencyUnit = 'M';
        break;

      case 'year':
        $frequencyUnit = 'Y';
        break;
    }

897
    $numberOfUnits = $params['installments'] * $params['recurFrequencyInterval'];
898
899
900
    $endDate = new DateTime($params['start_date']);
    $endDate->add(new DateInterval("P{$numberOfUnits}{$frequencyUnit}"));
    return $endDate->format('Ymd') . '235959';
drastik's avatar
drastik committed
901
902
903
  }

  /**
904
905
   * Calculate the end_date for a recurring contribution based on the number of installments
   * @param $params
drastik's avatar
drastik committed
906
   *
907
908
909
910
   * @return string
   * @throws \CRM_Core_Exception
   */
  public function calculateNextScheduledDate($params) {
911
    $requiredParams = ['recurFrequencyInterval', 'recurFrequencyUnit'];
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
    foreach ($requiredParams as $required) {
      if (!isset($params[$required])) {
        $message = 'Stripe calculateNextScheduledDate: Missing mandatory parameter: ' . $required;
        Civi::log()->error($message);
        throw new CRM_Core_Exception($message);
      }
    }
    if (empty($params['start_date']) && empty($params['next_sched_contribution_date'])) {
      $startDate = date('YmdHis');
    }
    elseif (!empty($params['next_sched_contribution_date'])) {
      if ($params['next_sched_contribution_date'] < date('YmdHis')) {
        $startDate = $params['next_sched_contribution_date'];
      }
    }
    else {
      $startDate = $params['start_date'];
    }

931
    switch ($params['recurFrequencyUnit']) {
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
      case 'day':
        $frequencyUnit = 'D';
        break;

      case 'week':
        $frequencyUnit = 'W';
        break;

      case 'month':
        $frequencyUnit = 'M';
        break;

      case 'year':
        $frequencyUnit = 'Y';
        break;
    }

949
    $numberOfUnits = $params['recurFrequencyInterval'];
950
951
952
953
954
    $endDate = new DateTime($startDate);
    $endDate->add(new DateInterval("P{$numberOfUnits}{$frequencyUnit}"));
    return $endDate->format('Ymd');
  }

mattwire's avatar
mattwire committed
955
956
957
958
959
960
961
962
963
964
  /**
   * Default payment instrument validation.
   *
   * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
   * Not a static function, because I need to check for payment_type.
   *
   * @param array $values
   * @param array $errors
   */
  public function validatePaymentInstrument($values, &$errors) {
965
966
    // Use $_POST here and not $values - for webform fields are not set in $values, but are in $_POST
    CRM_Core_Form::validateMandatoryFields($this->getMandatoryFields(), $_POST, $errors);
967
968
  }

969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
  /**
   * @param \Civi\Payment\PropertyBag $propertyBag
   *
   * @return array|null[]
   * @throws \Civi\Payment\Exception\PaymentProcessorException
   */
  public function doCancelRecurring(PropertyBag $propertyBag) {
    // By default we always notify Stripe and we don't give the user the option
    // because supportsCancelRecurringNotifyOptional() = FALSE
    if (!$propertyBag->has('isNotifyProcessorOnCancelRecur')) {
      // @fixme setIsNotifyProcessorOnCancelRecur was added in 5.27 - remove method_exists once minVer is 5.27
      // If isNotifyProcessorOnCancelRecur is NOT set then we set our default
      if (method_exists($propertyBag, 'setIsNotifyProcessorOnCancelRecur')) {
        $propertyBag->setIsNotifyProcessorOnCancelRecur(TRUE);
      }
    }
    return parent::doCancelRecurring($propertyBag);
  }

988
989
990
991
992
993
994
  /**
   * @param string $message
   * @param array $params
   *
   * @return bool|object
   */
  public function cancelSubscription(&$message = '', $params = []) {
995
996
997
998
999
    /* @var \Civi\Payment\PropertyBag $paramsPb */
    $paramsPb = \Civi\Payment\PropertyBag::cast($params);
    // @todo From here on we are using the array instead of propertyBag. To be converted later...
    $params = $this->getPropertyBagAsArray($paramsPb);

1000
1001
1002
    $this->setAPIParams();

    try {
1003
      $contributionRecur = civicrm_api3('ContributionRecur', 'getsingle', [
1004
        'id' => $this->getRecurringContributionId($params),
1005
      ]);
mattwire's avatar
mattwire committed
1006
    }
1007
1008
1009
1010
    catch (Exception $e) {
      return FALSE;
    }
    if (empty($contributionRecur['trxn_id'])) {
1011
      CRM_Core_Session::setStatus(E::ts('The recurring contribution cannot be cancelled (No reference (trxn_id) found).'), 'Smart Debit', 'error');
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
      return FALSE;
    }

    try {
      $subscription = \Stripe\Subscription::retrieve($contributionRecur['trxn_id']);
      if (!$subscription->isDeleted()) {
        $subscription->cancel();
      }
    }
    catch (Exception $e) {
      $errorMessage = 'Could not delete Stripe subscription: ' . $e->getMessage();
      CRM_Core_Session::setStatus($errorMessage, 'Stripe', 'error');
1024
      Civi::log()->error($errorMessage);
1025
1026
1027
1028
      return FALSE;
    }

    return TRUE;
mattwire's avatar
mattwire committed
1029
  }
1030

1031
  /**
1032
   * Process incoming payment notification (IPN).
Matthew Wire's avatar
Matthew Wire committed
1033
1034
   *
   * @throws \CRM_Core_Exception
1035
   * @throws \CiviCRM_API3_Exception
mattwire's avatar
mattwire committed
1036
   * @throws \Stripe\Error\Api
1037
   */
Matthew Wire's avatar
Matthew Wire committed
1038
  public static function handlePaymentNotification() {
1039
1040
1041
    $data_raw = file_get_contents("php://input");
    $data = json_decode($data_raw);
    $ipnClass = new CRM_Core_Payment_StripeIPN($data);
1042
1043
1044
    if ($ipnClass->main()) {
      http_response_code(200);
    }
1045
  }
1046

1047
1048
1049
1050
1051
  public function getText($context, $params) {
    $text = parent::getText($context, $params);

    switch ($context) {
      case 'cancelRecurDetailText':
1052
        $text .= ' <br/><strong>' . E::ts('Stripe will be automatically notified and the subscription will be cancelled.') . '</strong>';
1053
1054
1055
1056
    }
    return $text;
  }

1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
  /**
   * Get the error URL to "bounce" the user back to.
   * @param \Civi\Payment\PropertyBag $params
   *
   * @return string|null
   */
  public function getErrorUrl($params) {
    // Get proper entry URL for returning on error.
    if (!$params->has('qfKey')) {
      // Probably not called from a civicrm form (e.g. webform) -
      // will return error object to original api caller.
      $errorUrl = NULL;
    }
    else {
      $qfKey = $params->getCustomProperty('qfKey');
      $parsedUrl = parse_url($params->getCustomProperty('entryURL'));
      $urlPath = substr($parsedUrl['path'], 1);
      $query = $parsedUrl['query'];
      if (strpos($query, '_qf_Main_display=1') === FALSE) {
        $query .= '&_qf_Main_display=1';
      }
      if (strpos($query, 'qfKey=') === FALSE) {
        $query .= "&qfKey={$qfKey}";
      }
      $errorUrl = CRM_Utils_System::url($urlPath, $query, FALSE, NULL, FALSE);
    }
    return $errorUrl;
  }

1086
}