> ## Documentation Index
> Fetch the complete documentation index at: https://docs.devinenterprise.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Crear un flujo de pago con Stripe Checkout

export const UseCaseHero = ({title, description, prompt, category, features, devinUrl, agent, intent, playbookId, type}) => {
  const encodedPrompt = encodeURIComponent(prompt || '');
  const tag = 'docs-use-case-gallery';
  const utm = 'utm_source=docs&utm_medium=use-case-gallery&utm_campaign=hero-cta';
  const agentParams = (agent ? '&agent=' + agent : '') + (intent ? '&intent=' + intent : '') + (playbookId ? '&playbookId=' + playbookId : '');
  const devinHref = type === 'schedule' ? 'https://app.devin.ai/settings/schedules/create?' + utm + agentParams + (prompt ? '&prompt=' + encodedPrompt : '') : type === 'review' ? 'https://app.devin.ai/review?' + utm : agent === 'ada' ? 'https://app.devin.ai/search?' + utm + '&noSubmit=true' + (prompt ? '&prompt=' + encodedPrompt : '') : devinUrl ? devinUrl.includes('?') ? devinUrl + '&' + utm + agentParams : devinUrl + '?' + utm + agentParams : prompt ? 'https://app.devin.ai/?tags=' + tag + '&' + utm + agentParams + '&prompt=' + encodedPrompt : 'https://app.devin.ai/?' + utm + agentParams;
  const buttonLabel = type === 'schedule' ? 'Schedule in Devin ↗' : type === 'review' ? 'Set Up Devin Review ↗' : agent === 'advanced' ? 'Try in Devin ↗' : agent === 'dana' ? 'Try in Dana ↗' : agent === 'ada' ? 'Try in Ask Devin ↗' : 'Try in Devin ↗';
  const featureList = features ? features.split(',').map(f => f.trim()) : [];
  return <div className="uc-hero">
      <div className="uc-hero-inner">
        <div className="uc-hero-left">
          <h1 className="uc-hero-title">{title}</h1>
          <p className="uc-hero-desc">{description}</p>
          <div>
            <a href={devinHref} target="_blank" rel="noopener noreferrer" className="try-in-devin-btn">
              {buttonLabel}
            </a>
          </div>
        </div>
        <div className="uc-hero-meta">
          <div className="uc-meta-item">
            <span className="uc-meta-label">Author</span>
            <span className="uc-meta-value">Cognition</span>
          </div>
          <div className="uc-meta-item">
            <span className="uc-meta-label">Category</span>
            <span className="uc-meta-value">{category}</span>
          </div>
          {featureList.length > 0 && <div className="uc-meta-item">
              <span className="uc-meta-label">Features</span>
              <span className="uc-meta-value">{featureList.join(', ')}</span>
            </div>}
        </div>
      </div>
    </div>;
};

