# Integrate the customer portal with the API

Learn how to integrate the customer portal using the Stripe API.

With the customer portal, you can let your customers manage their subscriptions, billing, and invoices without building that functionality yourself. Use the Dashboard to configure which features your customers can access, such as switching subscription plans. Then, create a portal session and redirect customers to a Stripe-hosted, co-branded portal where they can manage their accounts.

## Configurar el portal

First, you need to [register for a Stripe account](https://dashboard.stripe.com/register/).

Before you integrate the customer portal, use the Dashboard to choose which actions customers can take. Configure the portal separately for *sandboxes* (A sandbox is an isolated test environment that allows you to test Stripe functionality in your account without affecting your live integration. Use sandboxes to safely experiment with new features and changes) and live mode based on your product and price catalog.

> If you use the customer portal with Stripe Connect, configure it for your platform, not a connected account.

To use different portal settings for different groups of customers, or to manage configurations for connected accounts as a *Connect* (Connect is Stripe's solution for multi-party businesses, such as marketplace or software platforms, to route payments between sellers, customers, and other recipients) platform, [create portal configurations with the API](https://docs.stripe.com/api/customer_portal/configurations/create.md):

```curl
curl https://api.stripe.com/v1/billing_portal/configurations \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d "features[invoice_history][enabled]=true"
```

### Configura un catálogo de productos

If customers can upgrade, downgrade, or change subscription quantities, you must configure a product catalog. Specify the products and prices they can switch to and the subscription items whose quantities they can change. To learn more, see [Create a product](https://docs.stripe.com/products-prices/manage-prices.md#create-product).

You don’t need to configure a product catalog if you use the customer portal only for invoicing.

The portal displays the following attributes of your product catalog:

- **Product name and description**: Editable attributes in the Dashboard and API.
- **Quantity restrictions per product**: Editable attributes in the Dashboard.
- **Price amount, currency, and billing interval**: Fixed attributes. You can only set them when you create them in the Dashboard and API.

### Habilita la recopilación de identificaciones fiscales

If you use [Stripe Tax](https://docs.stripe.com/tax.md) to automatically collect taxes for subscriptions or invoices, you can let customers set and update their tax IDs in the customer portal. Stripe Billing adds the tax IDs to the customers’ *invoices* (Invoices are statements of amounts owed by a customer. They track the status of payments from draft through paid or otherwise finalized. Subscriptions automatically generate invoices, or you can manually create a one-off invoice). To allow customers to set their tax IDs, go to the [Customer portal settings](https://dashboard.stripe.com/settings/billing/portal) and toggle on **Tax ID**. For more information, see how customer tax IDs work with [subscriptions](https://docs.stripe.com/billing/customer/tax-ids.md) and [invoices](https://docs.stripe.com/invoicing/taxes/account-tax-ids.md).

To learn more, see [Set up Stripe Tax](https://docs.stripe.com/tax/set-up.md) and [Collect taxes for recurring payments](https://docs.stripe.com/billing/taxes/collect-taxes.md).

### Previsualización y prueba

While you configure the portal, click **Preview** to open a read-only view and see how customers can manage their subscriptions and billing details.

After you save your settings, test the portal with a sandbox customer:

1. In the Dashboard, open the customer’s details page.
2. Click **Actions**.
3. Click **Open customer portal**.

You can preview and test the portal only in a sandbox, and you need Dashboard edit permissions. If these options aren’t available, confirm that you’re viewing a sandbox, saved the configuration in that sandbox, and have the required permissions.

## Implementar un redireccionamiento en tu sitio [Lado del cliente] [Lado del servidor]

La sesión del portal es el punto de entrada al portal de clientes. Proporciona un enlace único y temporal al portal. Cuando el cliente quiere gestionar su facturación, debes crear una nueva sesión en el portal y redirigirlo a la `url` de la sesión.

En tu sitio, agrega un botón en el que los clientes puedan hacer click para entrar al portal. Usa una solicitud POST para crear una sesión en el portal:

```html
<form method="POST" action="/create-customer-portal-session">
  <button type="submit">Manage billing</button>
</form>
```

Next, add an endpoint that creates a portal session and redirects your customers. Make sure to authenticate customers on your site before creating sessions for them. To [create a session](https://docs.stripe.com/api/customer_portal/sessions/create.md), you need the customer’s ID and a `return_url`, which is required if a default return URL isn’t set in the Dashboard configuration.

When you create a portal session, Stripe returns the `portal session object`, which contains the session’s [short-lived URL](https://docs.stripe.com/api/customer_portal/sessions/object.md?lang=curl#portal_session_object-url) that your customers use to access the customer portal.

> #### Usa la API Accounts v2 para representar a los clientes
> 
> La API Accounts v2 suele estar disponible para usuarios Connect y en versión preliminar pública para otros usuarios de Stripe. Si eres parte de la versión preliminar Accounts v2, debes especificar una [versión preliminar](https://docs.stripe.com/api-v2-overview.md#sdk-and-api-versioning) en tu código.
> 
> Con el propósito de unirte a la versión preliminar Accounts v2, ve a las [versiones preliminares y funcionalidades de la cuenta](https://dashboard.stripe.com/settings/previews) en tu Dashboard y habilita **Métodos de pago reutilizables para Global Payouts**.
> 
> Para la mayoría de los casos de uso, te recomendamos que[modeles a tus clientes como objetos Account configurados por el cliente](https://docs.stripe.com/accounts-v2/use-accounts-as-customers.md) en lugar de usar objetos [Customer](https://docs.stripe.com/api/customers.md).

#### Accounts v2

```curl
curl https://api.stripe.com/v1/billing_portal/sessions \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d "customer_account={{CUSTOMERACCOUNT_ID}}" \
  --data-urlencode "return_url=https://example.com/account"
```

#### Customers v1

```curl
curl https://api.stripe.com/v1/billing_portal/sessions \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d "customer={{CUSTOMER_ID}}" \
  --data-urlencode "return_url=https://example.com/account"
```

## Escuchar webhooks [Lado del servidor]

Cuando se cambia la categoría de una suscripción o se cancela una suscripción, tienes que asegurarte de que los clientes solo reciban los productos o servicios correspondientes a la suscripción activa. Stripe envía notificaciones de estos cambios a tu integración usando *webhooks* (A configurable endpoint that executes when it receives certain event notifications from an event destination). En el objeto `Event`, busca el ID de la suscripción o el cliente para determinar a qué cliente se aplica el evento.

When your customers update their billing information in the customer portal, it’s important to update your customer records. Listen for changes using the `customer.updated` or `v2.core.account[configuration.customer].updated` webhook.

Stripe también envía notificaciones si se paga una factura a tu integración usando *webhooks* (A configurable endpoint that executes when it receives certain event notifications from an event destination). En el objeto `Event`, busca el ID de la factura o el cliente para determinar a qué cliente se aplica el evento.

If you haven’t set up a webhook endpoint with Stripe before, see [Stripe webhooks](https://docs.stripe.com/webhooks.md). Then, listen for the events in the following table.

| Evento | Descripción |
| --- | --- |
| [customer.subscription.updated](https://docs.stripe.com/api/events/types.md#event_types-customer.subscription.updated) | Escucha este evento para controlar los cambios de planes de suscripciones. Si se trata de un plan superior, verifica el atributo `subscription.items.data[0].price` en el objeto subscription para encontrar el precio de la suscripción del cliente. Luego, otorga acceso al producto nuevo. Si se trata de un plan inferior, verifica el mismo atributo y ajusta o revoca el acceso según corresponda.

When a customer uses the portal to upgrade or downgrade a subscription with a [trial](https://docs.stripe.com/billing/subscriptions/trials/free-trials.md), the subscription’s trial ends immediately when switching to the new price. |
| [customer.subscription.updated](https://docs.stripe.com/api/events/types.md#event_types-customer.subscription.updated) | Escucha este evento para controlar las actualizaciones de las cantidades de suscripciones. Cuando lo recibas, verifica el atributo `subscription.items.data[0].quantity` para encontrar la cantidad de la suscripción del cliente. Luego, otorga acceso a la nueva cantidad. |
| [customer.subscription.deleted](https://docs.stripe.com/api/events/types.md#event_types-customer.subscription.deleted) | Listen to this to monitor subscription cancellations. When you receive this event, revoke the customer’s access to the product. If you configure the portal to cancel subscriptions at the end of a billing period, listen to the [customer.subscription.updated](https://docs.stripe.com/api/events/types.md#event_types-customer.subscription.updated) event to be notified of cancellations before they occur. For flexible [billing mode](https://docs.stripe.com/api/subscriptions/object.md#subscription_object-billing_mode) subscriptions, if `cancel_at` isn’t `null`, the subscription is canceled at the end of its billing period. For classic billing mode subscriptions, check that `cancel_at_period_end` is `true`.

If a customer changes their mind, they can reactivate their subscription prior to the end of the billing period. When they do this, a [customer.subscription.updated](https://docs.stripe.com/api/events/types.md#event_types-customer.subscription.updated) event is sent. For flexible billing mode subscriptions, check that `cancel_at` is `null` to confirm reactivation. For classic billing mode, check that `cancel_at_period_end` is `false`. |
| [customer.subscription.paused](https://docs.stripe.com/api/events/types.md#event_types-customer.subscription.paused) | Occurs when a subscription that a customer paused in the portal enters the `paused` status. Suspend access to your service when you receive this event, not when the customer schedules the pause. Learn how to [handle pause and resume events](https://docs.stripe.com/customer-management/pause-subscriptions.md#webhooks). |
| [customer.subscription.resumed](https://docs.stripe.com/api/events/types.md#event_types-customer.subscription.resumed) | Occurs when a paused subscription resumes, either automatically or because the customer resumed it early in the portal. Restore access to your service when you receive this event. |
| [payment_method.attached](https://docs.stripe.com/api/events/types.md#event_types-payment_method.attached) | Ocurre cuando el cliente agrega un método de pago. |
| [payment_method.detached](https://docs.stripe.com/api/events/types.md#event_types-payment_method.detached) | Ocurre cuando el cliente quita un método de pago. |
| [customer.updated](https://docs.stripe.com/api/events/types.md#event_types-customer.updated) | Occurs when a [Customer](https://docs.stripe.com/api/customers/object.md) object is updated. Check the `invoice_settings.default_payment_method` attribute to find the payment method that the customer selected as the new default. If you have subscriptions that override the customer-level default payment method, customers can remove this override. Check the subscription’s `default_payment_method` attribute when you receive this event to see if the override was removed. Use this webhook to update any relevant information in your database. All updates must be treated as billing information changes only. Don’t use the customer billing email address as a login credential. |
| [v2.core.account[configuration.customer].updated](https://docs.stripe.com/api/v2/core/events/event-types.md#v2_event_types-v2.core.account%5Bconfiguration.customer%5D.updated) | Occurs when a customer-configured `Account`’s [customer configuration](https://docs.stripe.com/api/v2/core/accounts/object.md#v2_account_object-configuration-customer) is updated. Check the `configuration.customer.billing.default_payment_method` attribute to find the payment method that the customer selected as the new default. If you have subscriptions that override the customer-level default payment method, customers can remove this override. Check the subscription’s `default_payment_method` attribute when you receive this event to see if the override was removed. Use this webhook to update any relevant information in your database. All updates must be treated as billing information changes only. Don’t use the customer billing email address as a login credential. |
| [customer.tax_id.created](https://docs.stripe.com/api/events/types.md#event_types-customer.tax_id.created) | Occurs when customers manage their tax IDs. Stripe can validate some types of tax IDs. Learn more in the [tax IDs guide](https://docs.stripe.com/billing/customer/tax-ids.md). |
| [customer.tax_id.deleted](https://docs.stripe.com/api/events/types.md#event_types-customer.tax_id.deleted) | Occurs when customers manage their tax IDs. Stripe can validate some types of tax IDs. Learn more in the [tax IDs guide](https://docs.stripe.com/billing/customer/tax-ids.md). |
| [customer.tax_id.updated](https://docs.stripe.com/api/events/types.md#event_types-customer.tax_id.updated) | Listen to this to get validation updates about customer tax IDs. Learn more in the [tax IDs guide](https://docs.stripe.com/billing/customer/tax-ids.md). |
| [billing_portal.configuration.created](https://docs.stripe.com/api/events/types.md#event_types-billing_portal.configuration.created) | Ocurre cuando se crea una configuración. |
| [billing_portal.configuration.updated](https://docs.stripe.com/api/events/types.md#event_types-billing_portal.configuration.updated) | Ocurre cuando se actualiza una configuración. |
| [billing_portal.session.created](https://docs.stripe.com/api/events/types.md#event_types-billing_portal.session.created) | Ocurre cuando se crea una sesión del portal. |

## Launch the portal

Make sure to test the portal before enabling it in production.

When you create a portal session, Stripe returns the `portal session` object, which contains the session’s [short-lived URL](https://docs.stripe.com/api/customer_portal/sessions/object.md?lang=curl#portal_session_object-url) that your customers must use to access the customer portal. You can also create one shareable link for each configuration of the portal with the [login_page](https://docs.stripe.com/api/customer_portal/configurations/object.md#portal_configuration_object-login_page) parameter.

- Desactiva **Ver datos de prueba** en el Dashboard.
- [Configura](https://dashboard.stripe.com/settings/billing/portal) el portal en modo activo.
- Agrega tus [webhooks](https://dashboard.stripe.com/webhooks) en modo activo.

Stripe maintains multiple distinct sets of portal configurations: one for live mode and one for each sandbox. To help you validate your integration, making changes in one mode doesn’t affect your configuration in the other.

## Optional: Deep link to specific pages

You might want to streamline customer actions and further customize workflows between your own app and Stripe. Customer portal deep links allow you to link directly to a page with the specified action to complete, and to customize the redirect behavior after the customer completes the action. Learn more about using [customer portal deep links](https://docs.stripe.com/customer-management/portal-deep-links.md).

## Optional: Personalizar una sesión del portal [Lado del servidor]

Es posible que quieras habilitar diferentes conjuntos de productos, precios o funcionalidades en el portal para distintos grupos de clientes. Para usar una configuración específica durante una sesión del portal, debes definirla como sustitución al iniciar el portal. De lo contrario, el portal utilizará la configuración predeterminada.

The Dashboard supports creating and updating the default configuration. You can only manage other configurations using the [Customer Portal Configurations](https://docs.stripe.com/api/customer_portal/configurations/object.md).

#### Accounts v2

```curl
curl https://api.stripe.com/v1/billing_portal/sessions \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d "customer_account={{CUSTOMERACCOUNT_ID}}" \
  -d configuration={{CONFIGURATION_ID}}
```

#### Customers v1

```curl
curl https://api.stripe.com/v1/billing_portal/sessions \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d "customer={{CUSTOMER_ID}}" \
  -d configuration={{CONFIGURATION_ID}}
```

If you’re a Connect platform, you can specify `on_behalf_of` when launching the portal. This causes the branding, logo, and business name of the portal session to reflect the `on_behalf_of` account. In addition, the portal only shows subscriptions and invoices with the `on_behalf_of` account specified. To learn more about `on_behalf_of`, see the [on_behalf_of documentation](https://docs.stripe.com/connect/separate-charges-and-transfers.md#settlement-merchant).

#### Accounts v2

```curl
curl https://api.stripe.com/v1/billing_portal/sessions \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d "customer_account={{CUSTOMERACCOUNT_ID}}" \
  -d configuration={{CONFIGURATION_ID}} \
  -d on_behalf_of={{CONNECTED_ACCOUNT_ID}}
```

#### Customers v1

```curl
curl https://api.stripe.com/v1/billing_portal/sessions \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d "customer={{CUSTOMER_ID}}" \
  -d configuration={{CONFIGURATION_ID}} \
  -d on_behalf_of={{CONNECTED_ACCOUNT_ID}}
```

## Optional: Customize branding

To customize the portal:

1. Go to the [Branding settings](https://dashboard.stripe.com/settings/branding) page, upload your icon or logo, and customize colors.
2. Go to the [Public account settings](https://dashboard.stripe.com/settings/public) page and review your public business name and information.
