Fix Stripe webhook routing across shared accounts (#3969)

* Pass gateway identity to payment adapters

* Route Stripe webhooks to their originating gateway

* Test Stripe webhook gateway ownership

* Use DBAL for Stripe gateway ownership lookups

* Test DBAL gateway ownership fallbacks
This commit is contained in:
Adam Daley authored and GitHub committed 2026-07-13 18:11:09 +01:00
1 parent 03ba524f8c
commit 7d18160e5a
3 files changed
+254 -18

No files matched your search

+90 -17
View File
@@ -522,6 +522,16 @@ class Payment_Adapter_Stripe implements FOSSBilling\InjectionAwareInterface
$keepTransaction = false;
try {
// A Stripe account can deliver the same event to multiple webhook
// endpoints. Only the FOSSBilling gateway which created the Stripe
// object may process it; otherwise two gateway records configured
// for one Stripe account can both credit the same payment.
if (!$this->eventBelongsToGateway($event, $gateway_id)) {
$this->di['db']->trash($tx);
return;
}
$keepTransaction = match ($event->type) {
'customer.subscription.created' => $this->handleSubscriptionCreated($api_admin, $tx, $event, $gateway_id),
'customer.subscription.updated' => $this->handleSubscriptionUpdated($api_admin, $tx, $event),
@@ -556,6 +566,81 @@ class Payment_Adapter_Stripe implements FOSSBilling\InjectionAwareInterface
$this->di['db']->store($tx);
}
private function eventBelongsToGateway(object $event, int $gatewayId): bool
{
$stripeObject = $event->data->object ?? null;
if (!is_object($stripeObject)) {
return false;
}
$eventGatewayId = $this->getGatewayIdFromStripeObject($stripeObject);
// Older Stripe objects predate gateway_id metadata. Resolve them via
// their local invoice/subscription association so upgrades do not
// break in-flight payments or existing recurring subscriptions.
if ($eventGatewayId === null) {
$eventGatewayId = $this->getInvoiceGatewayId($stripeObject->metadata->invoice_id ?? null);
}
if ($eventGatewayId === null && str_starts_with((string) ($event->type ?? ''), 'customer.subscription.')) {
$eventGatewayId = $this->getLocalSubscriptionGatewayId($stripeObject->id ?? null);
}
if ($eventGatewayId === null && str_starts_with((string) ($event->type ?? ''), 'invoice')) {
$stripeInvoice = $this->resolveStripeInvoice($stripeObject);
$subscriptionId = $this->extractSubscriptionId($stripeInvoice);
if ($subscriptionId !== null) {
$eventGatewayId = $this->getLocalSubscriptionGatewayId($subscriptionId);
if ($eventGatewayId === null) {
$stripeSubscription = $this->stripe->subscriptions->retrieve($subscriptionId, []);
$eventGatewayId = $this->getGatewayIdFromStripeObject($stripeSubscription)
?? $this->getInvoiceGatewayId($stripeSubscription->metadata->invoice_id ?? null);
}
}
}
return $eventGatewayId === $gatewayId;
}
private function getGatewayIdFromStripeObject(object $stripeObject): ?int
{
$gatewayId = $stripeObject->metadata->gateway_id
?? $stripeObject->parent->subscription_details->metadata->gateway_id
?? $stripeObject->subscription_details->metadata->gateway_id
?? $stripeObject->lines->data[0]->metadata->gateway_id
?? null;
return is_numeric($gatewayId) && (int) $gatewayId > 0 ? (int) $gatewayId : null;
}
private function getInvoiceGatewayId(mixed $invoiceId): ?int
{
if (!is_numeric($invoiceId) || (int) $invoiceId <= 0) {
return null;
}
$gatewayId = $this->di['dbal']->fetchOne(
'SELECT gateway_id FROM invoice WHERE id = :id',
['id' => (int) $invoiceId]
);
return is_numeric($gatewayId) && (int) $gatewayId > 0 ? (int) $gatewayId : null;
}
private function getLocalSubscriptionGatewayId(mixed $subscriptionId): ?int
{
if (!is_string($subscriptionId) || $subscriptionId === '') {
return null;
}
$gatewayId = $this->di['dbal']->fetchOne(
'SELECT pay_gateway_id FROM subscription WHERE sid = :sid',
['sid' => $subscriptionId]
);
return is_numeric($gatewayId) && (int) $gatewayId > 0 ? (int) $gatewayId : null;
}
private function handleSubscriptionCreated($api_admin, Model_Transaction $tx, object $event, int $gateway_id): bool
{
$stripeSubscription = $event->data->object;
@@ -1139,6 +1224,7 @@ class Payment_Adapter_Stripe implements FOSSBilling\InjectionAwareInterface
'metadata' => [
'invoice_id' => $invoice->id,
'client_id' => $invoice->client_id,
'gateway_id' => (string) $this->config['gateway_id'],
],
], ['idempotency_key' => 'sub_invoice_' . $invoice->id]);
}
@@ -1247,17 +1333,12 @@ class Payment_Adapter_Stripe implements FOSSBilling\InjectionAwareInterface
'metadata' => [
'client_id' => (string) $invoice->client_id,
'invoice_id' => (string) $invoice->id,
'gateway_id' => (string) $this->config['gateway_id'],
],
]);
$pubKey = ($this->config['test_mode']) ? $this->config['test_pub_key'] : $this->config['pub_key'];
$dataAmount = $this->getAmountInMinorUnits($invoice);
$settingService = $this->di['mod_service']('System');
$title = $this->getInvoiceTitle($invoice);
$form = '<form id="payment-form" data-secret=":intent_secret">
<div class="loading" style="display:none;"><span>{% trans \'Loading ...\' %}</span></div>
<script src="https://js.stripe.com/v3/"></script>
@@ -1322,18 +1403,12 @@ class Payment_Adapter_Stripe implements FOSSBilling\InjectionAwareInterface
</script>
</form>';
$payGatewayService = $this->di['mod_service']('Invoice', 'PayGateway');
$payGateway = $this->di['db']->findOne('PayGateway', 'gateway = "Stripe"');
$bindings = [
':pub_key' => $pubKey,
':intent_secret' => $intent->client_secret,
':amount' => $dataAmount,
':currency' => $invoice->currency,
':description' => $title,
':buyer_email' => htmlspecialchars((string) $invoice->buyer_email, ENT_QUOTES, 'UTF-8'),
':buyer_name' => htmlspecialchars(trim($invoice->buyer_first_name . ' ' . $invoice->buyer_last_name), ENT_QUOTES, 'UTF-8'),
':callbackUrl' => $payGatewayService->getCallbackUrl($payGateway, $invoice),
':redirectUrl' => $this->di['tools']->url('invoice/' . $invoice->hash),
':callbackUrl' => $this->config['notify_url'],
':invoice_hash' => $invoice->hash,
];
@@ -1353,14 +1428,12 @@ class Payment_Adapter_Stripe implements FOSSBilling\InjectionAwareInterface
'metadata' => [
'invoice_id' => $invoice->id,
'price_id' => $price->id,
'gateway_id' => (string) $this->config['gateway_id'],
],
]);
$pubKey = ($this->config['test_mode']) ? $this->config['test_pub_key'] : $this->config['pub_key'];
$payGatewayService = $this->di['mod_service']('Invoice', 'PayGateway');
$payGateway = $this->di['db']->findOne('PayGateway', 'gateway = "Stripe"');
$form = '<form id="subscription-form" data-secret=":setup_intent_secret">
<div class="loading" style="display:none;"><span>{% trans \'Loading ...\' %}</span></div>
<script src="https://js.stripe.com/v3/"></script>
@@ -1419,7 +1492,7 @@ class Payment_Adapter_Stripe implements FOSSBilling\InjectionAwareInterface
':setup_intent_secret' => $setupIntent->client_secret,
':buyer_email' => htmlspecialchars($invoice->buyer_email ?? '', ENT_QUOTES, 'UTF-8'),
':buyer_name' => htmlspecialchars(trim($invoice->buyer_first_name . ' ' . $invoice->buyer_last_name), ENT_QUOTES, 'UTF-8'),
':callbackUrl' => $payGatewayService->getCallbackUrl($payGateway, $invoice),
':callbackUrl' => $this->config['notify_url'],
':invoice_hash' => $invoice->hash,
];
@@ -336,6 +336,7 @@ class ServicePayGateway implements InjectionAwareInterface
$config = json_decode($pg->config ?? '', true) ?? [];
$defaults = [];
$defaults['auto_redirect'] = false;
$defaults['gateway_id'] = (int) $pg->id;
$defaults['test_mode'] = $pg->test_mode;
$defaults['return_url'] = $this->getReturnUrl($pg, $model);
$defaults['cancel_url'] = $this->getCancelUrl($pg, $model);
+163 -1
View File
@@ -16,6 +16,7 @@ beforeEach(function (): void {
'test_api_key' => 'sk_test_dummy',
'test_pub_key' => 'pk_test_dummy',
'test_webhook_secret' => TEST_WEBHOOK_SECRET,
'gateway_id' => 1,
]);
});
@@ -1070,7 +1071,10 @@ describe('processWebhookEvent noise filtering', function (): void {
$rawBody = json_encode([
'type' => 'customer.subscription.deleted',
'id' => 'evt_life_1',
'data' => ['object' => ['id' => 'sub_nonexistent']],
'data' => ['object' => [
'id' => 'sub_nonexistent',
'metadata' => ['gateway_id' => '1'],
]],
]);
$trashCalled = false;
@@ -1110,6 +1114,164 @@ describe('processWebhookEvent noise filtering', function (): void {
});
});
describe('Stripe webhook gateway ownership', function (): void {
test('tags one-time payments and uses the selected gateway callback', function (): void {
$adapter = new Payment_Adapter_Stripe([
'test_mode' => true,
'test_api_key' => 'sk_test_dummy',
'test_pub_key' => 'pk_test_dummy',
'test_webhook_secret' => TEST_WEBHOOK_SECRET,
'gateway_id' => 3,
'notify_url' => 'https://billing.example/ipn.php?gateway_id=3&invoice_id=15',
]);
$paymentIntentsMock = Mockery::mock();
$paymentIntentsMock->shouldReceive('create')
->once()
->withArgs(fn (array $params): bool => $params['metadata']['gateway_id'] === '3'
&& $params['metadata']['invoice_id'] === '15')
->andReturn(Stripe\PaymentIntent::constructFrom([
'id' => 'pi_gateway_3',
'client_secret' => 'pi_gateway_3_secret',
]));
$stripeMock = Mockery::mock(StripeClient::class);
$stripeMock->paymentIntents = $paymentIntentsMock;
setPrivateProperty($adapter, 'stripe', $stripeMock);
$invoice = new Model_Invoice();
$invoice->loadBean(new DummyBean());
$invoice->id = 15;
$invoice->client_id = 7;
$invoice->currency = 'USD';
$invoice->buyer_email = 'client@example.com';
$invoice->buyer_first_name = 'Test';
$invoice->buyer_last_name = 'Client';
$invoice->hash = 'invoice-hash';
$invoice->nr = 15;
$invoice->serie = 'INV';
$dbMock = Mockery::mock('\\Box_Database');
$dbMock->shouldReceive('getAll')->once()->andReturn([['title' => 'Hosting']]);
$invoiceService = Mockery::mock();
$invoiceService->shouldReceive('getTotalWithTax')->once()->andReturn(15.00);
$di = container();
$di['db'] = $dbMock;
$di['mod_service'] = $di->protect(fn () => $invoiceService);
$adapter->setDi($di);
$form = invokePrivateMethod($adapter, '_generateForm', [$invoice]);
expect($form)->toContain('https://billing.example/ipn.php?gateway_id=3&invoice_id=15');
});
test('ignores an event created by another FOSSBilling Stripe gateway', function (): void {
$tx = buildTransaction();
$tx->id = 550;
$rawBody = json_encode([
'type' => 'payment_intent.succeeded',
'id' => 'evt_wrong_gateway',
'data' => ['object' => [
'id' => 'pi_gateway_3',
'status' => 'succeeded',
'amount' => 1500,
'currency' => 'usd',
'metadata' => [
'invoice_id' => '10',
'client_id' => '3',
'gateway_id' => '3',
],
]],
]);
$dbMock = Mockery::mock('\\Box_Database');
$dbMock->shouldReceive('trash')->once()->with($tx);
$dbMock->shouldNotReceive('findOne');
$dbMock->shouldNotReceive('store');
$di = container();
$di['db'] = $dbMock;
$this->adapter->setDi($di);
$data = [
'http_raw_post_data' => $rawBody,
'server' => ['HTTP_STRIPE_SIGNATURE' => signStripeWebhookPayload($rawBody)],
'get' => [],
'post' => [],
];
invokePrivateMethod($this->adapter, 'processWebhookEvent', [
Mockery::mock(),
$tx,
$data,
10,
]);
});
test('reads copied subscription metadata from recurring invoices', function (): void {
$event = (object) [
'type' => 'invoice.paid',
'data' => (object) ['object' => (object) [
'parent' => (object) [
'subscription_details' => (object) [
'metadata' => (object) ['gateway_id' => '3'],
],
],
]],
];
expect(invokePrivateMethod($this->adapter, 'eventBelongsToGateway', [$event, 3]))->toBeTrue()
->and(invokePrivateMethod($this->adapter, 'eventBelongsToGateway', [$event, 10]))->toBeFalse();
});
test('resolves gateway ownership from the invoice for legacy Stripe objects', function (): void {
$event = (object) [
'type' => 'payment_intent.succeeded',
'data' => (object) ['object' => (object) [
'metadata' => (object) ['invoice_id' => '10'],
]],
];
$dbalMock = Mockery::mock(Doctrine\DBAL\Connection::class);
$dbalMock->shouldReceive('fetchOne')
->twice()
->with('SELECT gateway_id FROM invoice WHERE id = :id', ['id' => 10])
->andReturn('3');
$di = container();
$di['dbal'] = $dbalMock;
$this->adapter->setDi($di);
expect(invokePrivateMethod($this->adapter, 'eventBelongsToGateway', [$event, 3]))->toBeTrue()
->and(invokePrivateMethod($this->adapter, 'eventBelongsToGateway', [$event, 10]))->toBeFalse();
});
test('resolves gateway ownership from a legacy local subscription', function (): void {
$event = (object) [
'type' => 'customer.subscription.updated',
'data' => (object) ['object' => (object) [
'id' => 'sub_legacy',
]],
];
$dbalMock = Mockery::mock(Doctrine\DBAL\Connection::class);
$dbalMock->shouldReceive('fetchOne')
->twice()
->with('SELECT pay_gateway_id FROM subscription WHERE sid = :sid', ['sid' => 'sub_legacy'])
->andReturn('3');
$di = container();
$di['dbal'] = $dbalMock;
$this->adapter->setDi($di);
expect(invokePrivateMethod($this->adapter, 'eventBelongsToGateway', [$event, 3]))->toBeTrue()
->and(invokePrivateMethod($this->adapter, 'eventBelongsToGateway', [$event, 10]))->toBeFalse();
});
});
describe('applyOneTimePayment already-paid guard', function (): void {
test('skips processing when invoice is already paid', function (): void {
$tx = buildTransaction();