# Crear una página de Checkout alojada en Stripe # Página alojada en Stripe Examina un ejemplo de código completo y funcional de una integración con [Stripe Checkout](https://docs.stripe.com/payments/checkout.md) en la que los clientes hacen clic en un botón de tu sitio y son redirigidos a una página de pago alojada en Stripe. El ejemplo incluye el código del lado del cliente y del lado del servidor, y la página de pago está prediseñada. ### Instalar la biblioteca de Stripe Node Instala el paquete e impórtalo en tu código. Como alternativa, si empiezas de cero y necesitas un archivo package.json, descarga los archivos del proyecto mediante el enlace de descarga que encontrarás en el editor de código. #### npm Instala la biblioteca: ```bash npm install --save stripe ``` #### GitHub O bien, descarga el código fuente de la biblioteca de stripe-node directamente [desde GitHub](https://github.com/stripe/stripe-node). ### Instalar la biblioteca de Stripe Ruby Instala la gema en Ruby de Stripe y pídela en tu código. Como alternativa, si empiezas de cero y necesitas un Gemfile, descarga los archivos del proyecto mediante el enlace que encontrarás en el editor de código. #### Terminal Instala la gema: ```bash gem install stripe ``` #### Paquete Agrega esta línea a tu Gemfile: ```bash gem 'stripe' ``` #### GitHub O bien, descarga el código fuente de la gema en Ruby de Stripe directamente [desde GitHub](https://github.com/stripe/stripe-ruby). ### Instalar la biblioteca de Stripe Java Agrega la dependencia para compilar e importar la biblioteca. Como alternativa, si empiezas de cero y necesitas un archivo pom.xml de muestra (para Maven), descarga los archivos del proyecto mediante el enlace que encontrarás en el editor de código. #### Maven Agrega la siguiente dependencia a tu POM y reemplaza {VERSION} con el número de versión que quieres usar. ```bash \ncom.stripe\nstripe-java\n{VERSION}\n ``` #### Gradle Agrega la dependencia a tu archivo build.gradle y reemplaza {VERSION} con el número de versión que quieres usar. ```bash implementation "com.stripe:stripe-java:{VERSION}" ``` #### GitHub Descarga el JAR directamente [desde GitHub](https://github.com/stripe/stripe-java/releases/latest). ### Instalar el paquete de Stripe Python Instala el paquete de Stripe e impórtalo en tu código. Como alternativa, si empiezas de cero y necesitas un archivo requirements.txt, descarga los archivos del proyecto mediante el enlace que encontrarás en el editor de código. #### pip Instala el paquete a través de pip: ```bash pip3 install stripe ``` #### GitHub Descargar el código Source de la biblioteca stripe-python directamente [desde GitHub](https://github.com/stripe/stripe-python). ### Instalar la biblioteca de Stripe PHP Usa Composer para instalar la biblioteca e inicializa con la clave secreta de tu API. Como alternativa, si empiezas de cero y necesitas un archivo composer.json, descarga los archivos mediante el enlace que encontrarás en el editor de código. #### Composer Instala la biblioteca: ```bash composer require stripe/stripe-php ``` #### GitHub O bien, descarga el código fuente de la biblioteca de stripe-php directamente [desde GitHub](https://github.com/stripe/stripe-php). ### Configurar tu servidor Agrega la dependencia para compilar e importar la biblioteca. Como alternativa, si empiezas de cero y necesitas un archivo go.mod, descarga los archivos del proyecto mediante el enlace que encontrarás en el editor de código. #### Go Asegúrate de inicializar con Go Modules: ```bash go get -u github.com/stripe/stripe-go/v85 ``` #### GitHub O bien, descarga el código fuente de stripe-go module directamente [desde GitHub](https://github.com/stripe/stripe-go). ### Instalar la biblioteca de Stripe.net Instala el paquete con .NET or NuGet. Como alternativa, si empiezas de cero, descarga los archivos que contengan un archivo .csproj configurado. #### dotnet Instala la biblioteca: ```bash dotnet add package Stripe.net ``` #### NuGet Instala la biblioteca: ```bash Install-Package Stripe.net ``` #### GitHub O bien, descarga el código fuente de la biblioteca de Stripe.net directamente [desde GitHub](https://github.com/stripe/stripe-dotnet). ### Instalar las bibliotecas de Stripe Instala los paquetes e impórtalos en tu código. Como alternativa, si empiezas de cero y necesitas un archivo `package.json`, descarga los archivos del proyecto mediante el enlace que encontrarás en el editor de código. Instala las bibliotecas: ```bash npm install --save stripe @stripe/stripe-js next ``` ### Crear una sesión de Checkout Agrega a tu servidor un punto de conexión que cree una [sesión de Checkout](https://docs.stripe.com/api/checkout/sessions.md). Una sesión de Checkout controla lo que tu cliente puede ver en la página de pago, como las partidas de factura, el importe y la moneda del pedido, y los métodos de pago aceptados. Habilitamos las tarjetas y otros métodos de pago comunes de forma predeterminada, y puedes habilitar o deshabilitar los métodos de pago directamente en el [Dashboard Stripe](https://dashboard.stripe.com/settings/payment_methods). ### Crear una sesión de Checkout Agrega un [Route Handler](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) en tu aplicación que cree una [Checkout Session](https://docs.stripe.com/api/checkout/sessions.md). Una Checkout Session controla lo que tu cliente puede ver en la página de pago, como partidas, el importe y la moneda del pedido, y los métodos de pago aceptados. Habilitamos las tarjetas y otros métodos de pago comunes de forma predeterminada, y puedes habilitar o deshabilitar los métodos de pago directamente en el [Dashboard de Stripe](https://dashboard.stripe.com/settings/payment_methods). ### Definir un producto para vender Mantén siempre en tu servidor los datos confidenciales de tu inventario de productos, como el precio y la disponibilidad, para evitar que el cliente los manipule. Define la información del producto al crear la sesión de Checkout, ya sea mediante [ID de precios predefinidos](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=checkout&ui=stripe-hosted#create-product-prices-upfront) o de forma dinámica con [price_data](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-line_items-price_data). ### Elige un modo Para manejar diferentes tipos de transacciones, ajusta el parámetro de `modo`. Para pagos únicos, utiliza `pago`. Para iniciar pagos recurrentes con [suscripciones](https://docs.stripe.com/billing/subscriptions/build-subscriptions.md?payment-ui=checkout&ui=stripe-hosted), cambia el `modo` a `suscripción`. Y para [configurar pagos futuros](https://docs.stripe.com/payments/save-and-reuse.md?platform=web&ui=stripe-hosted), fija el `modo` en `configuración`. ### Proporciona la URL de éxito. Especifica una URL para la página de éxito y asegurate de que sea públicamente accesible, así Stripe puede redirigir a los clientes allí después del pago. ### Redirigir a Checkout Después de crear la sesión, redirige a tu cliente a la URL de la página de Checkout devuelta en la respuesta. ### Agregar una página de confirmación Crea una página de confirmación para la URL que proporcionaste como `success_url` de la sesión de Checkout. Esta página le mostrará al cliente un mensaje de confirmación del pedido u otros detalles. Stripe redirige a esta página cuando el cliente finaliza correctamente el proceso de compra. ### Agregar una página de vista previa del pedido Finalmente, agrega una página que muestre una vista previa del pedido del cliente. Permítele que revise o modifique su pedido. Una vez que se dirige al cliente a la página de Checkout, el pedido es definitivo y solo se puede modificar creando una nueva sesión de Checkout. ### Agregar una página de vista previa del pedido Agrega una página que muestre una vista previa del pedido del cliente. Permítele que revise o modifique su pedido. Una vez que se dirige al cliente a la página de Checkout, el pedido es definitivo y solo se puede modificar creando una nueva sesión de Checkout. ### Agregar un botón de pago Agrega un botón a la página de vista previa del pedido. Cuando tu cliente haga click en ese botón, se le redirigirá a la página de pago alojada en Stripe. ### Agregar un botón de pago Agrega un botón a la página de vista previa del pedido. Cuando tu cliente haga clic en este botón, se lo redirigirá al formulario de pago alojado en Stripe. ### Agregar una página de vista previa del pedido Agrega un archivo debajo de `pages/` para crear una página que muestre una vista previa del pedido del cliente. Permítele que revise o modifique su pedido. Una vez que se dirige al cliente a la página de Checkout, el pedido es definitivo y solo se puede modificar creando una nueva sesión de Checkout ### Recuperar una sesión de Checkout Agrega un botón a la página de vista previa del pedido. Cuando el cliente haga clic en él, haz una solicitud al Route Handler para redirigirlo a una nueva Checkout Session. ### Gestionar el redireccionamiento desde Checkout Muestra un mensaje a tu cliente cuando se lo redirija a tu página. Espera para completar el pedido (por ejemplo, realizar el envío o enviar recibos por correo electrónico) hasta que el pago se haya efectuado correctamente. Obtén más información sobre cómo [completar pedidos con Checkout](https://docs.stripe.com/checkout/fulfillment.md). ### Establecer las variables de entorno Agrega tus claves secretas y publicables en un archivo `.env`. Next.js las carga automáticamente en tu aplicación como [variables de entorno](https://nextjs.org/docs/basic-features/environment-variables). Si quieres escuchar webhooks, incluye un secreto de webhook, que puedes crear en el [Dashboard](https://dashboard.stripe.com/webhooks) o con el [CLI de Stripe](https://docs.stripe.com/stripe-cli.md). ### Antes de ejecutar la aplicación Agrega `“proxy”: “”` a tu archivo `package.json` durante el desarrollo local. ### Ejecutar la aplicación Inicie su servidor y vaya a ### Ejecutar la aplicación Inicie su servidor y vaya a ### Ejecutar la aplicación Inicie su aplicación con `npm run dev` y vaya a ### Pruébalo Haz click en el botón de pago para ir a la página de Stripe Checkout. Utiliza alguna de estas tarjetas de prueba para simular un pago. | Scenario | Card Number | | ----------------------------------- | ---------------- | | Payment succeeds | 4242424242424242 | | Payment requires 3DS authentication | 4000002500003155 | | Payment is declined | 4000000000009995 | ## ¡Felicitaciones! Tu integración básica de Checkout está en funcionamiento. Ahora aprende a personalizar el aspecto de tu página de finalización de compra y a automatizar el cobro de impuestos. ### Personalizar la página de finalización de compra Personaliza el aspecto de la página de Checkout alojada de la siguiente manera: - Agrega tu logotipo y tu paleta de colores en la [configuración de imagen de marca](https://dashboard.stripe.com/settings/branding). - Usa la [API Checkout Sessions](https://docs.stripe.com/api/checkout/sessions/create.md) para activar funcionalidades adicionales, como recopilar direcciones o completar previamente los datos de los clientes. ### Rellenar automáticamente los datos de los clientes Usa [customer_email](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_email) para completar automáticamente la dirección de correo electrónico del cliente en el campo de entrada. También puedes especificar un ID del objeto [Customer](https://docs.stripe.com/api/customers.md) en el campo `customer` para completar automáticamente el campo de dirección de correo electrónico con la dirección almacenada en el objeto Customer. ### Elegir un botón de envío Configura la copia que se muestra en el botón de envío de Checkout estableciendo el [submit_type](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-submit_type). Hay cuatro tipos diferentes de envíos. ### Recopilar datos de facturación y envío Utiliza [billing_address_collection](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-billing_address_collection) y [shipping_address_collection](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-shipping_address_collection) para recopilar la dirección de tu cliente. [shipping_address_collection](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-shipping_address_collection) requiere una lista de `allowed_countries`. Checkout muestra la lista de países admitidos en un menú desplegable en la página. ### Vista previa de la página personalizada Haz clic en el botón de pago para ver una muestra de la página de Stripe Checkout con estos campos adicionales. Obtén más información sobre todas las maneras en que puedes [personalizar Checkout](https://docs.stripe.com/payments/checkout/customization.md). ### Automatizar el cobro de impuestos Calcula y recauda el importe correcto de los impuestos para tus transacciones de Stripe. Obtén más información sobre [Stripe Tax](https://docs.stripe.com/tax.md) y cómo [agregarlo a Checkout](https://docs.stripe.com/tax/checkout.md). ### Configura Stripe Tax en el Dashboard [Activa Stripe Tax](https://dashboard.stripe.com/tax) para monitorear tus obligaciones fiscales, cobrar impuestos automáticamente y acceder a los informes que necesitas para presentar las declaraciones. ### Agregar el parámetro de impuestos automático Establece el parámetro `automatic_tax` en `enabled: true`. ### Clientes nuevos y recurrentes De forma predeterminada, Checkout solo crea [Customers](https://docs.stripe.com/api/customers.md) cuando se necesita uno (por ejemplo, para suscripciones). De lo contrario, Checkout usa [clientes invitados](https://docs.stripe.com/payments/checkout/guest-customers.md) para agrupar los pagos en el Dashboard. Como opción, puedes configurar Checkout para crear siempre un nuevo cliente o para especificar un cliente recurrente. ### Crear clientes siempre Para crear clientes siempre que no se proporcione uno, establece [customer_creation](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_creation) en `'always'`. ### Especifica clientes recurrentes Para asociar una sesión de confirmación de compra a un cliente que ya existe, proporciona el [cliente](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer) cuando crees la sesión. Si modelas clientes usando cuentas v2, también puedes especificar un ID de cuenta en el campo [customer_account](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_account) para completar previamente la dirección de correo electrónico asociada. Obtén más información sobre la [diferencia entre usar v1 Customers y v2 Accounts](https://docs.stripe.com/connect/use-accounts-as-customers.md). // This test secret API key is a placeholder. Don't include personal details in requests with this key. // To see your test secret API key embedded in code samples, sign in to your Stripe account. // You can also find your test secret API key at https://dashboard.stripe.com/test/apikeys. const stripe = require('stripe')('<>'); const session = await stripe.checkout.sessions.create({ customer_email: 'customer@example.com', submit_type: 'donate', billing_address_collection: 'auto', shipping_address_collection: { allowed_countries: ['US', 'CA'], }, line_items: [ { // Provide the exact Price ID (for example, price_1234) of the product you want to sell price: '{{PRICE_ID}}', quantity: 1, }, ], mode: {{CHECKOUT_MODE}}, success_url: `${YOUR_DOMAIN}/success.html`, success_url: `${YOUR_DOMAIN}?success=true`, automatic_tax: {enabled: true}, customer_creation: 'always', // Provide the Customer ID (for example, cus_1234) for an existing customer to associate it with this session // customer: '{{CUSTOMER_ID}}' }); res.redirect(303, session.url); { "name": "stripe-sample", "version": "1.0.0", "description": "A sample Stripe implementation", "main": "server.js", "scripts": { "start": "node server.js" }, "author": "stripe-samples", "license": "ISC", "dependencies": { "express": "^4.17.1", "stripe": "^21.0.1" } } { "name": "stripe-sample", "version": "0.1.0", "dependencies": { "@stripe/react-stripe-js": "^3.7.0", "@stripe/stripe-js": "^7.3.0", "express": "^4.17.1", "react": "^18.2.0", "react-dom": "^18.2.0", "react-scripts": "^3.4.0", "stripe": "21.0.1" }, "devDependencies": { "concurrently": "4.1.2" }, "homepage": "http://localhost:3000/checkout", "proxy": "http://localhost:4242", "scripts": { "start-client": "react-scripts start", "start-server": "node server.js", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "start": "concurrently \"yarn start-client\" \"yarn start-server\"" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } \# This test secret API key is a placeholder. Don't include personal details in requests with this key. # To see your test secret API key embedded in code samples, sign in to your Stripe account. # You can also find your test secret API key at https://dashboard.stripe.com/test/apikeys. client = Stripe::StripeClient.new('<>') session = client.v1.checkout.sessions.create({ customer_email: 'customer@example.com', submit_type: 'donate', billing_address_collection: 'required', shipping_address_collection: { allowed_countries: ['US', 'CA'], }, line_items: [{ \# Provide the exact Price ID (for example, price_1234) of the product you want to sell price: '{{PRICE_ID}}', quantity: 1, }], mode: {{CHECKOUT_MODE}}, success_url: YOUR_DOMAIN + '/success.html', success_url: YOUR_DOMAIN + '?success=true', automatic_tax: {enabled: true}, customer_creation: 'always', \# Provide the Customer ID (for example, cus_1234) for an existing customer to associate it with this session # customer: '{{CUSTOMER_ID}}' }) redirect session.url, 303 import stripe \# This test secret API key is a placeholder. Don't include personal details in requests with this key. # To see your test secret API key embedded in code samples, sign in to your Stripe account. # You can also find your test secret API key at https://dashboard.stripe.com/test/apikeys. client = stripe.StripeClient('<>') checkout_session = client.v1.checkout.sessions.create(params={ 'customer_email': 'customer@example.com', 'submit_type': 'donate', 'billing_address_collection': 'auto', 'shipping_address_collection': { 'allowed_countries': ['US', 'CA'], }, 'line_items': [ { \# Provide the exact Price ID (for example, price_1234) of the product you want to sell 'price': '{{PRICE_ID}}', 'quantity': 1, }, ], 'mode': {{CHECKOUT_MODE}}, 'success_url': YOUR_DOMAIN + '/success.html', 'success_url': YOUR_DOMAIN + '?success=true', 'automatic_tax': {'enabled': True}, 'customer_creation': 'always', \# Provide the Customer ID (for example, cus_1234) for an existing customer to associate it with this session # customer='{{CUSTOMER_ID}}' }) return redirect(checkout_session.url, code=303) certifi==2026.1.4 chardet==5.2.0 click==8.3.1 Flask==3.1.2 idna==3.11 itsdangerous==2.2.0 Jinja2==3.1.6 MarkupSafe==3.0.3 requests==2.32.5 stripe==15.0.0 toml==0.10.2 Werkzeug==3.1.5 $stripe = new \Stripe\StripeClient($stripeSecretKey); $checkout_session = $stripe->checkout->sessions->create([ 'customer_email' => 'customer@example.com', 'submit_type' => 'donate', 'billing_address_collection' => 'required', 'shipping_address_collection' => [ 'allowed_countries' => ['US', 'CA'], ], 'line_items' => [[ \# Provide the exact Price ID (for example, price_1234) of the product you want to sell 'price' => '{{PRICE_ID}}', 'quantity' => 1, ]], 'mode' => {{CHECKOUT_MODE}}, 'success_url' => $YOUR_DOMAIN . '/success.html', 'success_url' => $YOUR_DOMAIN . '?success=true', 'automatic_tax' => [ 'enabled' => true, ], 'customer_creation' => 'always', \# Provide the Customer ID (for example, cus_1234) for an existing customer to associate it with this session # 'customer' => '{{CUSTOMER_ID}}' ]); header("HTTP/1.1 303 See Other"); header("Location: " . $checkout_session->url); $stripeSecretKey = '<>'; // This test secret API key is a placeholder. Don't include personal details in requests with this key. // To see your test secret API key embedded in code samples, sign in to your Stripe account. // You can also find your test secret API key at https://dashboard.stripe.com/test/apikeys. services.AddSingleton(new StripeClient("<>")); CustomerEmail = "customer@example.com", SubmitType = "donate", BillingAddressCollection = "auto", ShippingAddressCollection = new SessionShippingAddressCollectionOptions { AllowedCountries = new List { "US", "CA", }, }, LineItems = new List { new SessionLineItemOptions { // Provide the exact Price ID (for example, price_1234) of the product you want to sell Price = "{{PRICE_ID}}", Quantity = 1, }, }, Mode = {{CHECKOUT_MODE}}, SuccessUrl = domain + "/success.html", SuccessUrl = domain + "?success=true", AutomaticTax = new SessionAutomaticTaxOptions { Enabled = true }, CustomerCreation = "always", // Provide the Customer ID (for example, cus_1234) for an existing customer to associate it with this session // Customer="cus_RnhPlBnbBbXapY", Session session = _client.V1.Checkout.Sessions.Create(options); Response.Headers.Add("Location", session.Url); return new StatusCodeResult(303); "github.com/stripe/stripe-go/v85" sc := stripe.NewClient("<>") params := &stripe.CheckoutSessionCreateParams{ CustomerEmail: stripe.String("customer@example.com"), SubmitType: stripe.String("donate"), BillingAddressCollection: stripe.String("auto"), ShippingAddressCollection: &stripe.CheckoutSessionCreateShippingAddressCollectionParams{ AllowedCountries: stripe.StringSlice([]string{ "US", "CA", }), }, LineItems: []*stripe.CheckoutSessionCreateLineItemParams{ &stripe.CheckoutSessionCreateLineItemParams{ // Provide the exact Price ID (for example, price_1234) of the product you want to sell Price: stripe.String("{{PRICE_ID}}"), Quantity: stripe.Int64(1), }, }, Mode: {{CHECKOUT_MODE}}, SuccessURL: stripe.String(domain + "/success.html"), SuccessURL: stripe.String(domain + "?success=true"), AutomaticTax: &stripe.CheckoutSessionCreateAutomaticTaxParams{Enabled: stripe.Bool(true)}, CustomerCreation: stripe.String(stripe.CheckoutSessionCustomerCreationAlways), // Provide the Customer ID (for example, cus_1234) for an existing customer to associate it with this session // Customer: stripe.String("{{CUSTOMER_ID}}"), } s, err := sc.V1CheckoutSessions.Create(context.TODO(), params) if err != nil { log.Printf("sc.V1CheckoutSessions.Create: %v", err) } http.Redirect(w, r, s.URL, http.StatusSeeOther) require github.com/stripe/stripe-go/v85 v85.0.0 // This test secret API key is a placeholder. Don't include personal details in requests with this key. // To see your test secret API key embedded in code samples, sign in to your Stripe account. // You can also find your test secret API key at https://dashboard.stripe.com/test/apikeys. StripeClient client = new StripeClient("<>"); SessionCreateParams params = SessionCreateParams.builder() .setCustomerEmail("customer@example.com") .setSubmitType(SessionCreateParams.SubmitType.DONATE) .setBillingAddressCollection(SessionCreateParams.BillingAddressCollection.REQUIRED) .setShippingAddressCollection( SessionCreateParams.ShippingAddressCollection.builder() .addAllowedCountry(SessionCreateParams.ShippingAddressCollection.AllowedCountry.CA) .addAllowedCountry(SessionCreateParams.ShippingAddressCollection.AllowedCountry.US) .build()) .setMode({{CHECKOUT_MODE}}) .setSuccessUrl(YOUR_DOMAIN + "/success.html") .setSuccessUrl(YOUR_DOMAIN + "?success=true") .setAutomaticTax( SessionCreateParams.AutomaticTax.builder() .setEnabled(true) .build()) .setCustomerCreation(SessionCreateParams.CustomerCreation.ALWAYS) // Provide the Customer ID (for example, cus_1234) for an existing customer to associate it with this session // .setCustomer("{{CUSTOMER_ID}}") .addLineItem( SessionCreateParams.LineItem.builder() .setQuantity(1L) // Provide the exact Price ID (for example, price_1234) of the product you want to sell .setPrice("{{PRICE_ID}}") .build()) .build(); response.redirect(session.getUrl(), 303); return "";
The cover of Stubborn Attachments

