diff --git a/app/Models/Foundation/Summit/Factories/PaymentGatewayProfileFactory.php b/app/Models/Foundation/Summit/Factories/PaymentGatewayProfileFactory.php index d733545ba3..632d339fe3 100644 --- a/app/Models/Foundation/Summit/Factories/PaymentGatewayProfileFactory.php +++ b/app/Models/Foundation/Summit/Factories/PaymentGatewayProfileFactory.php @@ -29,19 +29,26 @@ final class PaymentGatewayProfileFactory public static function build(string $provider, array $params): ?PaymentGatewayProfile { Log::debug("PaymentGatewayProfileFactory::build()", ['provider' => $provider, 'params' => $params]); - $profile = null; - if ($provider == IPaymentConstants::ProviderStripe) { - $profile = static::populate(new StripePaymentProfile, $params); - } + return static::populate(static::create($provider), $params); + } - if ($provider == IPaymentConstants::ProviderLawPay) { - $profile = static::populate(new LawPayPaymentProfile, $params); - } + /** + * Returns an empty profile for the provider. Unlike build(), it never calls the payment + * gateway, so the caller can keep a reference to the profile before populate() creates + * any webhook. + * @param string $provider + * @return PaymentGatewayProfile + * @throws \models\exceptions\ValidationException + */ + public static function create(string $provider): PaymentGatewayProfile + { + if ($provider == IPaymentConstants::ProviderStripe) + return new StripePaymentProfile; - if(is_null($profile)) - throw new ValidationException("Profile type does not exists."); + if ($provider == IPaymentConstants::ProviderLawPay) + return new LawPayPaymentProfile; - return $profile; + throw new ValidationException("Profile type does not exists."); } /** diff --git a/app/Models/Foundation/Summit/Registration/Payment/PaymentGatewayProfile.php b/app/Models/Foundation/Summit/Registration/Payment/PaymentGatewayProfile.php index a1fad43078..e27ffd214c 100644 --- a/app/Models/Foundation/Summit/Registration/Payment/PaymentGatewayProfile.php +++ b/app/Models/Foundation/Summit/Registration/Payment/PaymentGatewayProfile.php @@ -328,6 +328,16 @@ public function setTestMode(): void abstract public function buildWebHook(): void; + /** + * Deletes at the payment gateway every webhook that this in-memory instance created itself. + * Called when the transaction meant to persist the profile fails: the DB rollback cannot + * undo a call to the gateway, and a webhook nobody stored would be left behind. + * Providers whose webhooks cannot be told apart per profile keep this no-op. + */ + public function discardCreatedWebHooks(): void + { + } + abstract protected function clearWebHooks():void; public function setExternalId(string $external_id): void{ diff --git a/app/Models/Foundation/Summit/Registration/Payment/StripePaymentProfile.php b/app/Models/Foundation/Summit/Registration/Payment/StripePaymentProfile.php index bbbc4a4c99..184dad1fde 100644 --- a/app/Models/Foundation/Summit/Registration/Payment/StripePaymentProfile.php +++ b/app/Models/Foundation/Summit/Registration/Payment/StripePaymentProfile.php @@ -58,6 +58,13 @@ class StripePaymentProfile extends PaymentGatewayProfile #[ORM\Column(name: 'SendEmailReceipt', type: 'boolean')] protected $send_email_receipt; + /** + * Webhooks this in-memory instance created at Stripe, so that discardCreatedWebHooks() can + * delete them again. Not mapped: it never outlives the request that created them. + * @var array + */ + private array $created_webhooks = []; + /** * StripePaymentProfile constructor. */ @@ -235,6 +242,7 @@ public function buildWebHook(): void ])); // and set web hook info $this->setWebHookInfo($info); + $this->created_webhooks[] = ['id' => $info['id'], 'test_mode' => (bool)$this->test_mode_enabled]; } } catch (\Exception $ex) { Log::error($ex); @@ -289,6 +297,27 @@ protected function clearLiveWebHook(): void } } + /** + * @inheritDoc + */ + public function discardCreatedWebHooks(): void + { + foreach ($this->created_webhooks as $webhook) { + $id = $webhook['id']; + try { + Log::warning(sprintf("StripePaymentProfile::discardCreatedWebHooks deleting webhook %s", $id)); + $config = $webhook['test_mode'] ? $this->createTestConfiguration() : $this->createLiveConfiguration(); + (new StripeApi($config))->deleteWebHookById($id); + if ($this->live_webhook_id === $id) $this->live_webhook_id = $this->live_webhook_secret_key = ''; + if ($this->test_webhook_id === $id) $this->test_webhook_id = $this->test_webhook_secret_key = ''; + } catch (\Exception $ex) { + // the profile is not stored, so nothing else will ever delete this webhook + Log::error(sprintf("StripePaymentProfile::discardCreatedWebHooks could not delete webhook %s: %s", $id, $ex->getMessage())); + } + } + $this->created_webhooks = []; + } + protected function clearWebHooks(): void { Log::debug("StripePaymentProfile::clearWebHooks"); diff --git a/app/Services/Model/Imp/PaymentGatewayProfileService.php b/app/Services/Model/Imp/PaymentGatewayProfileService.php index b8d8130946..0ed94dbc48 100644 --- a/app/Services/Model/Imp/PaymentGatewayProfileService.php +++ b/app/Services/Model/Imp/PaymentGatewayProfileService.php @@ -17,9 +17,11 @@ use Illuminate\Support\Facades\Log; use models\exceptions\EntityNotFoundException; use models\exceptions\ValidationException; +use models\summit\IPaymentConstants; use models\summit\PaymentGatewayProfile; use models\summit\PaymentGatewayProfileFactory; use models\summit\Summit; +use services\utils\AmbiguousCommitException; /** * Class PaymentGatewayProfileService @@ -35,24 +37,74 @@ final class PaymentGatewayProfileService */ public function addPaymentProfile(Summit $summit, array $payload): ?PaymentGatewayProfile { - return $this->tx_service->transaction(function () use ($summit, $payload) { - Log::debug("PaymentGatewayProfileService::addPaymentProfilee", ["summit" => $summit->getId(), 'payload' => $payload]); - $payload['summit'] = $summit; - $profile = PaymentGatewayProfileFactory::build($payload['provider'], $payload); - $formerProfile = $summit->getPaymentGateWayProfilePerApp($profile->getApplicationType()); - if ($profile->isActive() && !is_null($formerProfile) && $formerProfile->isActive()) { - throw new ValidationException - ( - sprintf("There is already an active Payment Profile for application type %s,", $formerProfile->getApplicationType()) - ); - } - $summit->addPaymentProfile($profile); - if (isset($payload['active']) && boolval($payload['active']) == true) { - // force activation ( rebuild web hook ) - $profile->activate(); + // Populating a profile can already create its webhook at the payment gateway, and a DB + // rollback cannot undo that. Every profile built here is tracked so that its webhooks can + // be deleted again when it does not end up stored: a failed transaction, an attempt that + // the root transaction re-ran after a transient DB error, or a returned profile that the + // transaction never inserted. + $built_profiles = []; + try { + $profile = $this->tx_service->transaction(function () use ($summit, $payload, &$built_profiles) { + Log::debug("PaymentGatewayProfileService::addPaymentProfilee", ["summit" => $summit->getId(), 'payload' => $payload]); + $is_active = isset($payload['active']) && boolval($payload['active']) == true; + // check before building the profile, so that a rejected one never reaches the gateway + if ($is_active) { + $formerProfile = $summit->getPaymentGateWayProfilePerApp + ( + $payload['application_type'] ?? IPaymentConstants::ApplicationTypeRegistration + ); + if (!is_null($formerProfile) && $formerProfile->isActive()) { + throw new ValidationException + ( + sprintf("There is already an active Payment Profile for application type %s,", $formerProfile->getApplicationType()) + ); + } + } + $payload['summit'] = $summit; + $profile = PaymentGatewayProfileFactory::create($payload['provider']); + $built_profiles[] = $profile; + PaymentGatewayProfileFactory::populate($profile, $payload); + $summit->addPaymentProfile($profile); + if ($is_active) { + // force activation ( rebuild web hook ) + $profile->activate(); + } + return $profile; + }); + } catch (AmbiguousCommitException $ex) { + // The COMMIT of the last attempt was sent but never acknowledged, so its profile may + // be stored, and its webhook has to stay. The root transaction re-runs the closure + // only before COMMIT, so every earlier attempt was rolled back. + $last_profile = array_pop($built_profiles); + foreach ($built_profiles as $built_profile) + $built_profile->discardCreatedWebHooks(); + if (!is_null($last_profile)) { + Log::warning(sprintf( + "PaymentGatewayProfileService::addPaymentProfile summit %s commit outcome unknown, kept the webhooks of the %s profile; reconcile them with the stored payment profiles.", + $summit->getId(), + $last_profile->getApplicationType() + )); } - return $profile; - }); + throw $ex; + } catch (\Throwable $ex) { + foreach ($built_profiles as $built_profile) + $built_profile->discardCreatedWebHooks(); + throw $ex; + } + + if ($profile->isNew()) { + Log::warning(sprintf( + "PaymentGatewayProfileService::addPaymentProfile summit %s the transaction returned a %s profile that was not stored.", + $summit->getId(), + $profile->getApplicationType() + )); + } + foreach ($built_profiles as $built_profile) { + // the returned profile keeps its webhooks only when the transaction inserted it + if ($built_profile !== $profile || $profile->isNew()) + $built_profile->discardCreatedWebHooks(); + } + return $profile; } /** diff --git a/tests/Unit/Services/PaymentGatewayProfileServiceTest.php b/tests/Unit/Services/PaymentGatewayProfileServiceTest.php new file mode 100644 index 0000000000..59d13dd311 --- /dev/null +++ b/tests/Unit/Services/PaymentGatewayProfileServiceTest.php @@ -0,0 +1,411 @@ +app = new Container(); + $this->log = Mockery::spy(LoggerInterface::class); + $this->app->instance('log', $this->log); + Container::setInstance($this->app); + Facade::setFacadeApplication($this->app); + $this->tx_invocations = 0; + } + + protected function tearDown(): void + { + ApiRequestor::setHttpClient(null); + Facade::setFacadeApplication(null); + Facade::clearResolvedInstances(); + Container::setInstance(null); + Mockery::close(); + parent::tearDown(); + } + + /** + * Transaction service that really runs the closure, so the code under test executes. + * $runner replaces the default "run it once and return its value", to simulate a commit + * failure or a retried attempt; it receives a closure that runs the callback and counts it. + */ + private function makeService(?\Closure $runner = null): PaymentGatewayProfileService + { + $tx_service = Mockery::mock(ITransactionService::class); + $tx_service->shouldReceive('transaction') + ->once() + ->andReturnUsing(function (\Closure $callback) use ($runner) { + $attempt = function () use ($callback) { + $this->tx_invocations++; + return $callback(); + }; + return is_null($runner) ? $attempt() : $runner($attempt); + }); + + return new PaymentGatewayProfileService($tx_service); + } + + /** + * Routes every Stripe SDK request to an in-memory fake, and binds the 'url' service that + * buildWebHook() needs to render the confirm route. Returns the fake, whose $requests + * lists each call as "METHOD /path". + */ + private function fakeStripe(): object + { + $url = Mockery::mock(UrlGenerator::class); + $url->shouldReceive('action')->andReturn('https://api.test/api/public/v1/summits/78/payments/Registration/confirm'); + $this->app->instance('url', $url); + + $stripe = new class implements ClientInterface { + public array $requests = []; + private int $next_id = 0; + + public function request($method, $absUrl, $headers, $params, $hasFile) + { + $path = parse_url($absUrl, PHP_URL_PATH); + $this->requests[] = strtoupper($method) . ' ' . $path; + if (strtolower($method) === 'post' && $path === '/v1/webhook_endpoints') { + $this->next_id++; + $body = [ + 'id' => 'we_test_' . $this->next_id, + 'object' => 'webhook_endpoint', + 'secret' => 'whsec_test_' . $this->next_id, + 'livemode' => false, + 'url' => $params['url'] ?? null, + ]; + } elseif (strtolower($method) === 'delete') { + $body = ['id' => basename($path), 'object' => 'webhook_endpoint', 'deleted' => true]; + } else { + $body = ['id' => basename($path), 'object' => 'webhook_endpoint']; + } + return [json_encode($body), 200, []]; + } + }; + ApiRequestor::setHttpClient($stripe); + return $stripe; + } + + /** + * A summit with no payment profile yet whose profile collection behaves like the real one: + * addPaymentProfile() keeps the profile, and getPaymentGateWayProfilePerApp() returns the + * first active profile of that type, including one added by an earlier attempt. A real + * Summit keeps that in-memory state when the root transaction re-runs the closure. + * The profiles it holds are exposed through $profiles. + */ + private function statefulSummit(?array &$profiles): Summit + { + $profiles = []; + $summit = Mockery::mock(Summit::class); + $summit->shouldReceive('getId')->andReturn(78); + $summit->shouldReceive('addPaymentProfile')->andReturnUsing(function (PaymentGatewayProfile $profile) use (&$profiles) { + $profiles[] = $profile; + }); + $summit->shouldReceive('getPaymentGateWayProfilePerApp')->andReturnUsing(function (string $application_type) use (&$profiles) { + foreach ($profiles as $profile) { + if ($profile->isActive() && $profile->getApplicationType() === $application_type) + return $profile; + } + return null; + }); + return $summit; + } + + /** + * Simulates the INSERT done by the transaction's flush(): Doctrine assigns the generated id. + */ + private function stored(PaymentGatewayProfile $profile): PaymentGatewayProfile + { + $id = new \ReflectionProperty(BaseEntity::class, 'id'); + $id->setValue($profile, 24); + return $profile; + } + + /** + * A live Stripe profile payload with no 'active' key, as the admin API can send it: it is + * populated (and gets its webhook) without going through the duplicate check. + */ + private function liveStripePayloadWithoutActiveFlag(): array + { + $payload = $this->activeLiveStripePayload(); + unset($payload['active']); + return $payload; + } + + private function activeRegistrationProfile(): PaymentGatewayProfile + { + $profile = Mockery::mock(PaymentGatewayProfile::class); + $profile->shouldReceive('isActive')->andReturn(true); + $profile->shouldReceive('getApplicationType')->andReturn(IPaymentConstants::ApplicationTypeRegistration); + return $profile; + } + + /** + * A summit that already has an active Registration profile. + */ + private function summitWithActiveRegistrationProfile(): Summit + { + $summit = Mockery::mock(Summit::class); + $summit->shouldReceive('getId')->andReturn(70); + $summit->shouldReceive('getPaymentGateWayProfilePerApp') + ->with(IPaymentConstants::ApplicationTypeRegistration) + ->andReturn($this->activeRegistrationProfile()); + return $summit; + } + + /** + * Payload shape the purchases-api sync (CreatePaymentProfileMQJob) sends for an active, + * live-mode Stripe profile. + */ + private function activeLiveStripePayload(): array + { + return [ + 'provider' => IPaymentConstants::ProviderStripe, + 'application_type' => IPaymentConstants::ApplicationTypeRegistration, + 'active' => true, + 'test_mode_enabled' => false, + 'live_secret_key' => 'sk_live_dummy', + 'live_publishable_key' => 'pk_live_dummy', + 'test_secret_key' => 'sk_test_dummy', + 'test_publishable_key' => 'pk_test_dummy', + 'external_id' => 5, + ]; + } + + public function testRejectsSecondActiveProfileBeforeCreatingAnyWebhook(): void + { + $summit = $this->summitWithActiveRegistrationProfile(); + $summit->shouldNotReceive('addPaymentProfile'); + + $error = null; + try { + $this->makeService()->addPaymentProfile($summit, $this->activeLiveStripePayload()); + } catch (ValidationException $ex) { + $error = $ex; + } + + $this->assertSame(1, $this->tx_invocations); + $this->log->shouldNotHaveReceived('debug', function ($message) { + return is_string($message) && str_contains($message, 'buildWebHook'); + }); + $this->assertNotNull($error, 'addPaymentProfile must reject a second active Registration profile.'); + $this->assertSame( + 'There is already an active Payment Profile for application type Registration,', + $error->getMessage() + ); + } + + public function testStillAddsAnInactiveProfileWhenAnActiveOneExists(): void + { + $summit = $this->summitWithActiveRegistrationProfile(); + $summit->shouldReceive('addPaymentProfile')->once(); + + $profile = $this->makeService()->addPaymentProfile($summit, [ + 'provider' => IPaymentConstants::ProviderStripe, + 'application_type' => IPaymentConstants::ApplicationTypeRegistration, + 'active' => false, + ]); + + $this->assertSame(1, $this->tx_invocations); + $this->assertInstanceOf(StripePaymentProfile::class, $profile); + $this->assertFalse($profile->isActive()); + } + + public function testKeepsTheWebhookOfAStoredProfile(): void + { + $stripe = $this->fakeStripe(); + + $profile = $this->makeService(fn (\Closure $attempt) => $this->stored($attempt())) + ->addPaymentProfile($this->statefulSummit($profiles), $this->activeLiveStripePayload()); + + $this->assertSame(1, $this->tx_invocations); + $this->assertSame([$profile], $profiles); + $this->assertSame('we_test_1', $profile->getLiveWebhookId()); + $this->assertSame(['POST /v1/webhook_endpoints'], $stripe->requests); + } + + public function testDeletesTheCreatedWebhookWhenTheTransactionFailsAfterCreatingIt(): void + { + $stripe = $this->fakeStripe(); + $commit_failure = new \RuntimeException('commit failed'); + + $error = null; + try { + $this->makeService(function (\Closure $attempt) use ($commit_failure) { + $attempt(); + throw $commit_failure; + })->addPaymentProfile($this->statefulSummit($profiles), $this->activeLiveStripePayload()); + } catch (\RuntimeException $ex) { + $error = $ex; + } + + $this->assertSame($commit_failure, $error, 'the original failure must reach the caller'); + $this->assertSame(1, $this->tx_invocations); + $this->assertSame([ + 'POST /v1/webhook_endpoints', + 'GET /v1/webhook_endpoints/we_test_1', + 'DELETE /v1/webhook_endpoints/we_test_1', + ], $stripe->requests); + } + + public function testKeepsTheWebhookWhenTheCommitOutcomeIsUnknown(): void + { + $stripe = $this->fakeStripe(); + $ambiguous = new AmbiguousCommitException('commit outcome unknown'); + + $error = null; + try { + // the COMMIT was sent but its acknowledgment was lost: the profile may be stored + $this->makeService(function (\Closure $attempt) use ($ambiguous) { + $this->stored($attempt()); + throw $ambiguous; + })->addPaymentProfile($this->statefulSummit($profiles), $this->activeLiveStripePayload()); + } catch (AmbiguousCommitException $ex) { + $error = $ex; + } + + $this->assertSame($ambiguous, $error, 'the ambiguous outcome must reach the caller'); + $this->assertSame(['POST /v1/webhook_endpoints'], $stripe->requests); + } + + public function testRetriedAttemptOfAnActiveProfileFailsAsDuplicateAndDeletesTheFirstWebhook(): void + { + $stripe = $this->fakeStripe(); + + // The root transaction re-runs the closure after a transient DB error. The summit still + // holds the first attempt's active profile, so the retry is rejected as a duplicate + // before it reaches Stripe. + $error = null; + try { + $this->makeService(function (\Closure $attempt) { + $attempt(); + return $this->stored($attempt()); + })->addPaymentProfile($this->statefulSummit($profiles), $this->activeLiveStripePayload()); + } catch (ValidationException $ex) { + $error = $ex; + } + + $this->assertSame(2, $this->tx_invocations); + $this->assertNotNull($error); + $this->assertSame('There is already an active Payment Profile for application type Registration,', $error->getMessage()); + $this->assertSame([ + 'POST /v1/webhook_endpoints', + 'GET /v1/webhook_endpoints/we_test_1', + 'DELETE /v1/webhook_endpoints/we_test_1', + ], $stripe->requests); + } + + public function testDeletesOnlyTheWebhookOfAnAttemptThatWasRetried(): void + { + $stripe = $this->fakeStripe(); + + // without the active flag there is no duplicate check, so the retried attempt goes + // through; only its profile gets stored + $profile = $this->makeService(function (\Closure $attempt) { + $attempt(); + return $this->stored($attempt()); + })->addPaymentProfile($this->statefulSummit($profiles), $this->liveStripePayloadWithoutActiveFlag()); + + $this->assertSame(2, $this->tx_invocations); + $this->assertCount(2, $profiles); + $this->assertSame($profiles[1], $profile); + $this->assertSame('we_test_2', $profile->getLiveWebhookId()); + $this->assertSame([ + 'POST /v1/webhook_endpoints', + 'POST /v1/webhook_endpoints', + 'GET /v1/webhook_endpoints/we_test_1', + 'DELETE /v1/webhook_endpoints/we_test_1', + ], $stripe->requests); + } + + public function testDeletesTheWebhookOfAReturnedProfileThatWasNotStored(): void + { + $stripe = $this->fakeStripe(); + + // the transaction returns, but nothing inserted the profile (it never got an id) + $profile = $this->makeService(fn (\Closure $attempt) => $attempt()) + ->addPaymentProfile($this->statefulSummit($profiles), $this->activeLiveStripePayload()); + + $this->assertTrue($profile->isNew()); + $this->assertSame('', $profile->getLiveWebhookId()); + $this->assertSame([ + 'POST /v1/webhook_endpoints', + 'GET /v1/webhook_endpoints/we_test_1', + 'DELETE /v1/webhook_endpoints/we_test_1', + ], $stripe->requests); + } +}