Skip to content

Open-source live-chat, email support, omni-channel desk. An alternative to Intercom, Zendesk, Salesforce Service Cloud etc. 🔥💬

fix(stripe): disconnect accounts when the app is uninstalled (#16253)

Muhsin Keloth00b13f7873ed
diff --git a/app/controllers/super_admin/app_configs_controller.rb b/app/controllers/super_admin/app_configs_controller.rb
index f9cfd77e717..e5d5efcaa8a 100644
--- a/app/controllers/super_admin/app_configs_controller.rb
+++ b/app/controllers/super_admin/app_configs_controller.rb
@@ -65,7 +65,7 @@ class SuperAdmin::AppConfigsController < SuperAdmin::ApplicationController
'microsoft' => %w[AZURE_APP_ID AZURE_APP_SECRET],
'email' => %w[MAILER_INBOUND_EMAIL_DOMAIN ACCOUNT_EMAILS_LIMIT ACCOUNT_EMAILS_PLAN_LIMITS],
'linear' => %w[LINEAR_CLIENT_ID LINEAR_CLIENT_SECRET],
- 'stripe' => %w[STRIPE_APP_AUTHORIZE_URL STRIPE_APP_SECRET_KEY],
+ 'stripe' => %w[STRIPE_APP_AUTHORIZE_URL STRIPE_APP_SECRET_KEY STRIPE_APP_WEBHOOK_SECRET],
'slack' => %w[SLACK_CLIENT_ID SLACK_CLIENT_SECRET SLACK_SIGNING_SECRET],
'instagram' => %w[INSTAGRAM_APP_ID INSTAGRAM_APP_SECRET INSTAGRAM_VERIFY_TOKEN INSTAGRAM_API_VERSION ENABLE_INSTAGRAM_CHANNEL_HUMAN_AGENT],
'tiktok' => %w[TIKTOK_APP_ID TIKTOK_APP_SECRET TIKTOK_API_VERSION],
diff --git a/app/controllers/webhooks/stripe_app_controller.rb b/app/controllers/webhooks/stripe_app_controller.rb
new file mode 100644
index 00000000000..d6e59d91a80
--- /dev/null
+++ b/app/controllers/webhooks/stripe_app_controller.rb
@@ -0,0 +1,16 @@
+class Webhooks::StripeAppController < ActionController::API
+ def events
+ secret = GlobalConfig.get_value('STRIPE_APP_WEBHOOK_SECRET')
+ return head :service_unavailable if secret.blank?
+
+ event = Stripe::Webhook.construct_event(request.raw_post, request.headers['Stripe-Signature'], secret)
+ if event.type == 'account.application.deauthorized'
+ return head :bad_request unless event[:account].is_a?(String) && event[:account].match?(/\Aacct_[A-Za-z0-9]+\z/)
+
+ Integrations::Stripe::UninstallationService.new(event: event).perform
+ end
+ head :ok
+ rescue JSON::ParserError, Stripe::SignatureVerificationError
+ head :bad_request
+ end
+end
diff --git a/app/javascript/dashboard/routes/dashboard/settings/integrations/Stripe.vue b/app/javascript/dashboard/routes/dashboard/settings/integrations/Stripe.vue
index bb02bc52fc6..b99d0f1e2a1 100644
--- a/app/javascript/dashboard/routes/dashboard/settings/integrations/Stripe.vue
+++ b/app/javascript/dashboard/routes/dashboard/settings/integrations/Stripe.vue
@@ -1,5 +1,6 @@
<script setup>
import { computed, ref, onMounted } from 'vue';
+import { useEventListener } from '@vueuse/core';
import { useRoute } from 'vue-router';
import { useStore, useFunctionGetter } from 'dashboard/composables/store';
import { useBranding } from 'shared/composables/useBranding';
@@ -20,6 +21,7 @@ const available = ref(false);
const busy = ref(false);
const error = ref(!!route.query.error);
const account = ref(null);
+let refreshVersion = 0;
const STRIPE_LOGO = '/dashboard/images/integrations/stripe.svg';
const STRIPE_LOGO_DARK = '/dashboard/images/integrations/stripe-dark.svg';
@@ -29,18 +31,30 @@ const dashboardURL = computed(() => {
});
const loadIntegration = async () => {
- const { data } = await IntegrationsAPI.get();
- store.commit('integrations/SET_INTEGRATIONS', data.payload);
- const stripe = data.payload.find(item => item.id === 'stripe');
- available.value = !!stripe && !stripe.cleanup_only;
- account.value =
- stripe && (integration.value.enabled || stripe.cleanup_only)
- ? (await StripeAPI.get()).data
- : null;
- loaded.value = true;
+ refreshVersion += 1;
+ const version = refreshVersion;
+ try {
+ const { data } = await IntegrationsAPI.get();
+ if (version !== refreshVersion) return;
+
+ const stripe = data.payload.find(item => item.id === 'stripe');
+ const details =
+ stripe && (stripe.enabled || stripe.cleanup_only)
+ ? (await StripeAPI.get()).data
+ : null;
+ if (version !== refreshVersion) return;
+
+ store.commit('integrations/SET_INTEGRATIONS', data.payload);
+ available.value = !!stripe && !stripe.cleanup_only;
+ account.value = details;
+ loaded.value = true;
+ } catch (err) {
+ if (version === refreshVersion) throw err;
+ }
};
const connect = async () => {
+ refreshVersion += 1;
busy.value = true;
error.value = false;
try {
@@ -54,6 +68,7 @@ const connect = async () => {
};
const disconnect = async () => {
+ refreshVersion += 1;
busy.value = true;
error.value = false;
try {
@@ -72,6 +87,16 @@ const disconnect = async () => {
}
};
+useEventListener(window, 'focus', async () => {
+ if (!loaded.value || busy.value) return;
+
+ try {
+ await loadIntegration();
+ } catch {
+ error.value = true;
+ }
+});
+
onMounted(async () => {
try {
await loadIntegration();
diff --git a/app/javascript/dashboard/routes/dashboard/settings/integrations/specs/Stripe.spec.js b/app/javascript/dashboard/routes/dashboard/settings/integrations/specs/Stripe.spec.js
index 98c3317114e..d3c5c811cf6 100644
--- a/app/javascript/dashboard/routes/dashboard/settings/integrations/specs/Stripe.spec.js
+++ b/app/javascript/dashboard/routes/dashboard/settings/integrations/specs/Stripe.spec.js
@@ -11,6 +11,17 @@ const mocks = vi.hoisted(() => ({
installationName: undefined,
}));
+vi.mock('@vueuse/core', async importOriginal => {
+ const original = await importOriginal();
+ const { onUnmounted } = await import('vue');
+ return {
+ ...original,
+ useEventListener: (target, event, listener) => {
+ target.addEventListener(event, listener);
+ onUnmounted(() => target.removeEventListener(event, listener));
+ },
+ };
+});
vi.mock('vue-router', () => ({ useRoute: () => ({ query: mocks.query }) }));
vi.mock(
'dashboard/routes/dashboard/settings/components/BaseSettingsHeader.vue',
@@ -108,6 +119,9 @@ describe('Stripe integration settings', () => {
it('does not request account details when disconnected', async () => {
mocks.enabled = false;
+ IntegrationsAPI.get.mockResolvedValue({
+ data: { payload: [{ id: 'stripe', enabled: false }] },
+ });
wrapper = mount(Stripe, { global });
await flushPromises();
expect(StripeAPI.get).not.toHaveBeenCalled();
@@ -219,4 +233,51 @@ describe('Stripe integration settings', () => {
expect(wrapper.text()).toContain('acct_test');
expect(wrapper.get('[role="alert"]').exists()).toBe(true);
});
+
+ it.each(['list', 'details', 'error'])(
+ 'ignores an older focus refresh after disconnect: %s',
+ async stage => {
+ wrapper = mount(Stripe, { global });
+ await flushPromises();
+ let resolveRefresh;
+ let rejectRefresh;
+ const pending = new Promise((resolve, reject) => {
+ resolveRefresh = resolve;
+ rejectRefresh = reject;
+ });
+ if (stage === 'list') {
+ IntegrationsAPI.get.mockReturnValueOnce(pending);
+ } else {
+ StripeAPI.get.mockReturnValueOnce(pending);
+ }
+ await wrapper.vm.$nextTick();
+ window.dispatchEvent(new Event('focus'));
+ await flushPromises();
+
+ expect(IntegrationsAPI.get).toHaveBeenCalledTimes(2);
+ StripeAPI.disconnect.mockResolvedValue({});
+ IntegrationsAPI.get.mockResolvedValue({
+ data: { payload: [{ id: 'stripe', enabled: false }] },
+ });
+ await wrapper.get('button').trigger('click');
+ await flushPromises();
+ mocks.commit.mockClear();
+
+ if (stage === 'error') {
+ rejectRefresh(new Error('outdated request failed'));
+ } else {
+ resolveRefresh({
+ data:
+ stage === 'list'
+ ? { payload: [{ id: 'stripe', enabled: true }] }
+ : { account_id: 'acct_test', mode: 'sandbox' },
+ });
+ }
+ await flushPromises();
+ expect(mocks.commit).not.toHaveBeenCalled();
+ expect(wrapper.text()).not.toContain('acct_test');
+ expect(wrapper.get('button').text()).toBe('STRIPE_INTEGRATION.CONNECT');
+ expect(wrapper.find('[role="alert"]').exists()).toBe(false);
+ }
+ );
});
diff --git a/app/services/integrations/stripe/uninstallation_service.rb b/app/services/integrations/stripe/uninstallation_service.rb
new file mode 100644
index 00000000000..33980523f92
--- /dev/null
+++ b/app/services/integrations/stripe/uninstallation_service.rb
@@ -0,0 +1,27 @@
+class Integrations::Stripe::UninstallationService
+ def initialize(event:)
+ @event = event
+ end
+
+ def perform
+ hooks.select(:account_id).distinct.pluck(:account_id).each do |account_id|
+ Account.find(account_id).with_lock do
+ hooks.where(account_id: account_id).lock.each do |hook|
+ connected_at = hook.settings['connected_at']
+ # Equal timestamps cannot distinguish an uninstall from a newer reconnection in the same second.
+ next if connected_at.present? && @event.created <= Time.iso8601(connected_at).to_i
+
+ hook.reauthorized!
+ hook.destroy!
+ end
+ end
+ end
+ end
+
+ private
+
+ def hooks
+ Integrations::Hook.where(app_id: 'stripe', reference_id: @event.account)
+ .where("COALESCE((settings->>'livemode')::boolean, false) = ?", @event.livemode)
+ end
+end
diff --git a/config/installation_config.yml b/config/installation_config.yml
index 298e6481736..75e3f61172f 100644
--- a/config/installation_config.yml
+++ b/config/installation_config.yml
@@ -437,6 +437,13 @@
type: secret
description: 'Use the app developer live secret key for Live mode, or the app managed sandbox secret key for Sandbox. Active Record encryption is required. Changing environments requires reconnecting existing accounts.'
+- name: STRIPE_APP_WEBHOOK_SECRET
+ display_title: 'Stripe App Webhook Signing Secret'
+ value:
+ locked: false
+ type: secret
+ description: 'Signing secret for the Stripe App connected-account webhook endpoint at /webhooks/stripe_app. Subscribe to account.application.deauthorized to disconnect uninstalled accounts.'
+
## ------ Configs added for Linear ------ ##
- name: LINEAR_CLIENT_ID
display_title: 'Linear Client ID'
diff --git a/config/routes.rb b/config/routes.rb
index c467271ee42..acb2fb0a38a 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -719,6 +719,7 @@ Rails.application.routes.draw do
get 'webhooks/instagram', to: 'webhooks/instagram#verify'
post 'webhooks/instagram', to: 'webhooks/instagram#events'
post 'webhooks/tiktok', to: 'webhooks/tiktok#events'
+ post 'webhooks/stripe_app', to: 'webhooks/stripe_app#events'
post 'webhooks/shopify', to: 'webhooks/shopify#events'
namespace :twitter do
diff --git a/spec/services/integrations/stripe/uninstallation_service_spec.rb b/spec/services/integrations/stripe/uninstallation_service_spec.rb
new file mode 100644
index 00000000000..f223971125a
--- /dev/null
+++ b/spec/services/integrations/stripe/uninstallation_service_spec.rb
@@ -0,0 +1,37 @@
+require 'rails_helper'
+
+RSpec.describe Integrations::Stripe::UninstallationService do
+ let(:connected_at) { Time.iso8601('2026-10-15T06:00:00.900Z') }
+ let!(:hook) do
+ create(:integrations_hook, app_id: 'stripe', reference_id: 'acct_reconnected', access_token: 'replacement-token',
+ settings: { 'livemode' => false, 'connected_at' => connected_at.iso8601 })
+ end
+ let(:event) { Stripe::Event.construct_from(account: hook.reference_id, livemode: false, created: event_created) }
+
+ context 'when an earlier uninstall and a reconnection share the same timestamp second' do
+ let(:event_created) { connected_at.to_i }
+
+ it 'preserves the replacement credentials, including on repeated delivery' do
+ 2.times { described_class.new(event: event).perform }
+ expect(hook.reload.access_token).to eq('replacement-token')
+ end
+ end
+
+ context 'when the uninstall predates the reconnection' do
+ let(:event_created) { connected_at.to_i - 1 }
+
+ it 'preserves the connection' do
+ expect { described_class.new(event: event).perform }.not_to change(Integrations::Hook, :count)
+ end
+ end
+
+ context 'when the uninstall is newer than the connection' do
+ let(:event_created) { connected_at.to_i + 1 }
+
+ it 'removes the saved connection and tolerates repeated delivery' do
+ service = described_class.new(event: event)
+ expect { service.perform }.to change(Integrations::Hook, :count).by(-1)
+ expect { service.perform }.not_to change(Integrations::Hook, :count)
+ end
+ end
+end