Stubborn Attachments

$20.00

We appreciate your business! If you have any questions, please email orders@example.com.

Forgot to add something to your cart? Shop around then come back to pay!

{ "name": "stripe-sample", "version": "0.1.0", "dependencies": { "@stripe/react-stripe-js": "^3.7.0", "@stripe/stripe-js": "^7.3.0", "express": "^4.17.1", "react": "^18.2.0", "react-dom": "^18.2.0", "react-scripts": "^5.0.1", "stripe": "^8.202.0" }, "devDependencies": { "concurrently": "4.1.2" }, "homepage": "http://localhost:3000/checkout", "proxy": "http://127.0.0.1:4242", "scripts": { "start-client": "react-scripts start", "start-server": "node server.js", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "start": "concurrently \"yarn start-client\" \"yarn start-server\"" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } { "name": "client", "version": "0.1.0", "private": true, "dependencies": { "@stripe/react-stripe-js": "^3.7.0", "@stripe/stripe-js": "^7.3.0", "react": "^18.2.0", "react-dom": "^18.2.0", "react-scripts": "^5.0.1" }, "homepage": "http://localhost:3000/checkout", "proxy": "http://127.0.0.1:4242", "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } }
The cover of Stubborn Attachments

Stubborn Attachments

$20.00
// Check to see if this is a redirect back from Checkout const query = new URLSearchParams(window.location.search); if (query.get("success")) { setMessage("Order placed! You will receive an email confirmation."); } if (query.get("canceled")) { setMessage( "Order canceled -- continue to shop around and checkout when you're ready." ); } { "name": "stripe-sample", "version": "0.1.0", "dependencies": { "@stripe/react-stripe-js": "^3.7.0", "@stripe/stripe-js": "^7.3.0", "express": "^4.17.1", "react": "^18.2.0", "react-dom": "^18.2.0", "react-scripts": "^3.4.0", "stripe": "^8.202.0" }, "devDependencies": { "concurrently": "4.1.2" }, "homepage": "http://localhost:3000/checkout", "proxy": "http://localhost:4242", "scripts": { "start-client": "react-scripts start", "start-server": "node server.js", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "start": "concurrently \"yarn start-client\" \"yarn start-server\"" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } { "name": "client", "version": "0.1.0", "private": true, "dependencies": { "@stripe/react-stripe-js": "^3.7.0", "@stripe/stripe-js": "^7.3.0", "react": "^18.2.0", "react-dom": "^18.2.0", "react-scripts": "^3.4.0" }, "homepage": "http://localhost:3000/checkout", "proxy": "http://localhost:4242", "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } // Create Checkout Sessions from body params. const session = await stripe.checkout.sessions.create({ customer_email: 'customer@example.com', submit_type: 'donate', billing_address_collection: 'auto', shipping_address_collection: { allowed_countries: ['US', 'CA'], }, line_items: [ { // Provide the exact Price ID (for example, price_1234) of the product you want to sell price: '{{PRICE_ID}}', quantity: 1, }, ], mode: {{CHECKOUT_MODE}}, success_url: `${origin}/success?session_id={CHECKOUT_SESSION_ID}`, automatic_tax: {enabled: true}, }); return NextResponse.redirect(session.url, 303) \# https://dashboard.stripe.com/apikeys NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=<> STRIPE_SECRET_KEY=<> \# Set this environment variable to support webhooks — https://stripe.com/docs/webhooks#verify-events # STRIPE_WEBHOOK_SECRET=whsec_12345 export default async function IndexPage({ searchParams }) {
import 'server-only' import Stripe from 'stripe' export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY) export default async function Success({ searchParams }) { const { session_id } = await searchParams if (!session_id) throw new Error('Please provide a valid session_id (`cs_test_...`)') const { status, customer_details: { email: customerEmail } } = await stripe.checkout.sessions.retrieve(session_id, { expand: ['line_items', 'payment_intent'] }) if (status === 'open') { return redirect('/') } if (status === 'complete') { return (

We appreciate your business! A confirmation email will be sent to{' '} {customerEmail}. If you have any questions, please email{' '} orders@example.com.

) } } 1. Build the server ~~~ pip3 install -r requirements.txt ~~~ 1. Build the server ~~~ bundle install ~~~ 1. Build the server ~~~ composer install ~~~ 1. Build the server ~~~ dotnet restore ~~~ 1. Build the server ~~~ mvn package ~~~ 2. Run the server ~~~ export FLASK_APP=server.py python3 -m flask run --port=4242 ~~~ 2. Run the server ~~~ ruby server.rb -o 0.0.0.0 ~~~ 2. Run the server ~~~ php -S 127.0.0.1:4242 --docroot=public ~~~ 2. Run the server ~~~ dotnet run ~~~ 2. Run the server ~~~ java -cp target/sample-jar-with-dependencies.jar com.stripe.sample.Server ~~~ 3. Build the client app ~~~ npm install ~~~ 4. Run the client app ~~~ npm start ~~~ If you run into an error, when running npm start, try running the following code and starting again: ~~~ export NODE_OPTIONS=--openssl-legacy-provider ~~~ 5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 3. Build the client app ~~~ npm install ~~~ 4. Run the client app ~~~ npm start ~~~ 5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 3. Build the client app ~~~ npm install ~~~ 4. Run the client app ~~~ npm start ~~~ 5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 3. Build the client app ~~~ npm install ~~~ 4. Run the client app ~~~ npm start ~~~ 5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 3. Build the client app ~~~ npm install ~~~ 4. Run the client app ~~~ npm start ~~~ 5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 1. Run the server ~~~ go run server.go ~~~ 2. Build the client app ~~~ npm install ~~~ 3. Run the client app ~~~ npm start ~~~ 4. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 1. Run the server ~~~ go run server.go ~~~ 2. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 1. Build the application ~~~ npm install ~~~ 2. Run the application ~~~ npm start ~~~ 3. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 1. Build the server ~~~ npm install ~~~ 2. Run the server ~~~ npm start ~~~ 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) \### Development 1. Build the application ~~~shell $ npm install ~~~ 2. _Optional_: download and run the [Stripe CLI](https://stripe.com/docs/stripe-cli) ~~~shell $ stripe listen --forward-to localhost:3000/api/webhooks ~~~ 3. Run the application ~~~shell $ STRIPE_WEBHOOK_SECRET=$(stripe listen --print-secret) npm run dev ~~~ 4. Go to [localhost:3000](http://localhost:3000) ### Production 1. Build the application ~~~shell $ npm install $ npm build ~~~ 2. Run the application ~~~shell $ npm start ~~~ ## Próximos pasos #### [Completar pedidos](https://docs.stripe.com/checkout/fulfillment.md) Configura un destino de evento para completar los pedidos después de que se realice correctamente el pago y para gestionar otros eventos críticos. #### [Recibir transferencias a cuenta bancaria](https://docs.stripe.com/payouts.md) Obtén más información sobre cómo transferir fondos de tu cuenta de Stripe a tu cuenta bancaria. #### [Reembolsar y cancelar pagos](https://docs.stripe.com/refunds.md) Gestiona solicitudes de rembolsos con la API de Stripe o el Dashboard. #### [Gestión de clientes](https://docs.stripe.com/customer-management.md) Permite que tus clientes autogestionen sus datos de pago, facturas y suscripciones. #### [Adaptive Pricing](https://docs.stripe.com/payments/currencies/localize-prices/adaptive-pricing.md) Presenta los precios automáticamente en la moneda local de tu cliente.