export const PromptBlock = ({children, type, agent, intent, playbookId}) => {
  var utm = 'utm_source=docs&utm_medium=use-case-gallery&utm_campaign=prompt-block';
  var tag = 'docs-use-case-gallery';
  var agentParams = (agent ? '&agent=' + agent : '') + (intent ? '&intent=' + intent : '') + (playbookId ? '&playbookId=' + playbookId : '');
  var label = type === 'schedule' ? 'Schedule in Devin' : type === 'playbook' ? 'Create Playbook' : type === 'knowledge' ? 'Add to Knowledge' : agent === 'advanced' ? 'Try in Devin' : agent === 'dana' ? 'Try in Dana' : agent === 'ada' ? 'Try in Ask Devin' : 'Try in Devin';
  var buildUrl = function (text) {
    var encoded = encodeURIComponent(text);
    if (type === 'schedule') return 'https://app.devin.ai/settings/schedules/create?' + utm + agentParams + '&prompt=' + encoded;
    if (type === 'playbook') return 'https://app.devin.ai/settings/playbooks/create?' + utm + '&body=' + encoded;
    if (type === 'knowledge') return 'https://app.devin.ai/knowledge?' + utm + '&body=' + encoded;
    if (agent === 'ada') return 'https://app.devin.ai/search?' + utm + '&noSubmit=true&prompt=' + encoded;
    return 'https://app.devin.ai/?tags=' + tag + '&' + utm + agentParams + '&prompt=' + encoded;
  };
  const ref = React.useRef(null);
  const [href, setHref] = React.useState('#');
  React.useEffect(() => {
    if (!ref.current) return;
    var codeEl = ref.current.querySelector('pre code');
    if (codeEl) {
      var text = codeEl.textContent.trim();
      if (text) setHref(buildUrl(text));
    }
    var header = ref.current.querySelector('[data-component-part="code-block-header"]');
    if (header && !header.querySelector('.prompt-block-devin-link')) {
      var link = document.createElement('a');
      link.href = href;
      link.target = '_blank';
      link.rel = 'noopener noreferrer';
      link.className = 'prompt-block-devin-link';
      link.style.cssText = 'display:inline-flex;align-items:center;gap:6px;text-decoration:none;color:#fff;font-size:11px;font-weight:500;padding:4px 10px;border-radius:6px;white-space:nowrap;background:#317CFF;transition:background 0.2s;margin-left:8px;';
      link.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg> ' + label;
      link.onmouseenter = function () {
        link.style.background = '#2968D9';
      };
      link.onmouseleave = function () {
        link.style.background = '#317CFF';
      };
      header.appendChild(link);
    }
    var existingLink = ref.current.querySelector('.prompt-block-devin-link');
    if (existingLink && href !== '#') existingLink.href = href;
  });
  return <div className="prompt-block" ref={ref}>{children}</div>;
};

<UseCaseHero title="Crear un flujo de Stripe Checkout" description="Entrega a Devin una especificación de checkout con tus claves de sandbox de Stripe y obtén un flujo de pago funcional — página de precios, sesión de checkout, controlador de webhooks y página de confirmación — verificado en el navegador." prompt="Implementa un flujo de Stripe Checkout para nuestra app SaaS. Página de precios en /pricing con tres planes: Starter 19 USD/mes (5 proyectos, 10GB, soporte por email), Pro 49 USD/mes (proyectos ilimitados, 100GB, soporte prioritario), Team 99 USD/mes (Pro + gestión de equipos, SSO, registro de auditoría). Cada tarjeta tiene un botón Subscribe que crea una sesión de Stripe Checkout vía POST /api/checkout/sessions. El webhook en /api/webhooks/stripe maneja checkout.session.completed — actualiza el plan del usuario y subscription_id en la base de datos, y verifica la firma con STRIPE_WEBHOOK_SECRET. La página de éxito en /checkout/success muestra el nombre del plan, el importe y un botón Go to Dashboard. Antes de escribir código, describe tu plan para revisión. Usa nuestra app Next.js, Prisma ORM y sigue los patrones en src/pages/settings/billing.tsx. STRIPE_SECRET_KEY y STRIPE_WEBHOOK_SECRET provienen de variables de entorno. Escribe pruebas para la verificación del webhook, la creación de sesiones y la lógica de actualización del plan. Inicia el servidor de desarrollo y verifica todo el flujo en el navegador con la tarjeta de prueba de Stripe 4242 4242 4242 4242. No abras un PR hasta que todo funcione de extremo a extremo." category="Desarrollo de funcionalidades" features="" />

