From b8feb5c4ffb16884b1087521cdd802e51c463d6f Mon Sep 17 00:00:00 2001 From: smarcet Date: Tue, 17 Nov 2026 11:55:21 -0300 Subject: [PATCH 1/2] fix(payments): stop leaving orphaned Stripe webhooks when adding a payment profile addPaymentProfile built the profile, which already creates its Stripe webhook, before checking whether the summit had another active profile for the same application type. A rejected profile was rolled back in the DB but its live webhook stayed at Stripe with no stored signing secret, so every delivery to it failed signature verification. Check for the active profile before building, and delete at Stripe any webhook created by an attempt whose profile is not stored: a failed transaction, or an attempt the root transaction re-ran. --- .../PaymentGatewayProfileFactory.php | 27 +- .../Payment/PaymentGatewayProfile.php | 10 + .../Payment/StripePaymentProfile.php | 29 ++ .../Imp/PaymentGatewayProfileService.php | 63 ++-- .../PaymentGatewayProfileServiceTest.php | 288 ++++++++++++++++++ 5 files changed, 389 insertions(+), 28 deletions(-) create mode 100644 tests/Unit/Services/PaymentGatewayProfileServiceTest.php 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..e814ae01fa 100644 --- a/app/Services/Model/Imp/PaymentGatewayProfileService.php +++ b/app/Services/Model/Imp/PaymentGatewayProfileService.php @@ -17,6 +17,7 @@ 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; @@ -35,24 +36,50 @@ 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(); - } - return $profile; - }); + // 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, including the ones built by an + // attempt that the root transaction re-ran after a transient DB error. + $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 (\Exception $ex) { + foreach ($built_profiles as $built_profile) + $built_profile->discardCreatedWebHooks(); + throw $ex; + } + + foreach ($built_profiles as $built_profile) { + if ($built_profile !== $profile) + $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..73e20d2580 --- /dev/null +++ b/tests/Unit/Services/PaymentGatewayProfileServiceTest.php @@ -0,0 +1,288 @@ +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; it expects $added_times addPaymentProfile() calls. + */ + private function summitWithoutProfile(int $added_times): Summit + { + $summit = Mockery::mock(Summit::class); + $summit->shouldReceive('getId')->andReturn(78); + $summit->shouldReceive('getPaymentGateWayProfilePerApp')->andReturn(null); + $summit->shouldReceive('addPaymentProfile')->times($added_times); + return $summit; + } + + 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 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->summitWithoutProfile(1), $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 testDeletesOnlyTheWebhookOfAnAttemptThatWasRetried(): void + { + $stripe = $this->fakeStripe(); + + // the first attempt is rolled back and re-run, as the root transaction does after a + // transient DB error; only the second attempt's profile gets stored + $profile = $this->makeService(function (\Closure $attempt) { + $attempt(); + return $attempt(); + })->addPaymentProfile($this->summitWithoutProfile(2), $this->activeLiveStripePayload()); + + $this->assertSame(2, $this->tx_invocations); + $this->assertInstanceOf(StripePaymentProfile::class, $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); + } +} From 409cd59d794bc2851d51df8c3892ec89b8e1102a Mon Sep 17 00:00:00 2001 From: smarcet Date: Tue, 17 Nov 2026 12:29:34 -0300 Subject: [PATCH 2/2] fix(payments): keep the webhook when the payment profile commit outcome is unknown AmbiguousCommitException means the COMMIT was sent but not acknowledged, so the profile may be stored. Deleting its webhook then would leave a live profile with no working webhook. On that exception only the webhooks of the attempts before the last are deleted (they were rolled back), and the outcome is logged for reconciliation. The cleanup now also runs for \Error throwables, and a returned profile that the transaction did not insert has its webhook deleted. The retry tests use a summit double that keeps its profile collection like a real Summit: a retried active profile is rejected as a duplicate. --- .../Imp/PaymentGatewayProfileService.php | 33 +++- .../PaymentGatewayProfileServiceTest.php | 149 ++++++++++++++++-- 2 files changed, 165 insertions(+), 17 deletions(-) diff --git a/app/Services/Model/Imp/PaymentGatewayProfileService.php b/app/Services/Model/Imp/PaymentGatewayProfileService.php index e814ae01fa..0ed94dbc48 100644 --- a/app/Services/Model/Imp/PaymentGatewayProfileService.php +++ b/app/Services/Model/Imp/PaymentGatewayProfileService.php @@ -21,6 +21,7 @@ use models\summit\PaymentGatewayProfile; use models\summit\PaymentGatewayProfileFactory; use models\summit\Summit; +use services\utils\AmbiguousCommitException; /** * Class PaymentGatewayProfileService @@ -38,8 +39,9 @@ public function addPaymentProfile(Summit $summit, array $payload): ?PaymentGatew { // 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, including the ones built by an - // attempt that the root transaction re-ran after a transient DB error. + // 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) { @@ -69,14 +71,37 @@ public function addPaymentProfile(Summit $summit, array $payload): ?PaymentGatew } return $profile; }); - } catch (\Exception $ex) { + } 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() + )); + } + 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) { - if ($built_profile !== $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 index 73e20d2580..59d13dd311 100644 --- a/tests/Unit/Services/PaymentGatewayProfileServiceTest.php +++ b/tests/Unit/Services/PaymentGatewayProfileServiceTest.php @@ -12,6 +12,7 @@ * limitations under the License. **/ +use App\Models\Utils\BaseEntity; use App\Services\Model\Imp\PaymentGatewayProfileService; use Illuminate\Container\Container; use Illuminate\Contracts\Routing\UrlGenerator; @@ -25,6 +26,7 @@ use models\summit\Summit; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; +use services\utils\AmbiguousCommitException; use Stripe\ApiRequestor; use Stripe\HttpClient\ClientInterface; @@ -40,9 +42,18 @@ * behind that nothing stored the signing secret for, and every delivery to it failed signature * verification. So: * - a second active profile is rejected before anything reaches Stripe; - * - when the transaction fails after a webhook was created, that webhook is deleted again; - * - when the root transaction re-runs the closure, the webhook of the discarded attempt is - * deleted and the stored profile keeps its own. + * - a stored profile keeps its webhook; + * - when the transaction fails after a webhook was created, that webhook is deleted again, + * unless the COMMIT outcome is unknown (AmbiguousCommitException): then the profile may be + * stored, so its webhook stays; + * - when the root transaction re-runs the closure, the webhooks of the discarded attempts are + * deleted. A retried active profile is rejected as a duplicate, because the summit keeps the + * first attempt's profile in memory; a retried profile without the active flag goes through + * and keeps its own webhook; + * - a returned profile the transaction did not insert gets its webhook deleted. + * + * The summit double keeps its profile collection like a real Summit, and stored() simulates + * the id Doctrine assigns on INSERT. * * No Laravel app is booted: a bare container provides the Log facade, and its logger spy is * the assertion surface for "the gateway was never reached". In the duplicate test the 'url' @@ -150,17 +161,51 @@ public function request($method, $absUrl, $headers, $params, $hasFile) } /** - * A summit with no payment profile yet; it expects $added_times addPaymentProfile() calls. + * 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 summitWithoutProfile(int $added_times): Summit + private function statefulSummit(?array &$profiles): Summit { + $profiles = []; $summit = Mockery::mock(Summit::class); $summit->shouldReceive('getId')->andReturn(78); - $summit->shouldReceive('getPaymentGateWayProfilePerApp')->andReturn(null); - $summit->shouldReceive('addPaymentProfile')->times($added_times); + $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); @@ -240,6 +285,19 @@ public function testStillAddsAnInactiveProfileWhenAnActiveOneExists(): void $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(); @@ -250,7 +308,7 @@ public function testDeletesTheCreatedWebhookWhenTheTransactionFailsAfterCreating $this->makeService(function (\Closure $attempt) use ($commit_failure) { $attempt(); throw $commit_failure; - })->addPaymentProfile($this->summitWithoutProfile(1), $this->activeLiveStripePayload()); + })->addPaymentProfile($this->statefulSummit($profiles), $this->activeLiveStripePayload()); } catch (\RuntimeException $ex) { $error = $ex; } @@ -264,19 +322,67 @@ public function testDeletesTheCreatedWebhookWhenTheTransactionFailsAfterCreating ], $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(); - // the first attempt is rolled back and re-run, as the root transaction does after a - // transient DB error; only the second attempt's profile gets stored + // 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 $attempt(); - })->addPaymentProfile($this->summitWithoutProfile(2), $this->activeLiveStripePayload()); + return $this->stored($attempt()); + })->addPaymentProfile($this->statefulSummit($profiles), $this->liveStripePayloadWithoutActiveFlag()); $this->assertSame(2, $this->tx_invocations); - $this->assertInstanceOf(StripePaymentProfile::class, $profile); + $this->assertCount(2, $profiles); + $this->assertSame($profiles[1], $profile); $this->assertSame('we_test_2', $profile->getLiveWebhookId()); $this->assertSame([ 'POST /v1/webhook_endpoints', @@ -285,4 +391,21 @@ public function testDeletesOnlyTheWebhookOfAnAttemptThatWasRetried(): void '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); + } }