-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDonationService.php
More file actions
1204 lines (1034 loc) · 51.2 KB
/
DonationService.php
File metadata and controls
1204 lines (1034 loc) · 51.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace MatchBot\Domain;
use Doctrine\DBAL\Exception\RetryableException;
use Doctrine\DBAL\Exception\ServerException as DBALServerException;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Exception\ORMException;
use GuzzleHttp\Exception\ClientException;
use MatchBot\Application\Actions\RegularGivingMandate\MandateCollectionRepeatedlyFailed;
use MatchBot\Application\Assertion;
use MatchBot\Application\Environment;
use MatchBot\Application\Matching\Adapter as MatchingAdapter;
use MatchBot\Application\Matching\Allocator;
use MatchBot\Application\Matching\DbErrorPreventedMatch;
use MatchBot\Application\Messenger\DonationUpserted;
use MatchBot\Application\Notifier\StripeChatterInterface;
use MatchBot\Client\NotFoundException;
use MatchBot\Client\Stripe;
use MatchBot\Application\HttpModels\DonationCreate;
use MatchBot\Domain\DomainException\CampaignNotOpen;
use MatchBot\Domain\DomainException\CharityAccountLacksNeededCapaiblities;
use MatchBot\Domain\DomainException\CouldNotCancelStripePaymentIntent;
use MatchBot\Domain\DomainException\CouldNotMakeStripePaymentIntent;
use MatchBot\Domain\DomainException\CouldNotRetrievePaymentMethod;
use MatchBot\Domain\DomainException\DomainRecordNotFoundException;
use MatchBot\Domain\DomainException\DonationAlreadyFinalised;
use MatchBot\Domain\DomainException\DonationCreateModelLoadFailure;
use MatchBot\Domain\DomainException\MandateNotActive;
use MatchBot\Domain\DomainException\NoDonorAccountException;
use MatchBot\Domain\DomainException\PaymentIntentNotSucceeded;
use MatchBot\Domain\DomainException\RegularGivingCollectionEndPassed;
use MatchBot\Domain\DomainException\RegularGivingDonationTooOldToCollect;
use MatchBot\Domain\DomainException\StripeAccountIdNotSetForAccount;
use MatchBot\Domain\DomainException\WrongCampaignType;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Ramsey\Uuid\UuidInterface;
use Random\Randomizer;
use Stripe\Card;
use Stripe\Charge;
use Stripe\ConfirmationToken;
use Stripe\Exception\ApiErrorException;
use Stripe\Exception\CardException;
use Stripe\Exception\InvalidRequestException;
use Stripe\PaymentIntent;
use Stripe\StripeObject;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\Lock\Exception\LockConflictedException;
use Symfony\Component\Messenger\RoutableMessageBus;
use Symfony\Component\Notifier\ChatterInterface;
use Symfony\Component\Notifier\Exception\TransportExceptionInterface;
use Symfony\Component\Notifier\Message\ChatMessage;
use Symfony\Component\RateLimiter\Exception\RateLimitExceededException;
use Symfony\Component\RateLimiter\RateLimiterFactory;
class DonationService
{
private const int MAX_RETRY_COUNT = 3;
/**
* Message excerpts that we expect to see sometimes from stripe on InvalidRequestExceptions. An exception
* containing any of these strings should not generate an alarm.
*/
public const array EXPECTED_STRIPE_INVALID_REQUEST_MESSAGES = [
'The provided PaymentMethod has failed authentication',
'You must collect the security code (CVC) for this card from the cardholder before you can use it',
// When a donation is cancelled we update it to cancelled in the DB, which stops it being confirmed later. But
// we can still get this error if the cancellation is too late to stop us attempting to confirm.
// phpcs:ignore
'This PaymentIntent\'s payment_method could not be updated because it has a status of canceled. You may only update the payment_method of a PaymentIntent with one of the following statuses: requires_payment_method, requires_confirmation, requires_action.',
'The confirmation token has already been used to confirm a previous PaymentIntent',
'This PaymentIntent\'s radar_options could not be updated because it has a status of canceled.',
'This PaymentIntent\'s amount could not be updated because it has a status of canceled.',
// phpcs:ignore
'The parameter application_fee_amount cannot be updated on a PaymentIntent after a capture has already been made.',
// people attempting to abuse the system may send donation confirmation requests with non-matching stripe customer IDs. We can't stop them, will just return an error to client:
'does not match the expected customer',
];
public const string STRIPE_DESTINATION_ACCOUNT_NEEDS_CAPABILITIES_MESSAGE = 'Your destination account needs to have at least one of the following capabilities enabled';
/**
* Previously donations were genereated from API requests in a separate class. That code has now been
* consolidated into this class, but this closure is retained to allow donations to be set for test scenarios.
* @var \Closure():Donation|null
*/
private ?\Closure $fakeDonationProviderForTestUseOnly = null;
public function __construct(
private Allocator $allocator,
private DonationRepository $donationRepository,
private CampaignRepository $campaignRepository,
private LoggerInterface $logger,
private EntityManagerInterface $entityManager,
private Stripe $stripe,
private MatchingAdapter $matchingAdapter,
private StripeChatterInterface|ChatterInterface $chatter,
private ClockInterface $clock,
private RateLimiterFactory $creationRateLimiterFactory,
private DonorAccountRepository $donorAccountRepository,
private RoutableMessageBus $bus,
private DonationNotifier $donationNotifier,
private FundRepository $fundRepository,
private \Redis $redis,
private RateLimiterFactory $confirmRateLimitFactory,
private RegularGivingNotifier $regularGivingNotifier,
) {
}
/**
* Creates a new pending ad-hoc donation.
*
* @param DonationCreate $donationData Details of the desired donation, as sent from the browser
* @param string $pspCustomerId The Stripe customer ID of the donor
* @param PersonId $donorId
*
* @throws CampaignNotOpen
* @throws CharityAccountLacksNeededCapaiblities
* @throws CouldNotMakeStripePaymentIntent
* @throws DBALServerException
* @throws DonationCreateModelLoadFailure
* @throws ORMException
* @throws StripeAccountIdNotSetForAccount
* @throws TransportExceptionInterface
* @throws RateLimitExceededException
* @throws WrongCampaignType
* @throws \MatchBot\Client\NotFoundException
* @throws DbErrorPreventedMatch
*/
public function createDonation(DonationCreate $donationData, string $pspCustomerId, PersonId $donorId): Donation
{
try {
return $this->doCreateDonation($pspCustomerId, $donationData, $donorId);
} catch (RetryableException $exception) {
/**
* See notes on {@see self::enrollNewDonation} for EM side effect details.
*/
$this->logger->warning("Error creating donation, will retry: " . $exception->getMessage());
return $this->doCreateDonation($pspCustomerId, $donationData, $donorId);
}
}
/**
* @param DonationCreate $donationData
* @return Donation
* @throws \UnexpectedValueException if inputs invalid, including projectId being unrecognised
* @throws NotFoundException
*/
public function buildFromAPIRequest(DonationCreate $donationData, PersonId $donorId): Donation
{
// can't work out why one test (testSuccessWithMatchedCampaignAndInitialCampaignDuplicateError)
// is failing if we don't pass useFake false here - the verison on develop seems to also return a
// donation object passed in from the test case on the second invocation.
if ($this->fakeDonationProviderForTestUseOnly) {
return $this->fakeDonationProviderForTestUseOnly->__invoke();
}
if (!in_array($donationData->psp, ['stripe'], true)) {
throw new \UnexpectedValueException(sprintf(
'PSP %s is invalid',
$donationData->psp,
));
}
$campaign = $this->campaignRepository->findOneBy(['salesforceId' => $donationData->projectId->value]);
if (!$campaign) {
// Fetch data for as-yet-unknown campaigns on-demand
$this->logger->info("Loading unknown campaign ID {$donationData->projectId} on-demand");
try {
$campaign = $this->campaignRepository->pullNewFromSf($donationData->projectId);
} catch (ClientException $exception) {
$this->logger->error("Pull error for campaign ID {$donationData->projectId}: {$exception->getMessage()}");
throw new \UnexpectedValueException('Campaign does not exist');
}
if ($this->clock->now() > new \DateTimeImmutable("Wed Apr 16 10:00:00 AM BST 2025")) {
$this->logger->warning("Unexpected individual campaign {$campaign->getSalesforceId()} pulled from SF - should have been prewarmed");
}
$this->fundRepository->pullForCampaign($campaign, $this->clock->now());
$this->entityManager->flush();
// Because this case of campaigns being set up individually is relatively rare,
// it is the one place outside of `UpdateCampaigns` where we clear the whole
// result cache. It's currently the only user-invoked or single item place where
// we do so.
$this->entityManager->getConfiguration()->getResultCache()?->clear();
}
if ($donationData->currencyCode !== $campaign->getCurrencyCode()) {
throw new \UnexpectedValueException(sprintf(
'Currency %s is invalid for campaign',
$donationData->currencyCode,
));
}
return Donation::fromApiModel($donationData, $campaign, $donorId);
}
/**
* @param \Closure $retryable The action to be executed and then retried if necessary
* @param string $actionName The name of the action, used in logs.
* @throws ORMException|DBALServerException if they're occurring when max retry count reached.
*/
private function runWithPossibleRetry(
\Closure $retryable,
string $actionName
): void {
$retryCount = 0;
while ($retryCount < self::MAX_RETRY_COUNT) {
try {
$retryable();
if ($retryCount > 0) {
$this->logger->error(
"$actionName SUCCEEDED after $retryCount retry - retry process is not useless. " .
"See MAT-388. See info logs for original exception"
);
}
return;
} catch (RetryableException $exception) {
$retryCount++;
$this->logger->info(
sprintf(
$actionName . ' error: %s. Retrying %d of %d.',
$exception->getMessage(),
$retryCount,
self::MAX_RETRY_COUNT,
)
);
$seconds = (new Randomizer())->getFloat(0.1, 1.1);
$this->clock->sleep($seconds);
if ($retryCount === self::MAX_RETRY_COUNT) {
$this->logger->error(
sprintf(
$actionName . ' error: %s. Giving up after %d retries.',
$exception->getMessage(),
self::MAX_RETRY_COUNT,
)
);
throw $exception;
}
}
}
}
/**
* Finalized a donation, instructing stripe to attempt to take payment immediately for a donor
* making an immediate, online donation.
*
* @param null|'on_session'|'off_session' $confirmationTokenSetupFutureUsage
* @throws ApiErrorException
* @throws RegularGivingDonationTooOldToCollect
* @throws PaymentIntentNotSucceeded
* @throws RateLimitExceededException
*/
public function confirmOnSessionDonation(
Donation $donation,
StripeConfirmationTokenId $tokenId,
?string $confirmationTokenSetupFutureUsage,
): \Stripe\PaymentIntent {
$confirmationToken = $this->stripe->retrieveConfirmationToken($tokenId);
/**
* phpstan is newly reporting a variable type issue here, hard to see at a glance exactly what the issue
* is as the type involved is rather complicated.
*
* @var StripeObject&object{
* card: null|object{country: string, brand: string, fingerprint: string},
* pay_by_bank: null|StripeObject
* } $paymentMethodPreview
*/
$paymentMethodPreview = $confirmationToken->payment_method_preview; // @phpstan-ignore varTag.type
$this->limitNewPaymentCardUsageRate($paymentMethodPreview, $donation);
$this->updateDonationFeesFromConfirmationToken($donation, $confirmationToken);
// We flush now to make sure the actual fees we're charging are recorded. If there's any DB error at this point
// we prefer to crash without collecting the donation over collecting the donation without a proper record
// or what we're charging.
$this->entityManager->flush();
$paymentIntentId = $donation->getTransactionId();
Assertion::notNull($paymentIntentId);
Assertion::false(
$donation->getDonationStatus() === DonationStatus::PreAuthorized,
'A pre-authed donation would not be on-session'
);
// following line has no mutation coverage but I think its fine to delete anyway given new assertion above.
$donation->checkPreAuthDateAllowsCollectionAt($this->clock->now());
$paymentIntent = $this->stripe->retrievePaymentIntent($paymentIntentId);
// Check if PaymentIntent has a payment_method of a different type
/** @var string|null $paymentMethodId */
$paymentMethodId = $paymentIntent->payment_method ?? null;
if ($paymentMethodId !== null) {
$paymentIntent = $this->updatePaymentMethodFromStripe(
donation: $donation,
paymentMethodId: $paymentMethodId,
paymentMethodPreview: $paymentMethodPreview,
paymentIntentId: $paymentIntentId,
paymentIntent: $paymentIntent
);
}
if ($confirmationTokenSetupFutureUsage === null && $paymentIntent->setup_future_usage !== null) {
$paymentIntentId = $this->replacePaymentIntent($donation, $paymentIntentId);
}
$updatedIntent = $this->stripe->confirmPaymentIntent(
$paymentIntentId, // May have changed just above, if setup_future_usage did.
[
'confirmation_token' => $tokenId->stripeConfirmationTokenId,
'return_url' => $donation->getReturnUrl(),
]
);
$this->throwIfUnsuccessful($updatedIntent);
return $updatedIntent;
}
/**
* Trigger collection of funds from a pre-authorized donation associated with a regular giving mandate.
*
* Where a charge fails ({@see PaymentIntentNotSucceeded}), emails the donor. They can typically amend payment
* details for a week to remedy it. If the charge fails after that week the mandate will be cancelled.
*
* Returns success or failure; won't throw when a card exception is new and remediation is still possible.
*
* @throws RegularGivingCollectionEndPassed|MandateNotActive|MandateCollectionRepeatedlyFailed
*/
#[\NoDiscard]
public function confirmPreAuthorized(Donation $donation): bool
{
$stripeAccountId = $donation->getPspCustomerId();
Assertion::notNull($stripeAccountId);
$donorAccount = $this->donorAccountRepository->findByStripeIdOrNull($stripeAccountId);
if ($donorAccount === null) {
throw new NoDonorAccountException("Donor account not found for donation $donation");
}
$mandate = $donation->getMandate();
\assert($mandate !== null);
$currentMandateStatus = $mandate->getStatus();
if ($currentMandateStatus !== MandateStatus::Active) {
throw new MandateNotActive(
"Not confirming donation as mandate is '{$currentMandateStatus->name}', not Active"
);
}
$donation->checkPreAuthDateAllowsCollectionAt($this->clock->now());
$campaign = $donation->getCampaign();
if ($campaign->regularGivingCollectionIsEndedAt($this->clock->now())) {
$collectionEnd = $campaign->getRegularGivingCollectionEnd();
Assertion::notNull($collectionEnd);
$donation->cancel();
$mandate->campaignEnded();
throw new RegularGivingCollectionEndPassed(
"Cannot confirm a donation now, " .
"regular giving collections for campaign {$campaign->getSalesforceId()} ended " .
"at {$collectionEnd->format('Y-m-d')}"
);
}
$paymentMethod = $donorAccount->getRegularGivingPaymentMethod();
if ($paymentMethod === null) {
throw new \MatchBot\Domain\NoRegularGivingPaymentMethod(
"Cannot confirm donation {$donation->getUuid()} for " .
"{$donorAccount->stripeCustomerId->stripeCustomerId}, no payment method"
);
}
try {
$this->confirmDonationWithSavedPaymentMethod(donation: $donation, paymentMethodId: $paymentMethod, offSession: true);
} catch (PaymentIntentNotSucceeded $exception) {
$this->regularGivingNotifier->notifyCollectionFailed($donation, $this->clock->now());
$this->logger->warning('PaymentIntentNotSucceeded for donation ' . $donation->getUuid()->toString() . ', will notify donor: ' . $exception->getMessage());
if ($donation->getPreAuthorizationDate() < $this->clock->now()->modify("-1 week")) {
throw new MandateCollectionRepeatedlyFailed();
}
return false;
}
return true;
}
/**
* Does multiple things required when a new donation is added to the system including:
* - Checking that the campaign is open
* - Allocating match funds to the donation
* - Creating Stripe Payment intent
*
* On retryable database errors, the passed `$donation` will be detached from the EM on the assumption that
* callers will use a new one. The exception is re-thrown when this happens.
*
* @param bool $attemptMatching Whether to use match funds. Match funds will be withdrawn based on
* availability or donation amount, which ever is smaller.
* @throws CampaignNotOpen
* @throws CharityAccountLacksNeededCapaiblities
* @throws CouldNotMakeStripePaymentIntent
* @throws DBALServerException
* @throws ORMException
* @throws StripeAccountIdNotSetForAccount
* @throws WrongCampaignType
* @throws NotFoundException
*/
public function enrollNewDonation(Donation $donation, bool $attemptMatching, bool $dispatchUpdateMessage = true): void
{
$campaign = $donation->getCampaign();
$campaign->checkIsReadyToAcceptDonation($donation, $this->clock->now());
// Handling txn ourselves because Doctrine closes EM on errors. We want to only remove the new Donation from
// tracking instead so that a retry can work.
$this->entityManager->beginTransaction();
// Must persist before Stripe work to have ID available. No retries at this level as it's cleaner to begin
// again with a fresh donation.
$this->entityManager->persist($donation);
$this->entityManager->flush();
if ($campaign->isMatched() && $attemptMatching) {
try {
$this->attemptFundingAllocation($donation);
} catch (RetryableException) { // here
$this->attemptFundingAllocation($donation);
}
}
// There's potential that funding withdrawls could be lost without the donor knowing, so we take a copy of the total
// here for them and we won't allow the donation to be confirmed if the total does not match the expectation later,
// e.g. in case of a front end bug that stops them seeing the notification that the withdrawls expired.
$donation->setExpectedMatchAmount($donation->getFundingWithdrawalTotalAsObject());
$this->entityManager->commit();
// Regular Giving enrolls donations with `DonationStatus::PreAuthorized`, which get Payment Intents later instead.
if ($donation->getPsp() === 'stripe' && $donation->getDonationStatus() === DonationStatus::Pending) {
$this->loadCampaignsStripeId($campaign);
$this->createAndAssociatePaymentIntent($donation);
}
if ($dispatchUpdateMessage) {
$this->bus->dispatch(DonationUpserted::fromDonationEnveloped($donation));
}
}
private function doUpdateDonationFees(
Donation $donation,
): void {
$updatedIntentData = [
// only setting things that may need to be updated at this point.
'metadata' => [
'stripeFeeRechargeGross' => $donation->getCharityFeeGross(),
'stripeFeeRechargeNet' => $donation->getCharityFee(),
'stripeFeeRechargeVat' => $donation->getCharityFeeVat(),
],
// See https://stripe.com/docs/connect/destination-charges#application-fee
// Update the fee amount in case the final charge was from
// e.g. a Non EU / Amex card where fees are varied.
'application_fee_amount' => $donation->getAmountToDeductFractional(),
// Note that `on_behalf_of` is set up on create and is *not allowed* on update.
];
$paymentIntentId = $donation->getTransactionId();
if ($paymentIntentId !== null) {
$this->stripe->updatePaymentIntent($paymentIntentId, $updatedIntentData);
}
}
private function updateDonationFeesFromConfirmationToken(
Donation $donation,
ConfirmationToken $confirmationToken
): void {
/**
* phpstan is newly reporting a variable type issue here, hard to see at a glance exactly what the issue
* is as the type involved is rather complicated.
* @var StripeObject&object{
* card: null|object{country: string, brand: string, fingerprint: string},
* pay_by_bank: null|StripeObject
* } $paymentMethodPreview
*/
$paymentMethodPreview = $confirmationToken->payment_method_preview; // @phpstan-ignore varTag.type
if ($paymentMethodPreview->card !== null) {
$cardBrand = CardBrand::fromNameOrNull($paymentMethodPreview->card->brand) ?? throw new \Exception('Missing card brand');
$cardCountry = Country::fromAlpha2OrNull($paymentMethodPreview->card->country) ?? throw new \Exception('Missing card country');
$this->logger->info(sprintf(
'Donation UUID %s has card brand %s and country %s',
$donation->getUuid(),
$cardBrand->value,
$cardCountry,
));
$donation->setPaymentCard(new PaymentCard($cardBrand, $cardCountry));
} else {
// if we had a ctoken at all we're not using Donation Funds so must be using Pay By Bank, which
// has no card / default fees.
\assert($paymentMethodPreview->pay_by_bank !== null);
$donation->setPaymentCard(null);
}
$this->doUpdateDonationFees(
donation: $donation,
);
}
/**
* Creates a payment intent at Stripe and records the PI ID against the donation.
* @throws RegularGivingDonationTooOldToCollect
*/
public function createAndAssociatePaymentIntent(Donation $donation): void
{
Assertion::same($donation->getPsp(), 'stripe');
$now = $this->clock->now();
$donation->checkPreAuthDateAllowsCollectionAt($now);
try {
$intent = $this->stripe->createPaymentIntent($donation->createStripePaymentIntentPayload());
} catch (ApiErrorException $exception) {
$message = $exception->getMessage();
$accountLacksCapabilities = str_contains(
$message,
self::STRIPE_DESTINATION_ACCOUNT_NEEDS_CAPABILITIES_MESSAGE
);
$failureMessage = sprintf(
'Stripe Payment Intent create error on %s, %s [%s]: %s. Charity: %s [%s].',
$donation->getUuid(),
$exception->getStripeCode() ?? 'unknown',
get_class($exception),
$message,
$donation->getCampaign()->getCharity()->getName(),
$donation->getCampaign()->getCharity()->getStripeAccountId() ?? 'unknown',
);
$level = $accountLacksCapabilities ? LogLevel::WARNING : LogLevel::ERROR;
$this->logger->log($level, $failureMessage);
if ($accountLacksCapabilities) {
$env = getenv('APP_ENV');
\assert(is_string($env));
$failureMessageWithContext = sprintf(
'[%s] %s',
$env,
$failureMessage,
);
$this->chatter->send(new ChatMessage($failureMessageWithContext));
throw new CharityAccountLacksNeededCapaiblities();
}
throw new CouldNotMakeStripePaymentIntent();
}
$donation->setTransactionId($intent->id);
// @todo-MAT-388: remove runWithPossibleRetry if we determine its not useful and unwrap body of function below
$this->runWithPossibleRetry(
function () use ($donation) {
$this->entityManager->persist($donation);
$this->entityManager->flush();
},
'Donation Create persist after stripe work'
);
}
/**
* Sets donation to cancelled in matchbot db, releases match funds, cancels payment in stripe, and updates
* salesforce.
*
* Call this from inside a transaction and with a locked donation to avoid double releasing funds associated with
* the donation.
* @throws CouldNotCancelStripePaymentIntent
* @throws DonationAlreadyFinalised
*/
public function cancel(Donation $donation): void
{
if ($donation->getDonationStatus() === DonationStatus::Cancelled) {
$this->logger->info("Donation ID {$donation->getUuid()} was already Cancelled");
return;
}
if ($donation->getDonationStatus()->isSuccessful()) {
// If a donor uses browser back before loading the thank you page, it is possible for them to get
// a Cancel dialog and send a cancellation attempt to this endpoint after finishing the donation.
throw new DonationAlreadyFinalised(
"Donation ID {$donation->getUuid()} could not be cancelled as {$donation->getDonationStatus()->value}"
);
}
$this->logger->info("Cancelled donation UUID {$donation->getUuid()}");
$donation->cancel();
// Save & flush early to reduce chance of lock conflicts.
$this->save($donation);
if ($donation->getCampaign()->isMatched()) {
$this->allocator->releaseMatchFunds($donation);
}
$transactionId = $donation->getTransactionId();
if ($donation->getPsp() === 'stripe' && $transactionId !== null) {
try {
$this->stripe->cancelPaymentIntent($transactionId);
} catch (ApiErrorException $exception) {
/**
* As per the notes in {@see Allocator::releaseMatchFunds()}, we
* occasionally see double-cancels from the frontend. If Stripe tell us the
* Cancelled Donation's PI is canceled [note US spelling doesn't match our internal
* status], in all CC21 checks this seemed to be the situation.
*
* Instead of panicking in this scenario, our best available option is to log only a
* notice – we can still easily find these in the logs on-demand if we need to
* investigate proactively – and return 200 OK to the frontend.
*/
$doubleCancelMessage = 'You cannot cancel this PaymentIntent because it has a status of canceled.';
$returnError = !str_starts_with($exception->getMessage(), $doubleCancelMessage);
$stripeErrorLogLevel = $returnError ? LogLevel::ERROR : LogLevel::NOTICE;
// We use the same log message, but reduce the severity in the case where we have detected
// that it's unlikely to be a serious issue.
$this->logger->log(
$stripeErrorLogLevel,
'Stripe Payment Intent cancel error: ' .
get_class($exception) . ': ' . $exception->getMessage()
);
if ($returnError) {
throw new CouldNotCancelStripePaymentIntent(previous: $exception);
} // Else likely double-send -> fall through to normal return the donation as-is.
}
}
}
/**
* Save donation in all cases. Also send updated donation data to Salesforce, *if* we know
* enough to do so successfully.
*
* Assumes it will be called only after starting a transaction pre-donation-select.
*
* @param Donation $donation
*/
public function save(Donation $donation): void
{
// SF push and the corresponding DB persist only happens when names are already set.
// There could be other data we need to save before that point, e.g. comms
// preferences, so to be safe we persist here first.
$this->entityManager->persist($donation);
$this->entityManager->flush();
if (!$donation->hasEnoughDataForSalesforce()) {
return;
}
$this->bus->dispatch(DonationUpserted::fromDonationEnveloped($donation));
}
/**
* InvalidRequestException can have various possible messages. If it's one we've seen before that we don't believe
* indicates a bug or failure in matchbot then we just send an error message to the client. If it's something we
* haven't seen before or didn't expect then we will also generate an alarm for Big Give devs to deal with.
* @param InvalidRequestException $exception
* @return bool
*/
public static function errorMessageFromStripeIsExpected(InvalidRequestException $exception): bool
{
$exceptionMessage = $exception->getMessage();
foreach (DonationService::EXPECTED_STRIPE_INVALID_REQUEST_MESSAGES as $expectedMessage) {
if (str_contains($exceptionMessage, $expectedMessage)) {
return true;
}
}
return false;
}
/**
* Within a transaction, loads a donation from the DB and then releases any funding matched to it.
*
* If the matching for the donation has already been released (e.g. by another process after the donationId
* was found but before we lock the donation here) then this should be a no-op because Donation::fundingWithdrawals
* are eagerly loaded with the donation so will be empty.
*
* @throws LockConflictedException in case there is another process trying to deal with this donation right now,
* e.g. to confirm it.
*/
public function releaseMatchFundsInTransaction(UuidInterface $donationId): void
{
$this->entityManager->wrapInTransaction(function () use ($donationId) {
$donation = $this->donationRepository->findAndLockOneByUUID($donationId);
Assertion::notNull($donation);
$this->allocator->releaseMatchFunds($donation);
$this->entityManager->flush();
});
}
/**
* @return array<string, mixed>
*/
public function donationAsApiModel(UuidInterface $donationUUID): array
{
$donation = $this->donationRepository->findOneByUUID($donationUUID);
if (!$donation) {
throw new DomainRecordNotFoundException('Donation not found');
}
return $donation->toFrontEndApiModel();
}
/**
* @return list<array<string, mixed>>
*/
public function findAllCompleteForCustomerAsAPIModels(StripeCustomerId $stripeCustomerId): array
{
$donations = $this->donationRepository->findAllCompleteForCustomer($stripeCustomerId);
return array_map(fn(Donation $donation) => $donation->toFrontEndApiModel(), $donations);
}
/**
* @throws PaymentIntentNotSucceeded
* @throws CouldNotRetrievePaymentMethod
*/
public function confirmDonationWithSavedPaymentMethod(
Donation $donation,
StripePaymentMethodId $paymentMethodId,
bool $offSession,
): void {
$paymentIntentId = $donation->getTransactionId();
$this->updateDonationFeesFromPaymentMethodId($donation, $paymentMethodId);
// We flush now to make sure the actual fees we're charging are recorded. If there's any DB error at this point
// we prefer to crash without collecting the donation over collecting the donation without a proper record
// or what we're charging.
$this->entityManager->flush();
Assertion::notNull($paymentIntentId);
try {
$paymentIntent = $this->stripe->confirmPaymentIntent(
$paymentIntentId,
[
'payment_method' => $paymentMethodId->stripePaymentMethodId,
'return_url' => $donation->getReturnUrl(),
'off_session' => $offSession,
]
);
} catch (CardException $exception) {
$this->logger->info('CardException during confirmDonationWithSavedPaymentMethod: ' . $exception->getMessage());
$paymentIntent = $this->stripe->retrievePaymentIntent($paymentIntentId);
throw new PaymentIntentNotSucceeded($paymentIntent, "CardException: " . $exception->getMessage());
}
$this->logger->info("PaymentIntent: {$paymentIntent->toJSON()}");
if ($paymentIntent->status !== PaymentIntent::STATUS_SUCCEEDED) {
// @todo-regular-giving-mat-407: create a new db field on Donation - e.g. payment_attempt_count and update here
// decide on a limit and log an error (or warning) if exceeded & perhaps auto-cancel the donation and/or
// mandate.
throw new PaymentIntentNotSucceeded(
$paymentIntent,
"Payment Intent not succeded, status is {$paymentIntent->status}",
);
}
}
/**
* For use when we have confirmed a donation and need to update it synchronously before further processing -
* i.e. to know whether to go on to start a regular giving agreement if it was sucessful.
*/
public function queryStripeToUpdateDonationStatus(Donation $donation): void
{
$paymentIntentID = $donation->getTransactionId();
if ($paymentIntentID === null) {
return;
}
$paymentIntent = $this->stripe->retrievePaymentIntent($paymentIntentID);
if ($paymentIntent->status !== PaymentIntent::STATUS_SUCCEEDED) {
return;
}
$charge = $paymentIntent->latest_charge;
if ($charge === null) {
return;
}
$charge = $this->stripe->retrieveCharge((string) $charge);
if ($charge->status !== Charge::STATUS_SUCCEEDED) {
return;
}
$this->updateDonationStatusFromSuccessfulCharge($charge, $donation);
}
/**
* Sets donation status, if necessary, and also additional metadata after a charge. Expected to be called multiple
* times per donation safely, e.g. once with less info immediately upon charge.succeeded and later when there's
* additional info about original Stripe fees on charge.updated.
*/
public function updateDonationStatusFromSuccessfulCharge(Charge $charge, Donation $donation): void
{
$startingOriginalPspFee = $donation->getOriginalPspFee();
$uuid = $donation->getUuid()->toString();
$this->logger->info(sprintf('Updating donation %s with starting original fee %s', $uuid, $startingOriginalPspFee));
$this->logger->info('updating donation from charge: ' . $charge->toJSON());
$donationWasPreviouslyCollected = $donation->getDonationStatus() === DonationStatus::Collected;
/**
* @psalm-suppress MixedMethodCall
* @var array<string, mixed>|Card|null $card
*/
$card = $charge->payment_method_details?->toArray()['card'] ?? null;
if (is_array($card)) {
/** @var Card $card */
$card = (object)$card; // @phpstan-ignore varTag.nativeType
}
$cardBrand = CardBrand::fromNameOrNull($card?->brand);
$cardCountry = Country::fromAlpha2OrNull($card?->country);
$balanceTransaction = $charge->balance_transaction;
// as we didn't ask Stripe for a full B.T. object they will only give us the ID or null -- may be null
// for the original async charge success, and then populated later when we handle a charge updated event.
Assertion::nullOrString($balanceTransaction);
/** @var numeric-string|null $originalFeeFractional In pence or similar, if known */
$originalFeeFractional = null;
if (\is_string($balanceTransaction)) {
$originalFeeFractional = (string) $this->getOriginalFeeFractional(
$balanceTransaction,
$donation->currency()->isoCode(),
);
$this->logger->info(sprintf(
'Donation %s: Retrieved original PSP fee %s from balance transaction %s',
$uuid,
$originalFeeFractional,
$balanceTransaction,
));
} else {
// Before MAT-468 we (incorrectly) tried to pass `collectFromStripeCharge()` the earlier Original
// PSP Fee which is in pounds. Rather than convert twice and add more scope for bugs, we now leave it
// null if unknown and skip setting nulls.
$this->logger->info("Donation $uuid: Keeping starting/placeholder original PSP fee as no balance transaction ID yet");
}
$donation->collectFromStripeCharge(
chargeId: $charge->id,
totalPaidFractional: $charge->amount,
transferId: $charge->transfer ?? null,
cardBrand: $cardBrand,
cardCountry: $cardCountry,
originalFeeFractional: $originalFeeFractional,
chargeCreationTimestamp: $charge->created,
);
$showAccountExistsForEmail = $this->donorAccountRepository->accountExistsMatchingEmailWithDonation($donation);
if (!$donation->isRegularGiving() && !$donationWasPreviouslyCollected) {
// Regular giving donors get an email confirming the setup of the mandate, but not an email for
// each individual donation.
$this->donationNotifier->notifyDonorOfDonationSuccess(
donation: $donation,
sendRegisterUri: $this->shouldInviteRegistration($donation) && ! $showAccountExistsForEmail,
showAccountExistsForEmail: $showAccountExistsForEmail,
);
}
}
private function getOriginalFeeFractional(string $balanceTransactionId, string $expectedCurrencyCode): int
{
$txn = $this->stripe->retrieveBalanceTransaction($balanceTransactionId);
if (count($txn->fee_details) !== 1) {
$this->logger->warning(sprintf(
'StripeChargeUpdate::getFee: Unexpected composite fee with %d parts: %s',
count($txn->fee_details),
json_encode($txn->fee_details, \JSON_THROW_ON_ERROR),
));
}
/**
* See https://docs.stripe.com/api/balance_transactions/object#balance_transaction_object-fee_details
* @var object{currency: string, type: string} $feeDetail
* // @phpstan-ignore varTag.type
*/
$feeDetail = $txn->fee_details[0];
if ($feeDetail->currency !== strtolower($expectedCurrencyCode)) {
// `fee` should presumably still be in parent account's currency, so don't bail out.
$this->logger->warning(sprintf(
'StripeChargeUpdate::getFee: Unexpected fee currency %s',
$feeDetail->currency,
));
}
if ($feeDetail->type !== 'stripe_fee') {
$this->logger->warning(sprintf(
'StripeChargeUpdate::getFee: Unexpected type %s',
$feeDetail->type,
));
}
return $txn->fee;
}
public function attemptFundingAllocation(Donation $donation): void
{
try {
$this->allocator->allocateMatchFunds($donation);
} catch (\Throwable $throwable) {
$this->logger->info(sprintf('Releasing allocated funds after match error for UUID %s', $donation->getUuid()));
$this->matchingAdapter->releaseNewlyAllocatedFunds();
throw $throwable;
}
}
/**
* Checks that a campaign has a Stripe Account ID and if not attempts to find one in SF.
*
* @throws StripeAccountIdNotSetForAccount
* @todo consider if any of this method is required - or if we do or can ensure that Stripe Account ID is always
* set in matchbot before the donation is attempted.
*/
private function loadCampaignsStripeId(Campaign $campaign): void
{
$stripeAccountId = $campaign->getCharity()->getStripeAccountId();
if ($stripeAccountId === null || $stripeAccountId === '') {
// Try re-pulling in case charity has very recently onboarded with for Stripe.
$this->campaignRepository->updateFromSf($campaign);
// If still empty, error out
$stripeAccountId = $campaign->getCharity()->getStripeAccountId();
if ($stripeAccountId === null || $stripeAccountId === '') {
$this->logger->error(sprintf(
'Stripe Payment Intent create error: Stripe Account ID not set for Account %s',
$campaign->getCharity()->getSalesforceId(),
));
throw new StripeAccountIdNotSetForAccount();
}
}
}
private function shouldInviteRegistration(Donation $donation): bool
{
$donorId = $donation->getDonorId();
if (!$donorId) {
// must be an old donation
return false;
}
// In most cases if there is already a donor account then identity wouldn't have sent us a token so
// we wouldn't be able to invite registration here anway. But we need this check in case there is a recent
// token from just before the donor registered their account very recently.
// Identity sends key info for MB DonorAccount iff a password was set via \Messages\Person, so
// we can use record existence to decide whether to send a register link.
return $this->donorAccountRepository->findByPersonId($donorId) === null;
}
/**
* @param null|\Closure():Donation $fakeDonationProviderForTestUseOnly = null;
*/