<div className="uc-detail-wrapper">
  <Tip>¿Prefieres no configurarlo manualmente? Pega un enlace a esta página en una sesión de Devin y pídele que lo configure todo por ti.</Tip>

  <Steps>
    <Step title="(Opcional) Delimita el alcance de la base de código con Ask Devin">
      Si no tienes claro cómo gestiona actualmente tu app los pagos, o qué archivos y patrones debes incluir en tu especificación, usa [Ask Devin](https://app.devin.ai/search?utm_source=docs\&utm_medium=use-case-gallery) para investigar primero:

      <PromptBlock agent="ada">
        ```txt Scope the checkout implementation theme={null}
        How does our app currently handle billing? Show me:
        1. Where user plans/subscriptions are stored in the database
        2. Any existing Stripe integration files or API routes
        3. How other payment-related pages are structured (e.g., settings/billing)
        4. What ORM we use and how migrations are typically created
        ```
      </PromptBlock>

      Utiliza las respuestas para completar tu especificación; menciona archivos concretos, nombres de tablas y patrones para que Devin implemente algo que se integre de forma natural en tu base de código. También puedes iniciar una sesión de Devin directamente desde Ask Devin, y se conservará todo lo que haya aprendido como contexto.
    </Step>

    <Step title="Agregar claves de prueba de Stripe">
      Devin necesita claves de Stripe en **modo de prueba** para crear sesiones de checkout y verificar el controlador del webhook. Usa siempre credenciales de sandbox; nunca le des a Devin claves de Stripe de producción.

      El enfoque más sencillo es almacenarlas como [secretos de organización](/es/product-guides/secrets) antes de iniciar la sesión:

      1. Ve a **Settings > Secrets** y agrega:
         * `STRIPE_SECRET_KEY` — tu clave secreta en modo de prueba desde el [Stripe Dashboard](https://dashboard.stripe.com/test/apikeys)
         * `STRIPE_WEBHOOK_SECRET` — el secreto de firma de tu [configuración del endpoint de webhook](https://dashboard.stripe.com/test/webhooks)
      2. Devin accede a estas como variables de entorno, por lo que nunca terminan incluidas directamente en tu código fuente.

      <Note>Los secretos de organización deben agregarse **antes** de iniciar la sesión; se inyectan al inicio de la sesión. Alternativamente, puedes proporcionar secretos durante la sesión usando el chat, y Devin también te pedirá de forma proactiva cualquier credencial que necesite cuando detecte variables de entorno faltantes.</Note>
    </Step>

    <Step title="Pasa tu especificación de checkout">
      Pega tu especificación — ya sea desde un PRD, un ticket de Linear o un mensaje detallado de Slack — directamente en Devin. Una buena especificación de checkout cubre los niveles de precios, el flujo de pago y lo que ocurre después de un pago exitoso. Cuanto más estructurada, mejor.

      <PromptBlock>
        ```txt Implement Stripe checkout flow theme={null}
        Implement a Stripe checkout flow for our SaaS app:

        ## Pricing page
        - New route at /pricing with three tier cards:
          - Starter: $19/mo — 5 projects, 10GB storage, email support
          - Pro: $49/mo — unlimited projects, 100GB storage, priority support
          - Team: $99/mo — everything in Pro + team management, SSO, audit log
        - Each card has a "Subscribe" button that initiates checkout

        ## Checkout
        - POST /api/checkout/sessions — crea una sesión de Stripe Checkout
          con el ID de precio seleccionado, el correo electrónico del cliente y las URL de éxito/cancelación
        - Redirige al usuario a la página de checkout alojada por Stripe
        - Si el pago es exitoso, redirige a /checkout/success?session_id={CHECKOUT_SESSION_ID}

        ## Webhook
        - POST /api/webhooks/stripe — receives Stripe events
        - Handle checkout.session.completed: update the user's plan and
          subscription_id in the database
        - Verify the webhook signature using STRIPE_WEBHOOK_SECRET

        ## Success page
        - /checkout/success — fetch the session details from Stripe,
          display the plan name, amount, and a "Go to Dashboard" button

        ## Planning
        - Before writing any code, outline your implementation plan and share
          it with me for approval. List the files you'll create or modify,
          the database changes, and the order of implementation.

        ## Technical notes
        - Follow the patterns in src/pages/settings/billing.tsx for the UI
        - Use Prisma: add a subscriptions table (id, user_id, stripe_subscription_id,
          plan, status, current_period_end)
        - STRIPE_SECRET_KEY and STRIPE_WEBHOOK_SECRET are available as env vars

        ## Testing & verification
        - Write tests for webhook signature verification, session creation,
          and the plan-update logic
        - After implementing, spin up the local dev server and verify the
          entire flow in the browser: navigate to /pricing, click Subscribe,
          complete a test payment with Stripe's test card (4242 4242 4242 4242),
          confirm the success page renders, and verify the database was updated
        - Do not open a PR until you've confirmed everything works end-to-end
        ```
      </PromptBlock>

      A good spec for Devin includes three things: **what** to build (pricing tiers, checkout flow, webhook handler), **where** it lives (routes, tables, files), and **how** it fits in (existing patterns to follow). You don't need to specify every implementation detail — Devin investigates your codebase to fill in the gaps.
    </Step>

    <Step title="Devin builds and verifies in the browser">
      Devin lee tu especificación, explora la base de código para encontrar patrones coincidentes y luego implementa en todo el stack. Antes de abrir una PR, ejecuta tu app localmente y abre su [navegador integrado](/es/work-with-devin/devin-session-tools) para verificar que el flujo de checkout funcione de principio a fin.

      Así es como se ve en el ejemplo de checkout con Stripe:

      1. **Crea la migración** — Agrega la tabla `subscriptions` con las columnas `user_id`, `stripe_subscription_id`, `plan`, `status` y `current_period_end`
      2. **Construye la página de precios** — Crea las tres tarjetas de niveles de precios en `/pricing`, cada una con un botón "Subscribe" que envía una solicitud a la API de checkout
      3. **Implementa la creación de la sesión de checkout** — Construye `POST /api/checkout/sessions`, que crea una sesión de Stripe Checkout con el ID de precio correcto, el correo electrónico del cliente y las URL de redirección
      4. **Agrega el controlador del webhook** — Implementa `POST /api/webhooks/stripe` con verificación de firma, manejo del evento `checkout.session.completed` y actualizaciones en la base de datos
      5. **Construye la página de éxito** — Crea `/checkout/success`, que obtiene la sesión de Stripe, muestra el nombre del plan, el importe cobrado y un enlace "Go to Dashboard"
      6. **Escribe pruebas** — Pruebas para la verificación de la firma del webhook (válida, inválida, ausente), la creación de la sesión de checkout y la lógica de actualización del plan en la base de datos
      7. **Abre el navegador** — Inicia el servidor de desarrollo, navega a `/pricing`, hace clic en "Subscribe" en el nivel Pro, verifica que la redirección de Stripe Checkout funcione y comprueba que la página de éxito se renderice correctamente después de un pago de prueba
      8. **Abre una PR** — Entrega todos los cambios con un resumen de lo que se implementó y cómo se verificó

      El paso de verificación en el navegador detecta problemas que las pruebas unitarias no cubren: una tarjeta de precios que no dispara el checkout, una URL de redirección que responde con 404 o una página de éxito que no logra cargar los detalles de la sesión. Si has definido una [skill de pruebas locales](/es/product-guides/skills), Devin sigue esos pasos automáticamente para cada funcionalidad que construye.
    </Step>

    <Step title="Iterate from the PR">
      Once the PR is open, send follow-up prompts in the same session to extend or adjust the checkout flow.

      <PromptBlock>
        ```txt Add subscription management theme={null}
        Add a "Manage Subscription" section to /settings/billing that shows the
        current plan, next billing date, and a "Cancel Subscription" button.
        Use the Stripe customer portal for cancellation — create a portal session
        and redirect the user.
        ```
      </PromptBlock>

      <PromptBlock>
        ```txt Add annual pricing toggle theme={null}
        Add a monthly/annual toggle on the pricing page. Annual plans get a 20%
        discount. Show the per-month price with a "billed annually" note and a
        "Save 20%" badge on each card when annual is selected.
        ```
      </PromptBlock>
    </Step>

    <Step title="Review the PR with Devin Review">
      Una vez que Devin abra la PR, usa [Devin Review](https://app.devin.ai/review?utm_source=docs\&utm_medium=use-case-gallery) para revisar los cambios. Devin Review tiene todo el contexto de tu base de código y puede detectar bug, problemas de seguridad e inconsistencias de estilo en todo el diff. Puedes hacer preguntas de seguimiento en el chat de revisión — por ejemplo, "¿El controlador del webhook valida el tipo de evento antes de procesarlo?" — y Devin responderá basándose en el código real.
    </Step>
  </Steps>
</div>
