Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Implement updating default card

Joshen Lim0fd1d15bb86e
diff --git a/studio/components/interfaces/Billing/AddNewPaymentMethodModal/AddPaymentMethodForm.tsx b/studio/components/interfaces/Billing/AddNewPaymentMethodModal/AddPaymentMethodForm.tsx
index db8b34ac942..85ca67df633 100644
--- a/studio/components/interfaces/Billing/AddNewPaymentMethodModal/AddPaymentMethodForm.tsx
+++ b/studio/components/interfaces/Billing/AddNewPaymentMethodModal/AddPaymentMethodForm.tsx
@@ -3,9 +3,9 @@ import { Button, Modal } from '@supabase/ui'
import { useStripe, useElements, PaymentElement } from '@stripe/react-stripe-js'
import { useStore } from 'hooks'
-import { getURL } from 'lib/helpers'
interface Props {
+ returnUrl: string
onCancel: () => void
}
@@ -13,7 +13,7 @@ interface Props {
// manually creating and attaching payment methods via the API
// Small UX annoyance here, that the page will be refreshed
-const AddPaymentMethodForm: FC<Props> = ({ onCancel }) => {
+const AddPaymentMethodForm: FC<Props> = ({ returnUrl, onCancel }) => {
const { ui } = useStore()
const projectRef = ui.selectedProject?.ref ?? ''
@@ -33,9 +33,7 @@ const AddPaymentMethodForm: FC<Props> = ({ onCancel }) => {
await stripe.confirmSetup({
elements,
- confirmParams: {
- return_url: `${getURL()}/project/${projectRef}/settings/billing/update/pro`,
- },
+ confirmParams: { return_url: returnUrl },
})
}
diff --git a/studio/components/interfaces/Billing/AddNewPaymentMethodModal/index.tsx b/studio/components/interfaces/Billing/AddNewPaymentMethodModal/index.tsx
index 2341607f003..6f4a927ea84 100644
--- a/studio/components/interfaces/Billing/AddNewPaymentMethodModal/index.tsx
+++ b/studio/components/interfaces/Billing/AddNewPaymentMethodModal/index.tsx
@@ -10,12 +10,13 @@ import AddPaymentMethodForm from './AddPaymentMethodForm'
interface Props {
visible: boolean
+ returnUrl: string
onCancel: () => void
}
const stripePromise = loadStripe(STRIPE_PUBLIC_KEY)
-const AddNewPaymentMethodModal: FC<Props> = ({ visible, onCancel }) => {
+const AddNewPaymentMethodModal: FC<Props> = ({ visible, returnUrl, onCancel }) => {
const { ui } = useStore()
const [intent, setIntent] = useState<any>()
@@ -49,7 +50,7 @@ const AddNewPaymentMethodModal: FC<Props> = ({ visible, onCancel }) => {
<div className="py-4 space-y-4">
{intent !== undefined ? (
<Elements stripe={stripePromise} options={options}>
- <AddPaymentMethodForm onCancel={onCancel} />
+ <AddPaymentMethodForm returnUrl={returnUrl} onCancel={onCancel} />
</Elements>
) : (
<div className="w-full flex items-center justify-center py-20">
diff --git a/studio/components/interfaces/Billing/ProUpgrade/index.tsx b/studio/components/interfaces/Billing/ProUpgrade/index.tsx
index 4c78d74a0be..1f42a2896e1 100644
--- a/studio/components/interfaces/Billing/ProUpgrade/index.tsx
+++ b/studio/components/interfaces/Billing/ProUpgrade/index.tsx
@@ -5,6 +5,7 @@ import { Badge, Button, IconArrowLeft, IconHelpCircle, Toggle, Modal } from '@su
import { useStore } from 'hooks'
import { post, patch } from 'lib/common/fetch'
import { API_URL } from 'lib/constants'
+import { getURL } from 'lib/helpers'
import Divider from 'components/ui/Divider'
import {
PaymentSummaryPanel,
@@ -232,6 +233,7 @@ const ProUpgrade: FC<Props> = ({
<AddNewPaymentMethodModal
visible={showAddPaymentMethodModal}
+ returnUrl={`${getURL()}/project/${projectRef}/settings/billing/update/pro`}
onCancel={() => setShowAddPaymentMethodModal(false)}
/>
diff --git a/studio/components/interfaces/Organization/BillingSettings/BillingSettings.tsx b/studio/components/interfaces/Organization/BillingSettings/BillingSettings.tsx
index 0fe97138558..68e16f4c8e4 100644
--- a/studio/components/interfaces/Organization/BillingSettings/BillingSettings.tsx
+++ b/studio/components/interfaces/Organization/BillingSettings/BillingSettings.tsx
@@ -4,7 +4,7 @@ import { FC, useState, useEffect } from 'react'
import { useStore } from 'hooks'
import { API_URL } from 'lib/constants'
import { getURL } from 'lib/helpers'
-import { post } from 'lib/common/fetch'
+import { get, post } from 'lib/common/fetch'
import AWSMarketplaceSubscription from './AWSMarketplaceSubscription'
import ProjectsSummary from './ProjectsSummary'
@@ -22,14 +22,17 @@ const BillingSettings: FC<Props> = ({ organization, projects = [] }) => {
const router = useRouter()
const { ui } = useStore()
+ const [isLoadingPaymentMethods, setIsLoadingPaymentMethods] = useState(false)
+
const [loading, setLoading] = useState<boolean>(false)
const [error, setError] = useState<any>(undefined)
const [customer, setCustomer] = useState<any>(null)
const [taxIds, setTaxIds] = useState<any>(null)
const [paymentMethods, setPaymentMethods] = useState<any>(null)
- const { stripe_customer_id, stripe_customer_object } = organization
+ const { slug, stripe_customer_id, stripe_customer_object } = organization
+ const defaultPaymentMethod = customer?.invoice_settings?.default_payment_method ?? ''
const customerBalance = customer && customer.balance ? customer.balance / 100 : 0
const isCredit = customerBalance < 0
const isDebt = customerBalance > 0
@@ -38,6 +41,10 @@ const BillingSettings: FC<Props> = ({ organization, projects = [] }) => {
? customerBalance.toString().replace('-', '')
: customerBalance
+ useEffect(() => {
+ getPaymentMethods()
+ }, [slug])
+
useEffect(() => {
if (stripe_customer_id) {
getStripeAccount()
@@ -51,15 +58,10 @@ const BillingSettings: FC<Props> = ({ organization, projects = [] }) => {
try {
setLoading(true)
setError(null)
- const {
- paymentMethods,
- customer,
- error: customerError,
- } = await post(`${API_URL}/stripe/customer`, {
+ const { customer, error: customerError } = await post(`${API_URL}/stripe/customer`, {
stripe_customer_id: stripe_customer_id,
})
if (customerError) throw customerError
- setPaymentMethods(paymentMethods)
setCustomer(customer)
const { taxIds, error: taxIdsError } = await post(`${API_URL}/stripe/tax-ids`, {
@@ -78,6 +80,22 @@ const BillingSettings: FC<Props> = ({ organization, projects = [] }) => {
}
}
+ const getPaymentMethods = async () => {
+ try {
+ setIsLoadingPaymentMethods(true)
+ const { data: paymentMethods, error } = await get(`${API_URL}/organizations/${slug}/payments`)
+ if (error) throw error
+ setPaymentMethods(paymentMethods)
+ setIsLoadingPaymentMethods(false)
+ } catch (error: any) {
+ ui.setNotification({
+ error,
+ category: 'error',
+ message: `Failed to get organization payment methods: ${error.message}`,
+ })
+ }
+ }
+
/**
* Get a link and then redirect them
* path is used to determine what path inside billing portal to redirect to
@@ -107,9 +125,11 @@ const BillingSettings: FC<Props> = ({ organization, projects = [] }) => {
<ProjectsSummary projects={projects} />
<CreditBalance balance={balance} isCredit={isCredit} isDebt={isDebt} />
<PaymentMethods
- loading={loading}
- paymentMethods={paymentMethods?.data ?? []}
- redirectToPortal={redirectToPortal}
+ loading={loading || isLoadingPaymentMethods}
+ defaultPaymentMethod={defaultPaymentMethod}
+ paymentMethods={paymentMethods || []}
+ onDefaultMethodUpdated={() => getStripeAccount()}
+ onPaymentMethodsDeleted={() => getPaymentMethods()}
/>
<BillingAddress
loading={loading}
diff --git a/studio/components/interfaces/Organization/BillingSettings/PaymentMethods.tsx b/studio/components/interfaces/Organization/BillingSettings/PaymentMethods.tsx
index 7f5016204e6..e129b32fa96 100644
--- a/studio/components/interfaces/Organization/BillingSettings/PaymentMethods.tsx
+++ b/studio/components/interfaces/Organization/BillingSettings/PaymentMethods.tsx
@@ -1,80 +1,284 @@
-import { FC } from 'react'
+import { FC, useState } from 'react'
+import {
+ Dropdown,
+ IconPlus,
+ IconCreditCard,
+ Button,
+ Input,
+ IconLoader,
+ Badge,
+ Modal,
+ Alert,
+ IconMoreHorizontal,
+ IconX,
+} from '@supabase/ui'
+import * as Tooltip from '@radix-ui/react-tooltip'
+
+import { useStore } from 'hooks'
+import { delete_, patch } from 'lib/common/fetch'
+import { getURL } from 'lib/helpers'
+import { API_URL } from 'lib/constants'
import Panel from 'components/to-be-cleaned/Panel'
-import { IconPlus, IconEdit2, IconCreditCard, Button, Input, IconLoader } from '@supabase/ui'
+import { AddNewPaymentMethodModal } from 'components/interfaces/Billing'
interface Props {
loading: boolean
+ defaultPaymentMethod: string
paymentMethods: any[]
- redirectToPortal: (url: string) => void
+ onDefaultMethodUpdated: () => void
+ onPaymentMethodsDeleted: () => void
}
-const PaymentMethods: FC<Props> = ({ loading, paymentMethods, redirectToPortal }) => {
+const PaymentMethods: FC<Props> = ({
+ loading,
+ defaultPaymentMethod,
+ paymentMethods,
+ onDefaultMethodUpdated,
+ onPaymentMethodsDeleted,
+}) => {
+ const { ui } = useStore()
+ const orgSlug = ui.selectedOrganization?.slug ?? ''
+
+ const [selectedMethodForDefault, setSelectedMethodForDefault] = useState<any>()
+ const [selectedMethodToDelete, setSelectedMethodToDelete] = useState<any>()
+ const [showAddPaymentMethodModal, setShowAddPaymentMethodModal] = useState(false)
+
+ const [isUpdatingPaymentMethod, setIsUpdatingPaymentMethod] = useState(false)
+
+ const onConfirmMakeDefaultPaymentMethod = async () => {
+ try {
+ setIsUpdatingPaymentMethod(true)
+ const { error } = await patch(`${API_URL}/organizations/${orgSlug}/customer`, {
+ invoice_settings: {
+ default_payment_method: selectedMethodForDefault.id,
+ },
+ })
+ if (error) throw error
+ onDefaultMethodUpdated()
+ setSelectedMethodForDefault(undefined)
+ ui.setNotification({
+ category: 'success',
+ message: 'Successfully updated default payment method',
+ })
+ } catch (error: any) {
+ ui.setNotification({
+ category: 'error',
+ message: `Failed to make payment method default: ${error.message}`,
+ })
+ } finally {
+ setIsUpdatingPaymentMethod(false)
+ }
+ }
+
+ const onConfirmDetachPaymentMethod = async () => {
+ try {
+ setIsUpdatingPaymentMethod(true)
+ const { error } = await delete_(`${API_URL}/organizations/${orgSlug}/payments`, {
+ card_id: selectedMethodToDelete.id,
+ })
+ if (error) throw error
+ onPaymentMethodsDeleted()
+ setSelectedMethodToDelete(undefined)
+ ui.setNotification({ category: 'success', message: 'Successfully deleted payment method' })
+ } catch (error: any) {
+ ui.setNotification({
+ category: 'error',
+ message: `Failed to delete payment method: ${error.message}`,
+ })
+ } finally {
+ setIsUpdatingPaymentMethod(false)
+ }
+ }
+
return (
- <div className="space-y-2">
- <div>
- <h4>Payment methods</h4>
- <p className="text-sm opacity-50">Charges will be deducted from the default card</p>
+ <>
+ <div className="space-y-2">
+ <div>
+ <h4>Payment methods</h4>
+ <p className="text-sm opacity-50">Charges will be deducted from the default card</p>
+ </div>
+ <Panel
+ loading={loading}
+ footer={
+ <div>
+ <Button
+ key="panel-footer"
+ type="default"
+ icon={<IconPlus />}
+ onClick={() => setShowAddPaymentMethodModal(true)}
+ >
+ Add new card
+ </Button>
+ </div>
+ }
+ >
+ <Panel.Content>
+ {loading && paymentMethods.length === 0 ? (
+ <div className="flex items-center space-x-4">
+ <IconLoader className="animate-spin" size={14} />
+ <p className="text-sm">Retrieving payment methods</p>
+ </div>
+ ) : paymentMethods.length >= 1 ? (
+ <div className="space-y-2">
+ {paymentMethods.map((paymentMethod: any) => {
+ const isDefault = paymentMethod.id === defaultPaymentMethod
+ return (
+ <div key={paymentMethod.id} className="flex items-center justify-between">
+ <div className="flex items-center space-x-8">
+ <img
+ src={`/img/payment-methods/${paymentMethod.card.brand
+ .replace(' ', '-')
+ .toLowerCase()}.png`}
+ width="32"
+ />
+ <Input
+ readOnly
+ className="w-64"
+ size="small"
+ value={`•••• •••• •••• ${paymentMethod.card.last4}`}
+ />
+ {isDefault ? (
+ <Badge color="gray">Default</Badge>
+ ) : (
+ <div className="opacity-0">
+ <Badge color="gray">Default</Badge>
+ </div>
+ )}
+ <p className="tabular-nums text-sm">
+ Expires: {paymentMethod.card.exp_month}/{paymentMethod.card.exp_year}
+ </p>
+ </div>
+ {isDefault ? (
+ <Tooltip.Root delayDuration={0}>
+ <Tooltip.Trigger>
+ <Button disabled type="outline" icon={<IconX />} />
+ </Tooltip.Trigger>
+ <Tooltip.Content side="bottom">
+ <Tooltip.Arrow className="radix-tooltip-arrow" />
+ <div
+ className={[
+ 'bg-scale-100 shadow py-1 px-2 rounded leading-none', // background
+ 'border border-scale-200 w-48 text-center', //border
+ ].join(' ')}
+ >
+ <span className="text-scale-1200 text-xs">
+ Your default payment method cannot be deleted
+ </span>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Root>
+ ) : (
+ <Dropdown
+ size="tiny"
+ overlay={[
+ <Dropdown.Item
+ onClick={() => setSelectedMethodForDefault(paymentMethod)}
+ >
+ Make default
+ </Dropdown.Item>,
+ <Dropdown.Item onClick={() => setSelectedMethodToDelete(paymentMethod)}>
+ Delete
+ </Dropdown.Item>,
+ ]}
+ >
+ <Button
+ type="outline"
+ icon={<IconMoreHorizontal />}
+ loading={loading}
+ className="hover:border-gray-500"
+ />
+ </Dropdown>
+ )}
+ </div>
+ )
+ })}
+ </div>
+ ) : (
+ <div>
+ <p className="flex items-center space-x-2 opacity-50">
+ <div>
+ <IconCreditCard />
+ </div>
+ <div>No payment methods</div>
+ </p>
+ </div>
+ )}
+ </Panel.Content>
+ </Panel>
</div>
- <Panel
- loading={loading}
- footer={
- <div>
+
+ <AddNewPaymentMethodModal
+ visible={showAddPaymentMethodModal}
+ returnUrl={`${getURL()}/org/${orgSlug}/settings`}
+ onCancel={() => setShowAddPaymentMethodModal(false)}
+ />
+
+ <Modal
+ visible={selectedMethodForDefault !== undefined}
+ size="small"
+ header="Set payment method as default"
+ onCancel={() => setSelectedMethodForDefault(undefined)}
+ customFooter={
+ <div className="flex items-center gap-2">
+ <Button type="default" onClick={() => setSelectedMethodForDefault(undefined)}>
+ Cancel
+ </Button>
<Button
- key="panel-footer"
- type="default"
- icon={<IconPlus />}
- onClick={() => redirectToPortal('/payment-methods')}
+ type="primary"
+ loading={isUpdatingPaymentMethod}
+ onClick={onConfirmMakeDefaultPaymentMethod}
>
- Add new card
+ Confirm
</Button>
</div>
}
>
- <Panel.Content>
- {loading && paymentMethods.length === 0 ? (
- <div className="flex items-center space-x-4">
- <IconLoader className="animate-spin" size={14} />
- <p className="text-sm">Retrieving payment methods</p>
- </div>
- ) : paymentMethods.length >= 1 ? (
- <div className="space-y-2">
- {paymentMethods.map((paymentMethod: any) => (
- <div key={paymentMethod.id} className="flex items-center justify-between">
- <div className="flex items-center space-x-8">
- <img
- src={`/img/payment-methods/${paymentMethod.card.brand
- .replace(' ', '-')
- .toLowerCase()}.png`}
- width="32"
- />
- <Input
- readOnly
- size="small"
- value={`•••• •••• •••• ${paymentMethod.card.last4}`}
- />
- <p>
- {paymentMethod.card.exp_month}/{paymentMethod.card.exp_year}
- </p>
- </div>
- <Button type="outline" icon={<IconEdit2 />} onClick={() => redirectToPortal('/')}>
- Edit
- </Button>
- </div>
- ))}
- </div>
- ) : (
- <div>
- <p className="flex items-center space-x-2 opacity-50">
- <div>
- <IconCreditCard />
- </div>
- <div>No payment methods</div>
+ <div className="py-4">
+ <Modal.Content>
+ <p className="text-sm">
+ Confirm to set selected payment method (Ending with{' '}
+ {selectedMethodForDefault?.card?.last4 ?? ''}) as the default?
+ </p>
+ </Modal.Content>
+ </div>
+ </Modal>
+
+ <Modal
+ visible={selectedMethodToDelete !== undefined}
+ size="medium"
+ header="Delete payment method"
+ onCancel={() => setSelectedMethodToDelete(undefined)}
+ customFooter={
+ <div className="flex items-center gap-2">
+ <Button type="default" onClick={() => setSelectedMethodToDelete(undefined)}>
+ Cancel
+ </Button>
+ <Button
+ type="primary"
+ loading={isUpdatingPaymentMethod}
+ onClick={onConfirmDetachPaymentMethod}
+ >
+ Confirm
+ </Button>
+ </div>
+ }
+ >
+ <div className="py-4">
+ <Modal.Content>
+ <Alert
+ withIcon
+ variant="warning"
+ title="This will permanently delete your payment method."
+ >
+ <p className="">
+ Any subscription currently charging this payment method will start charging your
+ default payment method.
</p>
- </div>
- )}
- </Panel.Content>
- </Panel>
- </div>
+ </Alert>
+ </Modal.Content>
+ </div>
+ </Modal>
+ </>
)
}
diff --git a/studio/pages/org/[slug]/settings.tsx b/studio/pages/org/[slug]/settings.tsx
index 118d29ddfec..aeda9c6bb48 100644
--- a/studio/pages/org/[slug]/settings.tsx
+++ b/studio/pages/org/[slug]/settings.tsx
@@ -40,6 +40,7 @@ const PageContext = createContext(null)
const OrgSettings = () => {
const { app, ui } = useStore()
+ const router = useRouter()
const PageState: any = useLocalObservable(() => ({
user: {} as any,
organization: {},
@@ -75,6 +76,13 @@ const OrgSettings = () => {
},
}))
+ useEffect(() => {
+ // User added a new payment method
+ if (router.query.setup_intent && router.query.redirect_status) {
+ ui.setNotification({ category: 'success', message: 'Successfully added new payment method' })
+ }
+ }, [])
+
useEffect(() => {
const organization = ui.selectedOrganization
const user = ui.profile
@@ -136,14 +144,17 @@ const OrganizationSettings = observer(() => {
})
const TabsView = observer(() => {
- const PageState: any = useContext(PageContext)
+ const { ui, app } = useStore()
const [selectedTab, setSelectedTab] = useState('GENERAL')
+ const organization = ui.selectedOrganization
+ const projects = app.projects.list((x: Project) => x.organization_id == organization?.id)
+
return (
<>
<div className="space-y-3">
<section className="mt-4">
- <h3 className="text-xl">{PageState.organization?.name || 'Organization'} settings</h3>
+ <h3 className="text-xl">{organization?.name || 'Organization'} settings</h3>
</section>
<nav className="">
<Tabs onChange={(id: any) => setSelectedTab(id)} type="underlined">
@@ -173,9 +184,9 @@ const TabsView = observer(() => {
) : selectedTab == 'TEAM' ? (
<TeamSettings />
) : selectedTab == 'BILLING' ? (
- <BillingSettings organization={PageState.organization} projects={PageState.projects} />
+ <BillingSettings organization={organization} projects={projects} />
) : selectedTab == 'INVOICES' ? (
- <InvoicesSettings organization={PageState.organization} />
+ <InvoicesSettings organization={organization} />
) : null}
</div>
</>