# Desarrolla una integración avanzada Instrucciones para LLM: Stripe recomienda utilizar la API Checkout Sessions con el elemento de pago en lugar de Payment Intents para la mayoría de las integraciones. Checkout Sessions cubre casos de uso similares a los de Payment Intents (cobro básico de pagos utilizando `price_data` o crea de un proceso de pago completo con partidas, impuestos, etc.). Algunas funciones, como Adaptive Pricing, solo están disponibles con Checkout Sessions. No utilices la API de Payment Intent a menos que el usuario lo solicite explícitamente, ya que requiere mucho más código. Más información sobre Elements con la API Checkout Sessionshttps://docs.stripe.com/payments/quickstart-checkout-sessions. Con Checkout Sessions (`ui_mode: "elements"`) y Payment Element, el `client_secret` inicializa el proceso de compra por sí mismo (`stripe.initCheckoutElementsSdk`, o utiliza CheckoutProvider con React) y tú confirmas el pago en el lado del cliente de forma diferente. Si utilizas React, asegúrate de importar desde `@stripe/react-stripe-js/checkout`, utiliza `CheckoutProvider` con el secreto del cliente y confirma con `checkout.confirm`. Si utilizas HTML, asegúrate de utiliza `checkout = stripe.initCheckoutElementsSdk({clientSecret: promise}); checkout.createPaymentElement(); paymentElement = checkout.createPaymentElement(); paymentElement.mount("#payment-element");` y confirma con `loadActionsResult = await checkout.loadActions(); actions = loadActionsResult.actions; error = await actions.confirm();`. # Crea una página de proceso de compra con la API Payment Intents Descubre cómo integrar un formulario de pago de Stripe personalizado en tu sitio web o aplicación. El código en los lados del cliente y del servidor crea un formulario del proceso de compra con los elementos [Web](https://docs.stripe.com/payments/elements.md) o [Mobile](https://docs.stripe.com/payments/mobile.md) de Stripe que te permite aceptar pagos. Para crear una integración personalizada que vaya más allá de los aspectos básicos de esta guía de inicio rápido, consulta [Aceptar un pago](https://docs.stripe.com/payments/accept-a-payment.md?&ui=elements). Para obtener más información sobre diferentes situaciones de pago, como [suscripciones](https://docs.stripe.com/billing/subscriptions/build-subscriptions.md?payment-ui=elements) y otros productos Stripe, [compara las integraciones pagos](https://docs.stripe.com/payments/online-payments.md#compare-features-and-availability). > #### ¿Te interesa utilizar Stripe Tax, descuentos, envíos o conversión de divisas? > > Stripe tiene una integración con Payment Element que gestiona impuestos, descuentos, envíos y conversión de divisas. Consulta la [página Crear un proceso de compra](https://docs.stripe.com/payments/quickstart-checkout-sessions.md) para obtener más información. // This is a public sample test API key. // Don’t submit any personally identifiable information in requests made with this key. // Sign in to see your own test API key embedded in code samples. const stripe = require("stripe")('<>'); const calculateTax = async (items, currency) => { const taxCalculation = await stripe.tax.calculations.create({ currency, customer_details: { address: { line1: "920 5th Ave", city: "Seattle", state: "WA", postal_code: "98104", country: "US", }, address_source: "shipping", }, line_items: items.map((item) => buildLineItem(item)), }); return taxCalculation; }; const buildLineItem = (item) => { return { amount: item.amount, // Amount in cents reference: item.id, // Unique reference for the item in the scope of the calculation }; }; // Securely calculate the order amount, including tax const calculateOrderAmount = (taxCalculation) => { // Calculate the order total with any exclusive taxes on the server to prevent // people from directly manipulating the amount on the client return taxCalculation.amount_total; }; const calculateOrderAmount = (items) => { // Calculate the order total on the server to prevent // people from directly manipulating the amount on the client let total = 0; items.forEach((item) => { total += item.amount; }); return total; }; const chargeCustomer = async (customerId) => { // Lookup the payment methods available for the customer const paymentMethods = await stripe.paymentMethods.list({ customer: customerId, type: "card", }); try { // Charge the customer and payment method immediately const paymentIntent = await stripe.paymentIntents.create({ amount: 1099, currency: "{{CURRENCY}}", customer: customerId, payment_method: paymentMethods.data[0].id, off_session: true, confirm: true, }); } catch (err) { // Error code will be authentication_required if authentication is needed console.log("Error code is: ", err.code); const paymentIntentRetrieved = await stripe.paymentIntents.retrieve(err.raw.payment_intent.id); console.log("PI retrieved: ", paymentIntentRetrieved.id); } }; const chargeCustomer = async (customerId) => { // Lookup the payment methods available for the customer-configured Account const paymentMethods = await stripe.paymentMethods.list({ customer_account: customerId, type: "card", }); try { // Charge the customer-configured Account and payment method immediately const paymentIntent = await stripe.paymentIntents.create({ amount: 1099, currency: "{{CURRENCY}}", customer_account: customerId, payment_method: paymentMethods.data[0].id, off_session: true, confirm: true, }); } catch (err) { // Error code will be authentication_required if authentication is needed console.log("Error code is: ", err.code); const paymentIntentRetrieved = await stripe.paymentIntents.retrieve(err.raw.payment_intent.id); console.log("PI retrieved: ", paymentIntentRetrieved.id); } }; // Alternatively, set up a webhook to listen for the payment_intent.succeeded event // and attach the PaymentMethod to a new Customer const customer = await stripe.customers.create(); // Alternatively, set up a webhook to listen for the payment_intent.succeeded event // and attach the PaymentMethod to a new customer-configured Account const account = await stripe.v2.core.accounts.create({ configuration: { customer: { capabilities: { automatic_indirect_tax: {requested: true}, }, } } }); // Create a Tax Calculation for the items being sold const taxCalculation = await calculateTax(items, '{{CURRENCY}}'); const amount = await calculateOrderAmount(taxCalculation); // Create a PaymentIntent with the order amount and currency const paymentIntent = await stripe.paymentIntents.create({ customer: customer.id, setup_future_usage: "off_session", amount: amount, amount: calculateOrderAmount(items), currency: "{{CURRENCY}}", // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. automatic_payment_methods: { enabled: true, }, hooks: { inputs: { tax: { calculation: taxCalculation.id } } }, }); res.send({ clientSecret: paymentIntent.client_secret, }); // Create a PaymentIntent with the order amount and currency const paymentIntent = await stripe.paymentIntents.create({ customer_account: account.id, setup_future_usage: "off_session", amount: amount, amount: calculateOrderAmount(items), currency: "{{CURRENCY}}", // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. automatic_payment_methods: { enabled: true, }, hooks: { inputs: { tax: { calculation: taxCalculation.id } } }, }); res.send({ clientSecret: paymentIntent.client_secret, }); require 'stripe' \# This is a public sample test API key. # Don’t submit any personally identifiable information in requests made with this key. # Sign in to see your own test API key embedded in code samples. $CLIENT = Stripe::StripeClient.new('<>') def calculate_tax(items, currency) $CLIENT.v1.tax.calculations.create( currency: currency, customer_details: { address: { line1: '920 5th Ave', city: 'Seattle', state: 'WA', postal_code: '98104', country: 'US', }, address_source: 'shipping', }, line_items: items.map {|item| build_line_item(item) } ) end def build_line_item(item) { amount: item['amount'], \# Amount in cents reference: item['id'], # Unique reference for the item in the scope of the calculation } end # Securely calculate the order amount, including tax def calculate_order_amount(tax_calculation) # Calculate the order total with any exclusive taxes on the server to prevent # people from directly manipulating the amount on the client tax_calculation.amount_total end def calculate_tax(items, currency) $CLIENT.v1.tax.calculations.create( currency: currency, customer_details: { address: { line1: '920 5th Ave', city: 'Seattle', state: 'WA', postal_code: '98104', country: 'US', }, address_source: 'shipping', }, line_items: items.map {|item| build_line_item(item) } ) end def build_line_item(item) { amount: item['amount'], \# Amount in cents reference: item['id'], # Unique reference for the item in the scope of the calculation } end # Securely calculate the order amount, including tax def calculate_order_amount(tax_calculation) # Calculate the order total with any exclusive taxes on the server to prevent # people from directly manipulating the amount on the client tax_calculation.amount_total end \# Securely calculate the order amount def calculate_order_amount(_items) # Calculate the order total on the server to prevent # people from directly manipulating the amount on the client _items.sum {|h| h['amount']} end def charge_customer(customerId) \# Lookup the payment methods available for the customer payment_methods = $CLIENT.v1.payment_methods.list( customer: customerId, type: 'card' ) begin # Charge the customer and payment method immediately payment_intent = $CLIENT.v1.payment_intents.create( amount: 1099, currency: '{{CURRENCY}}', customer_account: customerId, payment_method: payment_methods.data[0]['id'], off_session: true, confirm: true ) rescue Stripe::CardError => e # Error code will be authentication_required if authentication is needed puts "Error is: \#{e.error.code}" payment_intent_id = e.error.payment_intent.id payment_intent = $CLIENT.v1.payment_intents.retrieve(payment_intent_id) puts payment_intent.id end end def charge_customer(customerId) \# Lookup the payment methods available for the customer-configured Account payment_methods = $CLIENT.v1.payment_methods.list( customer_account: customerId, type: 'card' ) begin # Charge the customer-configured Account and payment method immediately payment_intent = $CLIENT.v1.payment_intents.create( amount: 1099, currency: '{{CURRENCY}}', customer_account: customerId, payment_method: payment_methods.data[0]['id'], off_session: true, confirm: true ) rescue Stripe::CardError => e # Error code will be authentication_required if authentication is needed puts "Error is: \#{e.error.code}" payment_intent_id = e.error.payment_intent.id payment_intent = $CLIENT.v1.payment_intents.retrieve(payment_intent_id) puts payment_intent.id end end \# Alternatively, set up a webhook to listen for the payment_intent.succeeded event # and attach the PaymentMethod to a new Customer customer = $CLIENT.v1.customers.create \# Alternatively, set up a webhook to listen for the payment_intent.succeeded event # and attach the PaymentMethod to a new customer-configured Account account = $CLIENT.v2.core.accounts.create({ configuration: { customer: { capabilities: {automatic_indirect_tax: {requested: true}} } } }) \# Create a Tax Calculation for the items being sold tax_calculation = calculate_tax(data['items'], '{{CURRENCY}}') \# Create a PaymentIntent with amount and currency payment_intent = $CLIENT.v1.payment_intents.create( customer: customer['id'], setup_future_usage: 'off_session', amount: calculate_order_amount(tax_calculation), amount: calculate_order_amount(data['items']), currency: '{{CURRENCY}}', \# In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. automatic_payment_methods: { enabled: true, }, hooks: { inputs: { tax: { calculation: tax_calculation.id } } }, ) { clientSecret: payment_intent.client_secret, }.to_json \# Create a PaymentIntent with amount and currency payment_intent = $CLIENT.v1.payment_intents.create( customer_account: account['id'], setup_future_usage: 'off_session', amount: calculate_order_amount(tax_calculation), amount: calculate_order_amount(data['items']), currency: '{{CURRENCY}}', \# In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. automatic_payment_methods: { enabled: true, }, hooks: { inputs: { tax: { calculation: tax_calculation.id } } }, ) { clientSecret: payment_intent.client_secret, }.to_json import stripe \# This is a public sample test API key. # Don’t submit any personally identifiable information in requests made with this key. # Sign in to see your own test API key embedded in code samples. client = stripe.StripeClient('<>') import stripe \# This is a public sample test API key. # Don’t submit any personally identifiable information in requests made with this key. # Sign in to see your own test API key embedded in code samples. client = stripe.StripeClient('<>') def calculate_tax(items, currency): tax_calculation = client.v1.tax.calculations.create(params={ 'currency': currency, 'customer_details': { "address": { "line1": "920 5th Ave", "city": "Seattle", "state": "WA", "postal_code": "98104", "country": "US", }, "address_source": "shipping", }, 'line_items': list(map(build_line_item, items)), }) return tax_calculation def build_line_item(item): return { "amount": item["amount"], \# Amount in cents "reference": item["id"], # Unique reference for the item in the scope of the calculation } def calculate_tax(items, currency): tax_calculation = client.v1.tax.calculations.create({ "currency": currency, "customer_details": { "address": { "line1": "920 5th Ave", "city": "Seattle", "state": "WA", "postal_code": "98104", "country": "US", }, "address_source": "shipping", }, "line_items": list(map(build_line_item, items)), }) return tax_calculation def build_line_item(item): return { "amount": item["amount"], \# Amount in cents "reference": item["id"], # Unique reference for the item in the scope of the calculation } \# Securely calculate the order amount, including tax def calculate_order_amount(items, tax_calculation): # Replace this constant with a calculation of the order's amount # Calculate the order total with any exclusive taxes on the server to prevent # people from directly manipulating the amount on the client order_amount = 1400 order_amount += tax_calculation['tax_amount_exclusive'] return order_amount def calculate_order_amount(items): \# Replace this constant with a calculation of the order's amount # Calculate the order total on the server to prevent # people from directly manipulating the amount on the client return 1400 def charge_customer(customer_id): \# Lookup the payment methods available for the customer payment_methods = client.v1.payment_methods.list(params={ 'customer': customer_id, 'type': 'card', }) # Charge the customer and payment method immediately try: client.v1.payment_intents.create(params={ 'amount': 1099, 'currency': '{{CURRENCY}}', 'customer': customer_id, 'payment_method': payment_methods.data[0].id, 'off_session': True, 'confirm': True, }) except stripe.error.CardError as e: err = e.error # Error code will be authentication_required if authentication is needed print('Code is: %s' % err.code) payment_intent_id = err.payment_intent['id'] payment_intent = client.v1.payment_intents.retrieve(payment_intent_id) def charge_customer(customer_id): \# Lookup the payment methods available for the customer-configured Account payment_methods = stripe.PaymentMethod.list( customer_account=customer_id, type='card' ) # Charge the customer-configured Account and payment method immediately try: stripe.PaymentIntent.create( amount=1099, currency='{{CURRENCY}}', customer_account=customer_id, payment_method=payment_methods.data[0].id, off_session=True, confirm=True ) except stripe.error.CardError as e: err = e.error # Error code will be authentication_required if authentication is needed print('Code is: %s' % err.code) payment_intent_id = err.payment_intent['id'] payment_intent = client.v1.payment_intents.retrieve(payment_intent_id) \# Alternatively, set up a webhook to listen for the payment_intent.succeeded event # and attach the PaymentMethod to a new Customer customer = client.v1.customers.create() \# Alternatively, set up a webhook to listen for the payment_intent.succeeded event # and attach the PaymentMethod to a new customer-configured Account account = client.v2.core.accounts.create({ "configuration": { "customer": { "capabilities": {"automatic_indirect_tax": {"requested": True}} }, }, }) try: data = json.loads(request.data) \# Create a Tax Calculation for the items being sold tax_calculation = calculate_tax(data['items'], '{{CURRENCY}}') \# Create a PaymentIntent with the order amount and currency intent = client.v1.payment_intents.create(params={ 'customer': customer['id'], 'setup_future_usage': 'off_session', 'amount': calculate_order_amount(data['items'], tax_calculation), 'amount': calculate_order_amount(data['items']), 'currency': '{{CURRENCY}}', \# In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. 'automatic_payment_methods': { 'enabled': True, }, 'hooks': { 'inputs': { 'tax': { 'calculation': tax_calculation['id'] } } }, }) return jsonify({ 'clientSecret': intent['client_secret'] }) except Exception as e: return jsonify(error=str(e)), 403 try: data = json.loads(request.data) \# Create a Tax Calculation for the items being sold tax_calculation = calculate_tax(data['items'], '{{CURRENCY}}') \# Create a PaymentIntent with the order amount and currency intent = client.v1.payment_intents.create({ "customer_account": account['id'], "setup_future_usage": 'off_session', "amount": calculate_order_amount(data['items'], tax_calculation), "amount": calculate_order_amount(data['items']), "currency": '{{CURRENCY}}', \# In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. "automatic_payment_methods": { 'enabled': True, }, "hooks": { 'inputs': { 'tax': { 'calculation': tax_calculation['id'] } } }, }) return jsonify({ 'clientSecret': intent['client_secret'] }) except Exception as e: return jsonify(error=str(e)), 403 $stripe = new \Stripe\StripeClient($stripeSecretKey); function calculateTax($stripe, $items, $currency) { $taxCalculation = $stripe->tax->calculations->create([ 'currency' => $currency, 'customer_details' => [ 'address' => [ 'line1' => '920 5th Ave', 'city' => 'Seattle', 'state' => 'WA', 'postal_code' => '98104', 'country' => 'US', ], 'address_source' => 'shipping', ], 'line_items' => array_map('buildLineItem', $items), ]); return $taxCalculation; } function buildLineItem($item) { return [ 'amount' => $item->amount, // Amount in cents 'reference' => $item->id, // Unique reference for the item in the scope of the calculation ]; } // Securely calculate the order amount, including tax function calculateOrderAmount($taxCalculation) { // Calculate the order total with any exclusive taxes on the server to prevent // people from directly manipulating the amount on the client return $taxCalculation->amount_total; } function calculateOrderAmount(array $items): int { // Calculate the order total on the server to prevent // people from directly manipulating the amount on the client $total = 0; foreach($items as $item) { $total += $item->amount; } return $total; } // Alternatively, set up a webhook to listen for the payment_intent.succeeded event // and attach the PaymentMethod to a new Customer $customer = $stripe->customers->create(); // Alternatively, set up a webhook to listen for the payment_intent.succeeded event // and attach the PaymentMethod to a new customer-configured Account $account = $stripe->v2->core->accounts->create([ 'configuration' => [ 'customer' => [ 'capabilities' => [ 'automatic_indirect_tax' => [ 'requested' => true, ], ], ], ] ]); // Create a Tax Calculation for the items being sold $taxCalculation = calculateTax($stripe, $jsonObj->items, '{{CURRENCY}}'); // Create a PaymentIntent with amount and currency $paymentIntent = $stripe->paymentIntents->create([ 'customer' => $customer->id, 'setup_future_usage' => 'off_session', 'amount' => calculateOrderAmount($jsonObj->items, $taxCalculation), 'amount' => calculateOrderAmount($jsonObj->items), 'currency' => '{{CURRENCY}}', // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. 'automatic_payment_methods' => [ 'enabled' => true, ], 'hooks' => [ 'inputs' => [ 'tax' => [ 'calculation' => $taxCalculation->id ] ] ], ]); $output = [ 'clientSecret' => $paymentIntent->client_secret, ]; // Create a PaymentIntent with amount and currency $paymentIntent = $stripe->paymentIntents->create([ 'customer_account' => $account->id, 'setup_future_usage' => 'off_session', 'amount' => calculateOrderAmount($jsonObj->items, $taxCalculation), 'amount' => calculateOrderAmount($jsonObj->items), 'currency' => '{{CURRENCY}}', // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. 'automatic_payment_methods' => [ 'enabled' => true, ], 'hooks' => [ 'inputs' => [ 'tax' => [ 'calculation' => $taxCalculation->id ] ] ], ]); $output = [ 'clientSecret' => $paymentIntent->client_secret, ]; $stripe = new \Stripe\StripeClient($'<>'); // Lookup the payment methods available for the customer $paymentMethods = $stripe->paymentMethods->all([ 'customer' => $jsonObj->customer, 'type' => 'card' ]); // Charge the customer and payment method immediately $paymentIntent = $stripe->paymentIntents->create([ 'amount' => 1099, 'currency' => '{{CURRENCY}}', 'customer' => $jsonObj->customer, 'payment_method' => $paymentMethods->data[0]->id, 'off_session' => true, 'confirm' => true, ]); // Lookup the payment methods available for the customer-configured Account $paymentMethods = $stripe->paymentMethods->all([ 'customer_account' => $jsonObj->customer, 'type' => 'card' ]); // Charge the customer-configured Account and payment method immediately $paymentIntent = $stripe->paymentIntents->create([ 'amount' => 1099, 'currency' => '{{CURRENCY}}', 'customer_account' => $jsonObj->customer, 'payment_method' => $paymentMethods->data[0]->id, 'off_session' => true, 'confirm' => true, ]); $stripeSecretKey = '<>'; "github.com/stripe/stripe-go/v85" // This is a public sample test API key. // Don’t submit any personally identifiable information in requests made with this key. // Sign in to see your own test API key embedded in code samples. sc = stripe.NewClient("<>") func calculateTax(items []item, currency stripe.Currency) *stripe.TaxCalculation { var lineItems []*stripe.TaxCalculationCreateLineItemParams for _, item := range items { lineItems = append(lineItems, buildLineItem(item)) } taxCalculationParams := &stripe.TaxCalculationCreateParams{ Currency: stripe.String(string(currency)), CustomerDetails: &stripe.TaxCalculationCreateCustomerDetailsParams{ Address: &stripe.AddressParams{ Line1: stripe.String("920 5th Ave"), City: stripe.String("Seattle"), State: stripe.String("WA"), PostalCode: stripe.String("98104"), Country: stripe.String("US"), }, AddressSource: stripe.String("shipping"), }, LineItems: lineItems, } taxCalculation, _ := sc.V1TaxCalculations.Create(context.TODO(), taxCalculationParams) return taxCalculation } func buildLineItem(i item) *stripe.TaxCalculationCreateLineItemParams { return &stripe.TaxCalculationCreateLineItemParams{ Amount: stripe.Int64(i.Amount), // Amount in cents Reference: stripe.String(i.Id), // Unique reference for the item in the scope of the calculation } } func calculateTax(items []item, currency stripe.Currency) *stripe.TaxCalculation { var lineItems []*stripe.TaxCalculationCreateLineItemParams for _, item := range items { lineItems = append(lineItems, buildLineItem(item)) } taxCalculationParams := &stripe.TaxCalculationCreateParams{ Currency: stripe.String(string(currency)), CustomerDetails: &stripe.TaxCalculationCreateCustomerDetailsParams{ Address: &stripe.AddressParams{ Line1: stripe.String("920 5th Ave"), City: stripe.String("Seattle"), State: stripe.String("WA"), PostalCode: stripe.String("98104"), Country: stripe.String("US"), }, AddressSource: stripe.String("shipping"), }, LineItems: lineItems, } taxCalculation, _ := sc.V1TaxCalculations.Create(context.TODO(), taxCalculationParams) return taxCalculation } func buildLineItem(i item) *stripe.TaxCalculationCreateLineItemParams { return &stripe.TaxCalculationCreateLineItemParams{ Amount: stripe.Int64(i.Amount), // Amount in cents Reference: stripe.String(i.Id), // Unique reference for the item in the scope of the calculation } } // Securely calculate the order amount, including tax func calculateOrderAmount(taxCalculation *stripe.TaxCalculation) int64 { // Calculate the order total with any exclusive taxes on the server to prevent // people from directly manipulating the amount on the client return taxCalculation.AmountTotal } func calculateOrderAmount(items []item) int64 { // Calculate the order total on the server to prevent // people from directly manipulating the amount on the client total := int64(0) for _, item := range items { total += item.Amount } return total; } func chargeCustomer(CustomerID string) { // Look up the payment methods available for the customer params := &stripe.PaymentMethodListParams{ Customer: stripe.String(CustomerID), Type: stripe.String(stripe.PaymentMethodTypeCard), } var pm *stripe.PaymentMethod for p, err := range sc.V1PaymentMethods.List(context.TODO(), params).All(context.TODO()) { if err != nil { log.Printf("sc.V1Prices.List: %v", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } pm = p break } paymentIntentParams := &stripe.PaymentIntentCreateParams{ Amount: stripe.Int64(1099), Currency: stripe.String(string(stripe.Currency{{CURRENCY}})), Customer: stripe.String(CustomerID), PaymentMethod: stripe.String(pm.ID), Confirm: stripe.Bool(true), OffSession: stripe.Bool(true), } // Charge the customer and payment method immediately _, err := sc.V1PaymentIntents.Create(context.TODO(), paymentIntentParams) if err != nil { if stripeErr, ok := err.(*stripe.Error); ok { // Error code will be authentication_required if authentication is needed fmt.Printf("Error code: %v", stripeErr.Code) paymentIntentID := stripeErr.PaymentIntent.ID paymentIntent, _ := sc.V1PaymentIntents.Retrieve(context.TODO(), paymentIntentID, nil) fmt.Printf("PI: %v", paymentIntent.ID) } } } func chargeCustomer(CustomerID string) { // Look up the payment methods available for the customer-configured Account params := &stripe.PaymentMethodListParams{ CustomerAccount: stripe.String(CustomerID), Type: stripe.String(stripe.PaymentMethodTypeCard), } var pm *stripe.PaymentMethod for p, err := range sc.V1PaymentMethods.List(context.TODO(), params).All(context.TODO()) { if err != nil { log.Printf("sc.V1Prices.List: %v", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } pm = p break } paymentIntentParams := &stripe.PaymentIntentCreateParams{ Amount: stripe.Int64(1099), Currency: stripe.String(string(stripe.Currency{{CURRENCY}})), CustomerAccount: stripe.String(CustomerID), PaymentMethod: stripe.String(pm.ID), Confirm: stripe.Bool(true), OffSession: stripe.Bool(true), } // Charge the customer-configured Account and payment method immediately _, err := sc.V1PaymentIntents.Create(context.TODO(), paymentIntentParams) if err != nil { if stripeErr, ok := err.(*stripe.Error); ok { // Error code will be authentication_required if authentication is needed fmt.Printf("Error code: %v", stripeErr.Code) paymentIntentID := stripeErr.PaymentIntent.ID paymentIntent, _ := sc.V1PaymentIntents.Retrieve(context.TODO(), paymentIntentID, nil) fmt.Printf("PI: %v", paymentIntent.ID) } } } // Alternatively, set up a webhook to listen for the payment_intent.succeeded event // and attach the PaymentMethod to a new Customer custParams := &stripe.CustomerCreateParams{} cust, _ := sc.V1Customers.Create(context.TODO(), custParams) // Alternatively, set up a webhook to listen for the payment_intent.succeeded event // and attach the PaymentMethod to a new customer-configured Account acctParams := &stripe.V2CoreAccountCreateParams{ Configuration: &stripe.V2CoreAccountCreateConfigurationParams{ Customer: &stripe.V2CoreAccountCreateConfigurationCustomerParams{ Capabilities: &stripe.V2CoreAccountCreateConfigurationCustomerCapabilitiesParams{ AutomaticIndirectTax: &stripe.V2CoreAccountCreateConfigurationCustomerCapabilitiesAutomaticIndirectTaxParams{ Requested: stripe.Bool(true), }, }, }, }, } acct, _ := sc.V2CoreAccounts.Create(context.TODO(), acctParams) // Create a Tax Calculation for the items being sold taxCalculation := calculateTax(req.Items, "{{CURRENCY}}") // Create a PaymentIntent with amount and currency params := &stripe.PaymentIntentCreateParams{ Customer: stripe.String(cust.ID), SetupFutureUsage: stripe.String("off_session"), Amount: stripe.Int64(calculateOrderAmount(taxCalculation)), Amount: stripe.Int64(calculateOrderAmount(req.Items)), Currency: stripe.String(string(stripe.Currency{{CURRENCY}})), // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. AutomaticPaymentMethods: &stripe.PaymentIntentCreateAutomaticPaymentMethodsParams{ Enabled: stripe.Bool(true), }, } params.Hooks = &stripe.PaymentIntentCreateHooksParams{ Inputs: &stripe.PaymentIntentCreateHooksInputsParams{ Tax: &stripe.PaymentIntentCreateHooksInputsTaxParams{ Calculation: stripe.String(taxCalculation.ID), }, }, } pi, err := sc.V1PaymentIntents.Create(context.TODO(), params) if err != nil { log.Printf("sc.V1PaymentIntents.Create: %v", pi.ClientSecret) http.Error(w, err.Error(), http.StatusInternalServerError) log.Printf("sc.V1PaymentIntents.Create: %v", err) return } writeJSON(w, struct { ClientSecret string `json:"clientSecret"` }{ ClientSecret: pi.ClientSecret, }) // Create a PaymentIntent with amount and currency params := &stripe.PaymentIntentCreateParams{ CustomerAccount: stripe.String(acct.ID), SetupFutureUsage: stripe.String("off_session"), Amount: stripe.Int64(calculateOrderAmount(taxCalculation)), Amount: stripe.Int64(calculateOrderAmount(req.Items)), Currency: stripe.String(string(stripe.Currency{{CURRENCY}})), // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. AutomaticPaymentMethods: &stripe.PaymentIntentCreateAutomaticPaymentMethodsParams{ Enabled: stripe.Bool(true), }, } params.Hooks = &stripe.PaymentIntentCreateHooksParams{ Inputs: &stripe.PaymentIntentCreateHooksInputsParams{ Tax: &stripe.PaymentIntentCreateHooksInputsTaxParams{ Calculation: stripe.String(taxCalculation.ID), }, }, } pi, err := sc.V1PaymentIntents.Create(context.TODO(), params) log.Printf("pi.Create: %v", pi.ClientSecret) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) log.Printf("pi.Create: %v", err) return } writeJSON(w, struct { ClientSecret string `json:"clientSecret"` }{ ClientSecret: pi.ClientSecret, }) using Stripe.Tax; using System.Linq; // This is a public sample test API key. // Don’t submit any personally identifiable information in requests made with this key. // Sign in to see your own test API key embedded in code samples. services.AddSingleton(new StripeClient("<>")); private readonly StripeClient _client; public PaymentIntentApiController(StripeClient client) { _client = client; } // Alternatively, set up a webhook to listen for the payment_intent.succeeded event // and attach the PaymentMethod to a new Customer var customer = _client.V1.Customers.Create(new CustomerCreateOptions()); // Alternatively, set up a webhook to listen for the payment_intent.succeeded event // and attach the PaymentMethod to a new customer-configured Account var customerOptions = new Stripe.V2.Core.AccountCreateOptions { Configuration = new Stripe.V2.Core.AccountCreateConfigurationOptions { Customer = new Stripe.V2.Core.AccountCreateConfigurationCustomerOptions { Capabilities = new Stripe.V2.Core.AccountCreateConfigurationCustomerCapabilitiesOptions { AutomaticIndirectTax = new Stripe.V2.Core.AccountCreateConfigurationCustomerCapabilitiesAutomaticIndirectTaxOptions { Requested = true, }, }, } }, }; var account = _client.V2.Core.Accounts.Create(customerOptions); // Create a Tax Calculation for the items being sold var taxCalculation = CalculateTax(request.Items, "{{CURRENCY}}"); var paymentIntent = _client.V1.PaymentIntents.Create(new PaymentIntentCreateOptions { Customer = customer.Id, SetupFutureUsage = "off_session", CustomerAccount = account.Id, SetupFutureUsage = "off_session", Amount = CalculateOrderAmount(taxCalculation), Amount = CalculateOrderAmount(request.Items), Currency = "{{CURRENCY}}", // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. AutomaticPaymentMethods = new PaymentIntentAutomaticPaymentMethodsOptions { Enabled = true, }, Hooks = new PaymentIntentHooksOptions { Inputs = new PaymentIntentHooksInputsOptions { Tax = new PaymentIntentHooksInputsTaxOptions { Calculation = taxCalculation.Id, }, }, }, Metadata = new Dictionary { { "tax_calculation", taxCalculation.Id }, }, }); return Json(new { clientSecret = paymentIntent.ClientSecret }); // Securely calculate the order amount, including tax [NonAction] public long CalculateOrderAmount(Calculation taxCalculation) { // Calculate the order total with any exclusive taxes on the server to prevent // people from directly manipulating the amount on the client return taxCalculation.AmountTotal; } private long CalculateOrderAmount(Item[] items) { // Calculate the order total on the server to prevent // people from directly manipulating the amount on the client long total = 0; foreach (Item item in items) { total += item.Amount; } return total; } [NonAction] public Calculation CalculateTax(Item[] items, string currency) { var lineItems = items.Select(item => BuildLineItem(item)).ToList(); var calculationCreateOptions = new CalculationCreateOptions { Currency = currency, CustomerDetails = new CalculationCustomerDetailsOptions { Address = new AddressOptions { Line1 = "920 5th Ave", City = "Seattle", State = "WA", PostalCode = "98104", Country = "US", }, AddressSource = "shipping", }, LineItems = lineItems, }; var calculation = _client.V1.Tax.Calculations.Create(calculationCreateOptions); return calculation; } [NonAction] public CalculationLineItemOptions BuildLineItem(Item item) { return new CalculationLineItemOptions { Amount = item.Amount, // Amount in cents Reference = item.Id, // Unique reference for the item in the scope of the calculation }; } public void ChargeCustomer(string customerId) { // Lookup the payment methods available for the customer var availableMethods = _client.V1.PaymentMethods.List(new PaymentMethodListOptions { Customer = customerId, Type = "card", }); try { // Charge the customer and payment method immediately var paymentIntent = _client.V1.PaymentIntents.Create(new PaymentIntentCreateOptions { Amount = 1099, Currency = "{{CURRENCY}}", Customer = customerId, PaymentMethod = availableMethods.Data[0].Id, OffSession = true, Confirm = true }); } catch (StripeException e) { switch (e.StripeError.ErrorType) { case "card_error": // Error code will be authentication_required if authentication is needed Console.WriteLine("Error code: " + e.StripeError.Code); var paymentIntentId = e.StripeError.PaymentIntent.Id; var paymentIntent = _client.V1.PaymentIntents.Get(paymentIntentId); Console.WriteLine(paymentIntent.Id); break; default: break; } } } public void ChargeCustomer(string customerId) { // Lookup the payment methods available for the customer-configured Account var availableMethods = _client.V1.PaymentMethods.List(new PaymentMethodListOptions { CustomerAccount = customerId, Type = "card", }); try { // Charge the customer-configured Account and payment method immediately var paymentIntent = _client.V1.PaymentIntents.Create(new PaymentIntentCreateOptions { Amount = 1099, Currency = "{{CURRENCY}}", CustomerAccount = customerId, PaymentMethod = availableMethods.Data[0].Id, OffSession = true, Confirm = true }); } catch (StripeException e) { switch (e.StripeError.ErrorType) { case "card_error": // Error code will be authentication_required if authentication is needed Console.WriteLine("Error code: " + e.StripeError.Code); var paymentIntentId = e.StripeError.PaymentIntent.Id; var paymentIntent = _client.V1.PaymentIntents.Get(paymentIntentId); Console.WriteLine(paymentIntent.Id); break; default: break; } } } import com.stripe.model.Customer; import com.stripe.param.CustomerCreateParams; import com.stripe.model.v2.core.Account; import com.stripe.param.v2.core.AccountCreateParams; import com.stripe.model.PaymentMethod; import com.stripe.model.StripeCollection; import com.stripe.param.PaymentMethodListParams; import java.util.Arrays; import com.stripe.model.tax.Calculation; import com.stripe.param.tax.CalculationCreateParams; import com.stripe.param.tax.CalculationCreateParams.CustomerDetails; import com.stripe.param.tax.CalculationCreateParams.CustomerDetails.Address; import com.stripe.param.tax.CalculationCreateParams.CustomerDetails.AddressSource; import com.stripe.param.tax.CalculationCreateParams.LineItem; static Calculation calculateTax(List items, String currency) throws StripeException { List lineItems = items.stream() .map(Server::buildLineItem) .collect(Collectors.toList()); CalculationCreateParams.Builder createParamsBuilder = CalculationCreateParams.builder() .setCurrency(currency) .setCustomerDetails(CustomerDetails.builder() .setAddress(Address.builder() .setLine1("920 5th Ave") .setCity("Seattle") .setState("WA") .setPostalCode("98104") .setCountry("US") .build()) .setAddressSource(AddressSource.SHIPPING) .build()) .addAllLineItem(lineItems); return client.v1().tax().calculations().create(createParamsBuilder.build()); } static LineItem buildLineItem(CreatePaymentItem item) { return LineItem.builder() .setAmount(item.getAmount()) // Amount in cents .setReference(item.getId()) // Unique reference for the item in the scope of the calculation .build(); } // Securely calculate the order amount, including tax static long calculateOrderAmount(Calculation taxCalculation) { // Calculate the order total with any exclusive taxes on the server to prevent // people from directly manipulating the amount on the client return taxCalculation.getAmountTotal(); } static int calculateOrderAmount(CreatePaymentItem[] items) { // Calculate the order total on the server to prevent // people from directly manipulating the amount on the client int total = 0; for (CreatePaymentItem item : items) { total += item.getAmount(); } return total; } // Call this function with the ID of the Customer you want to charge static void chargeCustomer(String customerId) throws StripeException { // Lookup the payment methods available for the customer PaymentMethodListParams listParams = new PaymentMethodListParams.Builder().setCustomer(customerId) .setType(PaymentMethodListParams.Type.CARD).build(); StripeCollection paymentMethods = client.v1().paymentMethods().list(listParams); PaymentIntentCreateParams createParams = new PaymentIntentCreateParams.Builder().setCurrency("{{CURRENCY}}") .setAmount(new Long(1099)) .setPaymentMethod(paymentMethods.getData().get(0).getId()) .setCustomer(customerId) .setConfirm(true) .setOffSession(true) .build(); try { // Charge the customer and payment method immediately PaymentIntent paymentIntent = client.v1().paymentIntents().create(createParams); } catch (CardException e) { // Error code will be authentication_required if authentication is needed System.out.println("Error code is : " + e.getCode()); String paymentIntentId = e.getStripeError().getPaymentIntent().getId(); PaymentIntent paymentIntent = client.v1().paymentIntents().retrieve(paymentIntentId); System.out.println(paymentIntent.getId()); } } // Call this function with the ID of the customer-configured Account you want to charge static void chargeCustomer(String customerId) throws StripeException { // Lookup the payment methods available for the customer-configured Account PaymentMethodListParams listParams = new PaymentMethodListParams.Builder().setCustomerAccount(customerId) .setType(PaymentMethodListParams.Type.CARD).build(); StripeCollection paymentMethods = client.v1().paymentMethods().list(listParams); PaymentIntentCreateParams createParams = new PaymentIntentCreateParams.Builder().setCurrency("{{CURRENCY}}") .setAmount(new Long(1099)) .setPaymentMethod(paymentMethods.getData().get(0).getId()) .setCustomerAccount(customerId) .setConfirm(true) .setOffSession(true) .build(); try { // Charge the customer-configured Account and payment method immediately PaymentIntent paymentIntent = client.v1().paymentIntents().create(createParams); } catch (CardException e) { // Error code will be authentication_required if authentication is needed System.out.println("Error code is : " + e.getCode()); String paymentIntentId = e.getStripeError().getPaymentIntent().getId(); PaymentIntent paymentIntent = client.v1().paymentIntents().retrieve(paymentIntentId); System.out.println(paymentIntent.getId()); } } // This is a public sample test API key. // Don’t submit any personally identifiable information in requests made with this key. // Sign in to see your own test API key embedded in code samples. public static StripeClient client = new StripeClient("<>"); public static void main(String[] args) { port(4242); staticFiles.externalLocation(Paths.get("public").toAbsolutePath().toString()); // Alternatively, set up a webhook to listen for the payment_intent.succeeded event // and attach the PaymentMethod to a new Customer CustomerCreateParams customerParams = new CustomerCreateParams.Builder().build(); Customer customer = client.v1().customers().create(customerParams); // Alternatively, set up a webhook to listen for the payment_intent.succeeded event // and attach the PaymentMethod to a new customer-configured Account AccountCreateParams accountParams = AccountCreateParams .builder() .setConfiguration( AccountCreateParams.Configuration.builder() .setCustomer( AccountCreateParams.Configuration.Customer.builder() .setCapabilities( AccountCreateParams.Configuration.Customer.Capabilities.builder() .setAutomaticIndirectTax( AccountCreateParams.Configuration.Customer.Capabilities.AutomaticIndirectTax.builder() .setRequested(true) .build() ) .build() ) .build() ) .build() ) .build(); Account account = client.v2().core().accounts().create(accountParams); CreatePayment postBody = gson.fromJson(request.body(), CreatePayment.class); // Create a Tax Calculation for the items being sold Calculation taxCalculation = calculateTax(Arrays.asList(postBody.getItems()), "{{CURRENCY}}"); PaymentIntentCreateParams params = PaymentIntentCreateParams.builder() .setCustomerAccount(account.getId()) .setSetupFutureUsage(PaymentIntentCreateParams.SetupFutureUsage.OFF_SESSION) .setAmount(calculateOrderAmount(taxCalculation)) .setAmount(new Long(calculateOrderAmount(postBody.getItems()))) .setCurrency("{{CURRENCY}}") // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. .setAutomaticPaymentMethods( PaymentIntentCreateParams.AutomaticPaymentMethods .builder() .setEnabled(true) .build() ) .setHooks( PaymentIntentCreateParams.Hooks .builder() .setInputs( PaymentIntentCreateParams.Hooks.Inputs .builder() .setTax( PaymentIntentCreateParams.Hooks.Inputs.Tax .builder() .setCalculation(taxCalculation.getId()) .build() ) .build() ) .build() ) .build(); // Create a PaymentIntent with the order amount and currency PaymentIntent paymentIntent = client.v1().paymentIntents().create(params); CreatePaymentResponse paymentResponse = new CreatePaymentResponse(paymentIntent.getClientSecret(), paymentIntent.getId()); return gson.toJson(paymentResponse); CreatePayment postBody = gson.fromJson(request.body(), CreatePayment.class); // Create a Tax Calculation for the items being sold Calculation taxCalculation = calculateTax(Arrays.asList(postBody.getItems()), "{{CURRENCY}}"); PaymentIntentCreateParams params = PaymentIntentCreateParams.builder() .setCustomerAccount(customer.getId()) .setSetupFutureUsage(PaymentIntentCreateParams.SetupFutureUsage.OFF_SESSION) .setAmount(calculateOrderAmount(taxCalculation)) .setAmount(new Long(calculateOrderAmount(postBody.getItems()))) .setCurrency("{{CURRENCY}}") // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. .setAutomaticPaymentMethods( PaymentIntentCreateParams.AutomaticPaymentMethods .builder() .setEnabled(true) .build() ) .setHooks( PaymentIntentCreateParams.Hooks .builder() .setInputs( PaymentIntentCreateParams.Hooks.Inputs .builder() .setTax( PaymentIntentCreateParams.Hooks.Inputs.Tax .builder() .setCalculation(taxCalculation.getId()) .build() ) .build() ) .build() ) .build(); // Create a PaymentIntent with the order amount and currency PaymentIntent paymentIntent = client.v1().paymentIntents().create(params); CreatePaymentResponse paymentResponse = new CreatePaymentResponse(paymentIntent.getClientSecret(), paymentIntent.getId()); return gson.toJson(paymentResponse); import React, { useState, useEffect } from "react"; import { loadStripe } from "@stripe/stripe-js"; import { Elements } from "@stripe/react-stripe-js"; // Make sure to call loadStripe outside of a component’s render to avoid // recreating the Stripe object on every render. // This is a public sample test API key. // Don’t submit any personally identifiable information in requests made with this key. // Sign in to see your own test API key embedded in code samples. const stripePromise = loadStripe("<>"); useEffect(() => { // Create PaymentIntent as soon as the page loads fetch("/create-payment-intent", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ items: [{ id: "xl-tshirt", amount: 1000 }] }), }) .then((res) => res.json()) .then((data) => setClientSecret(data.clientSecret)); }, []); useEffect(() => { // Create PaymentIntent as soon as the page loads fetch("/create.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ items: [{ id: "xl-tshirt", amount: 1000 }] }), }) .then((res) => res.json()) .then((data) => setClientSecret(data.clientSecret)); }, []); const appearance = { {{APPEARANCE}} }; {clientSecret && ( } /> } /> )} const clientSecret = new URLSearchParams(window.location.search).get( "payment_intent_client_secret" ); if (!clientSecret) { return; } stripe.retrievePaymentIntent(clientSecret).then(({paymentIntent}) => { if (!paymentIntent) { return; } setStatus(paymentIntent.status); setIntentId(paymentIntent.id); }); const stripe = useStripe(); const elements = useElements(); const [email, setEmail] = useState(''); const [message, setMessage] = useState(null); const [isLoading, setIsLoading] = useState(false); const { error } = await stripe.confirmPayment({ elements, confirmParams: { // Make sure to change this to your payment completion page return_url: "http://localhost:3000/complete", receipt_email: email, }, }); // This point will only be reached if there is an immediate error when // confirming the payment. Otherwise, your customer will be redirected to // your `return_url`. For some payment methods like iDEAL, your customer will // be redirected to an intermediate site first to authorize the payment, then // redirected to the `return_url`. if (error.type === "card_error" || error.type === "validation_error") { setMessage(error.message); } else { setMessage("An unexpected error occurred."); } setIsLoading(false); setEmail(e.target.value)} placeholder="Enter email address" /> #email { border-radius: 6px; margin-bottom: 16px; padding: 12px; border: 1px solid rgba(50, 50, 93, 0.1); max-height: 44px; font-size: 16px; width: 100%; background: white; box-sizing: border-box; }
const stripe = Stripe("<>"); // Fetches a payment intent and captures the client secret async function initialize() { const response = await fetch("/create-payment-intent", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ items }), }); const { clientSecret } = await response.json(); const appearance = { {{APPEARANCE}} }; elements = stripe.elements({ appearance, clientSecret }); const paymentElementOptions = { layout: "accordion", }; const paymentElement = elements.create("payment", paymentElementOptions); paymentElement.mount("#payment-element"); } // Fetches a payment intent and captures the client secret async function initialize() { const { clientSecret } = await fetch("/create.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ items }), }).then((r) => r.json()); elements = stripe.elements({ clientSecret }); const paymentElementOptions = { layout: "accordion", }; const paymentElement = elements.create("payment", paymentElementOptions); paymentElement.mount("#payment-element"); } async function handleSubmit(e) { e.preventDefault(); setLoading(true); const { error } = await stripe.confirmPayment({ elements, confirmParams: { // Make sure to change this to your payment completion page return_url: "http://localhost:4242/complete.html", receipt_email: document.getElementById("email").value, }, }); // This point will only be reached if there is an immediate error when // confirming the payment. Otherwise, your customer will be redirected to // your `return_url`. For some payment methods like iDEAL, your customer will // be redirected to an intermediate site first to authorize the payment, then // redirected to the `return_url`. if (error.type === "card_error" || error.type === "validation_error") { showMessage(error.message); } else { showMessage("An unexpected error occurred."); } setLoading(false); } async function handleSubmit(e) { e.preventDefault(); setLoading(true); const { error } = await stripe.confirmPayment({ elements, confirmParams: { // Make sure to change this to your payment completion page return_url: "http://localhost:4242/complete.html", receipt_email: document.getElementById("email").value, }, }); // This point will only be reached if there is an immediate error when // confirming the payment. Otherwise, your customer will be redirected to // your `return_url`. For some payment methods like iDEAL, your customer will // be redirected to an intermediate site first to authorize the payment, then // redirected to the `return_url`. if (error.type === "card_error" || error.type === "validation_error") { showMessage(error.message); } else { showMessage("An unexpected error occurred."); } setLoading(false); } #email { border-radius: 6px; margin-bottom: 16px; padding: 12px; border: 1px solid rgba(50, 50, 93, 0.1); max-height: 44px; font-size: 16px; width: 100%; background: white; box-sizing: border-box; } const stripe = Stripe("<>"); // Fetches the payment intent status after payment submission async function checkStatus() { const clientSecret = new URLSearchParams(window.location.search).get( "payment_intent_client_secret" ); if (!clientSecret) { setErrorState(); return; } const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret); setPaymentDetails(paymentIntent); } import { PaymentElement, useStripe, useElements, Elements } from '@stripe/react-stripe-js' import { loadStripe } from '@stripe/stripe-js' // Make sure to call loadStripe outside of a component’s render to avoid // recreating the Stripe object on every render. // This is your test publishable API key. const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY) const stripe = useStripe(); const elements = useElements(); const [email, setEmail] = useState(''); const [message, setMessage] = useState(null); const [isLoading, setIsLoading] = useState(false); const { error } = await stripe.confirmPayment({ elements, confirmParams: { // Make sure to change this to your payment completion page return_url: "http://localhost:3000/success", receipt_email: email, }, }); // This point will only be reached if there is an immediate error when // confirming the payment. Otherwise, your customer will be redirected to // your `return_url`. For some payment methods like iDEAL, your customer will // be redirected to an intermediate site first to authorize the payment, then // redirected to the `return_url`. if (error.type === "card_error" || error.type === "validation_error") { setMessage(error.message); } else { setMessage("An unexpected error occurred."); } setIsLoading(false); setEmail(e.target.value)} placeholder="Enter email address" /> const appearance = { {{APPEARANCE}} }; const { payment_intent: paymentIntentId } = await searchParams if (!paymentIntentId) redirect('/') const paymentIntent = await stripe.paymentIntents.retrieve(paymentIntentId) if (!paymentIntent) redirect('/') const { status } = paymentIntent \# 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 const calculateTax = async (items, currency) => { const taxCalculation = await stripe.tax.calculations.create({ currency, customer_details: { address: { line1: "920 5th Ave", city: "Seattle", state: "WA", postal_code: "98104", country: "US", }, address_source: "shipping", }, line_items: items.map((item) => buildLineItem(item)), }); return taxCalculation; }; const buildLineItem = (item) => { return { amount: item.amount, // Amount in cents reference: item.id, // Unique reference for the item in the scope of the calculation }; }; // Securely calculate the order amount, including tax const calculateOrderAmount = (items, taxCalculation) => { // Replace this constant with a calculation of the order's amount // Calculate the order total with any exclusive taxes on the server to prevent // people from directly manipulating the amount on the client let orderAmount = 1400; orderAmount += taxCalculation.tax_amount_exclusive; return orderAmount; }; const calculateOrderAmount = (items) => { // Replace this constant with a calculation of the order's amount // Calculate the order total on the server to prevent // people from directly manipulating the amount on the client return 1400; }; const chargeCustomer = async (customerId) => { // Lookup the payment methods available for the customer const paymentMethods = await stripe.paymentMethods.list({ customer: customerId, type: "card", }); try { // Charge the customer and payment method immediately const paymentIntent = await stripe.paymentIntents.create({ amount: 1099, currency: "eur", customer: customerId, payment_method: paymentMethods.data[0].id, off_session: true, confirm: true, }); } catch (err) { // Error code will be authentication_required if authentication is needed console.log("Error code is: ", err.code); const paymentIntentRetrieved = await stripe.paymentIntents.retrieve(err.raw.payment_intent.id); console.log("PI retrieved: ", paymentIntentRetrieved.id); } }; // Alternatively, set up a webhook to listen for the payment_intent.succeeded event // and attach the PaymentMethod to a new Customer const customer = await stripe.customers.create(); const items = [{ id: 'xl-tshirt', amount: 1000 }] const taxCalculation = await calculateTax(items, "eur"); const amount = await calculateOrderAmount(items, taxCalculation); // Create PaymentIntent as soon as the page loads const { client_secret: clientSecret } = await stripe.paymentIntents.create({ customer: customer.id, setup_future_usage: "off_session", amount, amount: calculateOrderAmount([{ id: 'xl-tshirt' }]), currency: 'eur', // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. automatic_payment_methods: { enabled: true, }, metadata: { tax_calculation: taxCalculation.id }, }) import 'server-only'; import Stripe from 'stripe'; export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY); export async function POST(req) { import StripePaymentSheet private lazy var addressViewController: AddressViewController? = { return AddressViewController(configuration: self.addressConfiguration, delegate: self) }() private var addressDetails: AddressViewController.AddressDetails? private var addressConfiguration: AddressViewController.Configuration { return AddressViewController.Configuration(additionalFields: .init(phone: .optional)) } private lazy var addressButton: UIButton = { let button = UIButton(type: .custom) button.setTitle("Add shipping address", for: .normal) button.backgroundColor = .systemIndigo button.layer.cornerRadius = 5 button.contentEdgeInsets = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12) button.addTarget(self, action: #selector(didTapShippingAddressButton), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false return button }() StripeAPI.defaultPublishableKey = "<>" view.addSubview(addressButton) NSLayoutConstraint.activate([ addressButton.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 16), addressButton.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -16), addressButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -80) ]) func fetchPaymentIntent() { let url = Self.backendURL.appendingPathComponent("/create-payment-intent") let shoppingCartContent: [String: Any] = [ "items": [ ["id": "xl-shirt"] ["id": "xl-shirt", "amount": 1000] ] ] var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = try? JSONSerialization.data(withJSONObject: shoppingCartContent) let task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (data, response, error) in guard let response = response as? HTTPURLResponse, response.statusCode == 200, let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any], let clientSecret = json["clientSecret"] as? String else { let message = error?.localizedDescription ?? "Failed to decode response from server." self?.displayAlert(title: "Error loading page", message: message) return } print("Created PaymentIntent") self?.paymentIntentClientSecret = clientSecret DispatchQueue.main.async { self?.payButton.isEnabled = true } }) task.resume() } var configuration = PaymentSheet.Configuration() configuration.merchantDisplayName = "Example, Inc." configuration.allowsDelayedPaymentMethods = true configuration.primaryButtonColor = UIColor(red: 1.0, green: 0.82, blue: 0.04, alpha: 1.0) configuration.applePay = .init( merchantId: "com.example.appname", merchantCountryCode: "US" ) configuration.shippingDetails = { [weak self] in return self?.addressDetails } let paymentSheet = PaymentSheet( paymentIntentClientSecret: paymentIntentClientSecret, configuration: configuration) paymentSheet.present(from: self) { [weak self] (paymentResult) in switch paymentResult { case .completed: self?.displayAlert(title: "Payment complete!") case .canceled: print("Payment canceled!") case .failed(let error): self?.displayAlert(title: "Payment failed", message: error.localizedDescription) } @objc func didTapShippingAddressButton() { present(UINavigationController(rootViewController: addressViewController!), animated: true) } // MARK: - AddressViewControllerDelegate extension CheckoutViewController: AddressViewControllerDelegate { func addressViewControllerDidFinish(_ addressViewController: AddressViewController, with address: AddressViewController.AddressDetails?) { addressViewController.dismiss(animated: true) self.addressDetails = address } } NSCameraUsageDescription Allow the app to scan cards. PaymentConfiguration.init( applicationContext, "<>" ) import androidx.compose.foundation.layout.Column import androidx.compose.ui.platform.LocalContext import com.stripe.android.PaymentConfiguration import com.stripe.android.paymentsheet.addresselement.AddressDetails import com.stripe.android.paymentsheet.addresselement.AddressLauncher import com.stripe.android.paymentsheet.addresselement.AddressLauncher.AdditionalFieldsConfiguration import com.stripe.android.paymentsheet.addresselement.AddressLauncherResult import com.stripe.android.paymentsheet.addresselement.rememberAddressLauncher private val addressConfiguration = AddressLauncher.Configuration.Builder() .additionalFields( AdditionalFieldsConfiguration( AdditionalFieldsConfiguration.FieldConfiguration.REQUIRED ) ) .allowedCountries(setOf("US", "CA", "GB")) .title("Shipping Address") .googlePlacesApiKey("(optional) YOUR KEY HERE") .build() when (paymentResult) { is PaymentSheetResult.Completed -> showToast("Payment complete!") is PaymentSheetResult.Canceled -> showToast("Payment canceled!") is PaymentSheetResult.Failed -> { error = paymentResult.error.localizedMessage ?: paymentResult.error.message } } val context = LocalContext.current var shippingDetails by remember { mutableStateOf(null) } val addressLauncher = rememberAddressLauncher { result -> when (result) { is AddressLauncherResult.Succeeded -> { shippingDetails = result.address showToast("Address selection complete!") } is AddressLauncherResult.Canceled -> showToast("Address selection canceled!") } } Column( modifier = Modifier.fillMaxWidth() ) { AddressButton { addressLauncher.present( publishableKey = PaymentConfiguration.getInstance(context).publishableKey, configuration = addressConfiguration ) } PayButton( enabled = paymentIntentClientSecret != null, onClick = { paymentIntentClientSecret?.let { onPayClicked( paymentSheet = paymentSheet, paymentIntentClientSecret = it, shippingDetails = shippingDetails, ) } } ) } PayButton( enabled = paymentIntentClientSecret != null, onClick = { paymentIntentClientSecret?.let { onPayClicked( paymentSheet = paymentSheet, paymentIntentClientSecret = it, ) } } ) @Composable private fun AddressButton( onClick: () -> Unit ) { Button( modifier = Modifier.fillMaxWidth(), onClick = onClick ) { Text("Add shipping address") } } private suspend fun fetchPaymentIntent(): Result = suspendCoroutine { continuation -> val url = "$BACKEND_URL/create-payment-intent" val shoppingCartContent = """ { "items": [ {"id":"xl-tshirt"} {"id":"xl-tshirt", "amount":1000} ] } """ val mediaType = "application/json; charset=utf-8".toMediaType() val body = shoppingCartContent.toRequestBody(mediaType) val request = Request.Builder() .url(url) .post(body) .build() OkHttpClient() .newCall(request) .enqueue(object: Callback { override fun onFailure(call: Call, e: IOException) { continuation.resume(Result.failure(e)) } override fun onResponse(call: Call, response: Response) { if (!response.isSuccessful) { continuation.resume(Result.failure(Exception(response.message))) } else { val clientSecret = extractClientSecretFromResponse(response) clientSecret?.let { secret -> continuation.resume(Result.success(secret)) } ?: run { val error = Exception("Could not find payment intent client secret in response!") continuation.resume(Result.failure(error)) } } } }) } private fun extractClientSecretFromResponse(response: Response): String? { return try { val responseData = response.body?.string() val responseJson = responseData?.let { JSONObject(it) } ?: JSONObject() responseJson.getString("clientSecret") } catch (exception: JSONException) { null } } shippingDetails: AddressDetails?, val configuration = PaymentSheet.Configuration.Builder(merchantDisplayName = "Example, Inc.") .shippingDetails(shippingDetails) .allowsDelayedPaymentMethods(true) .appearance( PaymentSheet.Appearance( primaryButton = PaymentSheet.PrimaryButton( colorsLight = PaymentSheet.PrimaryButtonColors( background = Color(red = 248, green = 72, blue = 94), onBackground = Color.White, border = Color.Unspecified ) ) ) ) .googlePay( PaymentSheet.GooglePayConfiguration( environment = PaymentSheet.GooglePayConfiguration.Environment.Test, countryCode = "US" ) ) .build() // Present Payment Sheet paymentSheet.presentWithPaymentIntent(paymentIntentClientSecret, configuration) PaymentConfiguration.init( getApplicationContext(), "<>" ); import com.stripe.android.paymentsheet.addresselement.AddressDetails; import com.stripe.android.paymentsheet.addresselement.AddressLauncher; import com.stripe.android.paymentsheet.addresselement.AddressLauncherResult; private AddressLauncher addressLauncher; private AddressDetails shippingDetails; private Button addressButton; private final AddressLauncher.Configuration configuration = new AddressLauncher.Configuration.Builder() .additionalFields( new AddressLauncher.AdditionalFieldsConfiguration( AddressLauncher.AdditionalFieldsConfiguration.FieldConfiguration.REQUIRED ) ) .allowedCountries(new HashSet<>(Arrays.asList("US", "CA", "GB"))) .title("Shipping Address") .googlePlacesApiKey("(optional) YOUR KEY HERE") .build(); // Hook up the address button addressButton = findViewById(R.id.address_button); addressButton.setOnClickListener(this::onAddressClicked); addressLauncher = new AddressLauncher(this, this::onAddressLauncherResult); private void fetchPaymentIntent() { final String shoppingCartContent = "{\"items\": [ {\"id\":\"xl-tshirt\"}]}"; final String shoppingCartContent = "{\"items\": [ {\"id\":\"xl-tshirt\", \"amount\":1000}]}"; final RequestBody requestBody = RequestBody.create( shoppingCartContent, MediaType.get("application/json; charset=utf-8") ); Request request = new Request.Builder() .url(BACKEND_URL + "/create-payment-intent") .post(requestBody) .build(); new OkHttpClient() .newCall(request) .enqueue(new Callback() { @Override public void onFailure(@NonNull Call call, @NonNull IOException e) { showAlert("Failed to load data", "Error: " + e.toString()); } @Override public void onResponse( @NonNull Call call, @NonNull Response response ) throws IOException { if (!response.isSuccessful()) { showAlert( "Failed to load page", "Error: " + response.toString() ); } else { final JSONObject responseJson = parseResponse(response.body()); paymentIntentClientSecret = responseJson.optString("clientSecret"); runOnUiThread(() -> payButton.setEnabled(true)); Log.i(TAG, "Retrieved PaymentIntent"); } } }); } PaymentSheet.Configuration configuration = new PaymentSheet.Configuration.Builder("Example, Inc.") .allowsDelayedPaymentMethods(true) .primaryButtonColor(ColorStateList.valueOf(Color.rgb(248, 72, 94))) .googlePay(new PaymentSheet.GooglePayConfiguration( PaymentSheet.GooglePayConfiguration.Environment.Test, "US")) .build(); // Present Payment Sheet paymentSheet.presentWithPaymentIntent(paymentIntentClientSecret, configuration); private void onAddressClicked(View view) { AddressLauncher.Configuration addressConfiguration = new AddressLauncher.Configuration.Builder().address(shippingDetails).build(); String publishableKey = PaymentConfiguration.getInstance(this.getApplicationContext()).getPublishableKey(); addressLauncher.present( publishableKey, addressConfiguration ); } if (paymentSheetResult instanceof PaymentSheetResult.Completed) { showToast("Payment complete!"); } else if (paymentSheetResult instanceof PaymentSheetResult.Canceled) { Log.i(TAG, "Payment canceled!"); } else if (paymentSheetResult instanceof PaymentSheetResult.Failed) { Throwable error = ((PaymentSheetResult.Failed) paymentSheetResult).getError(); showAlert("Payment failed", error.getLocalizedMessage()); } private void onAddressLauncherResult(AddressLauncherResult result) { // TODO: Handle result and update your UI if (result instanceof AddressLauncherResult.Succeeded) { shippingDetails = ((AddressLauncherResult.Succeeded) result).getAddress(); } else if (result instanceof AddressLauncherResult.Canceled) { // TODO: Handle cancel } } { "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" ] } } require github.com/stripe/stripe-go/v85 v85.0.0 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 { "name": "stripe-sample", "version": "0.2.0", "license": "ISC", "dependencies": { "@stripe/react-stripe-js": "^3.7.0", "@stripe/stripe-js": "^7.3.0", "express": "^4.21.0", "react": "^18.3.1", "react-dom": "^18.3.1", "react-router-dom": "^6.26.2", "react-scripts": "^5.0.1", "stripe": "^16.12.0" }, "devDependencies": { "@babel/plugin-transform-private-property-in-object": "^7.25.7", "concurrently": "^9.0.1" }, "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-router-dom": "^6.26.1", "react-scripts": "^5.0.1" }, "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" ] } } 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 ~~~ 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) \## API Keys This code sample uses a public sample test API key. Don’t submit any personally identifiable information in requests made with this key. The "View details" link to see the PaymentIntent details in the Dashboard won't work until you use your own test [API key](https://docs.stripe.com/keys). 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. Download and run the [Stripe CLI](https://stripe.com/docs/stripe-cli). The Stripe CLI is a developer tool that helps you build, test, and manage your integration with Stripe directly from the command line. ~~~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 ~~~ ### Instala la biblioteca Stripe Node Instala el paquete e impórtalo a tu código. Como alternativa, si estás empezando de cero y necesitas un archivo package.json, descarga los archivos del proyecto con el enlace de descarga que encontrarás en el editor de código. #### npm Instala la biblioteca: ```bash npm install --save stripe ``` #### GitHub O descarga directamente el código fuente de la biblioteca stripe-node [desde GitHub](https://github.com/stripe/stripe-node). ### Instala la biblioteca Stripe Ruby Instala la gema Ruby de Stripe y solicítala en tu código. Como alternativa, si estás empezando de cero y necesitas un Gemfile, descarga los archivos del proyecto con el enlace de descarga que encontrarás en el editor de código. #### Terminal Instala la gema: ```bash gem install stripe ``` #### Bundler Añade esta línea a tu Gemfile: ```bash gem 'stripe' ``` #### GitHub O descarga el código fuente de la gema stripe-ruby directamente [desde GitHub](https://github.com/stripe/stripe-ruby). ### Instala la biblioteca de Stripe Java Añade la dependencia a tu diseño e importa la biblioteca. Como alternativa, si estás empezando de cero y necesitas un archivo pom.xml de muestra (para Maven), descarga los archivos del proyecto con el enlace de descarga que encontrarás en el editor de código. #### Maven Añade la dependencia siguiente 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 Añade 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). ### Instala el paquete Stripe Python Instala el paquete de Stripe e impórtalo a tu código. Como alternativa, si estás empezando de cero y necesitas un archivo requirements.txt, descarga los archivos del proyecto con el enlace de descarga que encontrarás en el editor de código. #### pip Instala el paquete a través de pip: ```bash pip3 install stripe ``` #### GitHub Descarga directamente el código fuente de la biblioteca stripe-python [desde GitHub](https://github.com/stripe/stripe-python). ### Instala la biblioteca Stripe PHP Utiliza Composer para instalar la biblioteca e inicializa la clave secreta de tu API. Como alternativa, si estás empezando de cero y necesitas un archivo composer.json, descarga los archivos con el enlace de descarga que encontrarás en el editor de código. #### Composer Instala la biblioteca: ```bash composer require stripe/stripe-php ``` #### GitHub O descarga directamente el código fuente de la biblioteca stripe-php [desde GitHub](https://github.com/stripe/stripe-php). ### Configura tu servidor Añade la dependencia a tu diseño e importa la biblioteca. Como alternativa, si estás empezando de cero y necesitas un archivo go.mod, descarga los archivos del proyecto con el enlace de descarga que encontrarás en el editor de código. #### Go Asegúrate de que inicializas con Go Modules: ```bash go get -u github.com/stripe/stripe-go/v85 ``` #### GitHub O descarga directamente el código fuente del módulo stripe-go [desde GitHub](https://github.com/stripe/stripe-go). ### Instalar la biblioteca Stripe.net Instala el paquete con .NET o NuGet. Como alternativa, si estás empezando de cero, descarga los archivos que tienen 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 descarga el código fuente de la biblioteca Stripe.net directamente [desde GitHub](https://github.com/stripe/stripe-dotnet). ### Instala las bibliotecas de Stripe Instala los paquetes e impórtalos a tu código. Como alternativa, si estás empezando de cero y necesitas un archivo `package.json`, descarga los archivos del proyecto con el enlace de descarga que encontrarás en el editor de código. Instala las bibliotecas: ```bash npm install --save stripe @stripe/stripe-js next ``` ### Crea un PaymentIntent Añade a tu servidor un punto de conexión que cree un [PaymentIntent](https://docs.stripe.com/api/payment_intents.md). El PaymentIntent hace un seguimiento del ciclo de vida del pago del cliente, mantiene un registro de los intentos de pago fallidos y se asegura de que se le cobre al cliente solo una vez. Devuelve el *secreto de cliente* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) del PaymentIntent en la respuesta para finalizar el pago del lado del cliente. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Añade Stripe a tu aplicación de React Utiliza el *Stripe.js* (Use Stripe.js’ APIs to tokenize customer information, collect sensitive card data, and accept payments with browser payment APIs) y la [biblioteca Stripe Elements UI](https://docs.stripe.com/sdks/stripejs-react.md) para *cumplir con la normativa PCI* (Any party involved in processing, transmitting, or storing credit card data must comply with the rules specified in the Payment Card Industry (PCI) Data Security Standards. PCI compliance is a shared responsibility and applies to both Stripe and your business) asegurándote de que los datos del pago van directamente a Stripe y nunca llegan a tu servidor. ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` ### Añade Stripe a tu aplicación de React Utiliza el *Stripe.js* (Use Stripe.js’ APIs to tokenize customer information, collect sensitive card data, and accept payments with browser payment APIs) y la [biblioteca Stripe Elements UI](https://docs.stripe.com/sdks/stripejs-react.md) para *cumplir con la normativa PCI* (Any party involved in processing, transmitting, or storing credit card data must comply with the rules specified in the Payment Card Industry (PCI) Data Security Standards. PCI compliance is a shared responsibility and applies to both Stripe and your business) asegurándote de que los datos del pago van directamente a Stripe y nunca llegan a tu servidor. ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` ### Carga Stripe.js Llama a `loadStripe()` con tu [clave de API publicable](https://docs.stripe.com/keys.md#obtain-api-keys) de Stripe para configurar la biblioteca de Stripe. ### Carga Stripe.js Llama a `loadStripe()` con tu [clave de API publicable](https://docs.stripe.com/keys.md#obtain-api-keys) de Stripe para configurar la biblioteca de Stripe. ### Carga Stripe.js Utiliza *Stripe.js* (Use Stripe.js’ APIs to tokenize customer information, collect sensitive card data, and accept payments with browser payment APIs) para *cumplir con la normativa PCI* (Any party involved in processing, transmitting, or storing credit card data must comply with the rules specified in the Payment Card Industry (PCI) Data Security Standards. PCI compliance is a shared responsibility and applies to both Stripe and your business) asegurándote de que los datos del pago se envíen directamente a Stripe sin que pasen por tu servidor. Carga siempre Stripe.js desde js.stripe.com para cumplir con la normativa. No incluyas la secuencia de comandos en un paquete ni lo alojes tú mismo. ### Define el formulario de pago Añade un marcador de posición vacío `div` a tu formulario del proceso de compra por cada Element que vayas a montar. Stripe inserta un iframe en cada `div` para recolectar de forma segura la dirección de correo electrónico y la información de pago del cliente. ### Inicializa Stripe.js Inicia Stripe.js con tu [clave de API publicable](https://docs.stripe.com/keys.md#obtain-api-keys). Utilizarás Stripe.js para crear el Payment Element y completar el pago en el cliente. ### Obtén un PaymentIntent Haz una petición instantánea al punto de conexión de tu servidor para que cree un nuevo PaymentIntent justo cuando se cargue la página del proceso de compra. El `clientSecret` que tu punto de conexión devuelve se utiliza para efectivizar el pago. ### Inicializa Stripe Elements Pasa la promesa obtenida de `loadStripe` al proveedor de Elements. Esto permite que los componentes secundarios accedan al servicio de Stripe con el consumidor de Elements. Además, pasa el secreto de cliente como opción al proveedor de Elements. ### Inicializa Stripe Elements Pasa la promesa obtenida de `loadStripe` al proveedor de Elements. Esto permite que los componentes secundarios accedan al servicio de Stripe a través del consumidor de Elements. Además, pasa el secreto de cliente como opción al proveedor de Elements. ### Inicializa Stripe Elements Inicializa la [biblioteca de interfaz de usuario de Stripe Elements](https://docs.stripe.com/js/elements_object/create) con el secreto de cliente. Elements gestiona los componentes de la interfaz de usuario que necesitas para recolectar los datos de pago. ### Configura el estado Inicializa algún estado para realizar un seguimiento del pago, mostrar errores y gestionar la interfaz de usuario. ### Configura el estado Inicializa algún estado para realizar un seguimiento del pago, mostrar errores y gestionar la interfaz de usuario. ### Almacena una referencia a Stripe Utiliza los hooks `useStripe()` y `useElements()` para acceder a la biblioteca de Stripe de tu componente CheckoutForm. Si necesitas acceder a Elements con un componente de clase, utiliza [ElementsConsumer](https://docs.stripe.com/sdks/stripejs-react.md#elements-consumer) en su lugar. ### Almacena una referencia a Stripe Utiliza los hooks `useStripe()` y `useElements()` para acceder a la biblioteca de Stripe de tu componente CheckoutForm. Si necesitas acceder a Elements a través de una clase, utiliza [ElementsConsumer](https://docs.stripe.com/sdks/stripejs-react.md#elements-consumer) en su lugar. ### Añade el PaymentElement Añade [PaymentElement](https://docs.stripe.com/js/elements_object/create_payment_element) a tu formulario de pago. Integra un iframe con un formulario dinámico que recolecta los datos de pago para una variedad de métodos de pago. Tu cliente puede elegir un tipo de método de pago, y el formulario recolecta automáticamente todos los datos de pago necesarios para su selección. ### Añade el PaymentElement Añade el [PaymentElement](https://docs.stripe.com/js/elements_object/create_payment_element) a tu formulario de pago. Integra un iframe con un formulario dinámico que recolecta los datos de pago para una variedad de métodos de pago. Tu cliente puede elegir un tipo de método de pago, y el formulario recolecta automáticamente todos los datos de pago necesarios para su selección. ### Crea el PaymentElement Crea un [PaymentElement](https://docs.stripe.com/js/elements_object/create_payment_element) y móntalo en el marcador de posición `
` de tu formulario de pago. Esto integra un iframe con un formulario dinámico que muestra los tipos de métodos de pago configurados disponibles en el PaymentIntent, lo que permite a tu cliente elegir un método de pago. El formulario recolecta automáticamente los datos de pago asociados al tipo de método de pago elegido. ### (Opcional) Dale estilo al Payment Element Personaliza la interfaz del Payment Element creando un [objeto Appearance](https://docs.stripe.com/elements/appearance-api.md) y pasándolo como opción al proveedor de Elements. Utiliza el esquema de colores y la fuente de tu empresa para que coincida con el resto de tu página de proceso de compra. Utiliza fuentes personalizadas (por ejemplo, de Google Fonts) iniciando Elements con un [conjunto de fuentes](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-fonts). Asegúrate de abrir la vista previa de la derecha para ver tus cambios en modo activo. > Es posible que algunas partes de la versión beta no coincidan con tu página actual de proceso de compra. La configuración anterior solo representa un subconjunto de las variables del [objeto Appearance](https://docs.stripe.com/elements/appearance-api.md), y el [dicho objeto](https://docs.stripe.com/elements/appearance-api.md) solo controla ciertos atributos de Stripe Elements. Eres responsable de dar estilo al resto de tu página de proceso de compra. ### (Opcional) Dale estilo al Payment Element Personaliza la interfaz del Payment Element creando un [objeto Appearance](https://docs.stripe.com/elements/appearance-api.md) y pasándolo como opción al proveedor de Elements. Utiliza el esquema de colores y la fuente de tu empresa para que coincida con el resto de tu página de proceso de compra. Utiliza fuentes personalizadas (por ejemplo, de Google Fonts) iniciando Elements con un [conjunto de fuentes](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-fonts). Asegúrate de abrir la vista previa de la derecha para ver tus cambios en modo activo. > Algunas partes de la versión de demostración podrían no coincidir con tu página de proceso de compra real. La configuración anterior representa solo un subconjunto de las variables del objeto de apariencia y el objeto de apariencia solo controla ciertos atributos de Stripe Elements. Tú eres el responsable de diseñar el resto de la página de pago. ### (Opcional) Dale estilo al Payment Element Personaliza la interfaz de usuario de Payment Element creando un [objeto Appearance](https://docs.stripe.com/elements/appearance-api.md) e iniciando Elements con este. Utiliza el esquema de colores y la fuente de tu empresa para que coincida con el resto de tu página de proceso de compra. Utiliza fuentes personalizadas (por ejemplo, de Google Fonts) iniciando Elements con un [conjunto de fuentes](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-fonts). Asegúrate de abrir la vista previa de la derecha para ver tus cambios en modo activo. > Es posible que algunas partes de la versión beta no coincidan con tu página actual de proceso de compra. La configuración anterior solo representa un subconjunto de las variables del [objeto Appearance](https://docs.stripe.com/elements/appearance-api.md), y el [dicho objeto](https://docs.stripe.com/elements/appearance-api.md) solo controla ciertos atributos de Stripe Elements. Eres responsable de dar estilo al resto de tu página de proceso de compra. ### Gestiona el evento enviar Recibe notificaciones del evento enviar formulario para saber cuándo tienes que confirmar el pago a través de la API de Stripe. ### Efectiviza el pago Cuando tu cliente hace clic en el botón de pago, llama a [confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) con PaymentElement y especifica una [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) para indicar a dónde redirige al cliente después de completar el pago. Para los pagos que requieren autenticación, Stripe muestra un modal para la autenticación *3D Secure* (3D Secure (3DS) provides an additional layer of authentication for credit card transactions that protects businesses from liability for fraudulent card payments) o redirige al cliente a una página de autenticación, dependiendo del método de pago. Una vez que el cliente completa el proceso de autenticación, se le redirige a la `return_url`. ### Efectiviza el pago Cuando tu cliente hace clic en el botón de pago, llama a [confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) con PaymentElement y especifica una [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) para indicar a dónde redirige al cliente después de completar el pago. Para los pagos que requieren autenticación, Stripe muestra un modal para la autenticación *3D Secure* (3D Secure (3DS) provides an additional layer of authentication for credit card transactions that protects businesses from liability for fraudulent card payments) o redirige al cliente a una página de autenticación, dependiendo del método de pago. Una vez que el cliente completa el proceso de autenticación, se le redirige a la `return_url`. ### Efectiviza el pago Llama a [confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) con la instancia Element y una [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) para indicar a dónde redirige Stripe al cliente después de que complete el pago. Para pagos que requieren autenticación, Stripe muestra un cuadro de diálogo para la autenticación *3D Secure* (3D Secure (3DS) provides an additional layer of authentication for credit card transactions that protects businesses from liability for fraudulent card payments) o redirige al cliente a una página de autenticación, según el método de pago. Después de que el cliente complete el proceso de autenticación, se le redirige a la `return_url`. ### Gestiona los errores Si se producen [errores](https://docs.stripe.com/error-codes.md) inmediatos (por ejemplo, se ha rechazado la tarjeta de tu cliente), Stripe.js devuelve un error. Muestra ese mensaje de error a tu cliente para que vuelva a intentarlo. ### Muestra un mensaje de estado de pago Cuando Stripe redirige al cliente a la `return_url`, Stripe.js anexa el parámetro de consulta `payment_intent_client_secret`. Úsalo para recuperar la [actualización del estado de PaymentIntent](https://docs.stripe.com/payments/payment-intents/verifying-status.md) y determinar qué mostrarle a tu cliente. ### Muestra un mensaje de estado de pago Cuando Stripe redirige al cliente a `return_url`, Stripe.js anexa el parámetro de consulta `payment_intent`. Úsalo para recuperar la [actualización del estado de PaymentIntent](https://docs.stripe.com/payments/payment-intents/verifying-status.md) y determinar qué mostrarle a tu cliente. ### Usa un webhook Stripe envía varios eventos durante el proceso de pago y después de que este se completa. Crea un [destino de evento](https://docs.stripe.com/event-destinations.md) para que un [punto de conexión de webhook](https://docs.stripe.com/webhooks/quickstart.md) reciba estos eventos y ejecute acciones como, por ejemplo, enviar un correo electrónico de confirmación de pedido al cliente, registrar la venta en una base de datos o iniciar el flujo de tareas de envío. Stripe recomienda gestionar los eventos [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.succeeded), [payment_intent.processing](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.processing) y [payment_intent.payment_failed](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.payment_failed). Escucha estos eventos en lugar de esperar una devolución de llamada del cliente. Por su parte, el cliente puede cerrar la ventana del navegador o salir de la aplicación antes de que se ejecute la devolución de llamada. Si configuras tu integración para escuchar eventos asincrónicos, podrás aceptar [diferentes tipos de métodos de pago](https://stripe.com/payments/payment-methods-guide) con una sola integración. ### Ejecutar la aplicación Ejecuta la aplicación React y el servidor. Ve a [localhost:3000/checkout](http://localhost:3000/checkout) para ver tu página del proceso de compra. ```bash npm start ``` ### Ejecutar la aplicación Ejecuta la aplicación Next.js. Ve a [localhost:3000](http://localhost:3000) para ver tu página del proceso de compra. ```bash npm run dev ``` ### Ejecutar la aplicación Ejecuta tu servidor de Node y ve a [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash npm start ``` ### Ejecuta la aplicación de servidor Ejecuta la aplicación React y el servidor. Ve a [localhost:3000/checkout](http://localhost:3000/checkout) para ver tu página del proceso de compra. ```bash ruby server.rb ``` ### Ejecutar la aplicación Ejecuta tu servidor de Ruby y ve a [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash ruby server.rb ``` ### Ejecuta la aplicación de servidor Ejecuta la aplicación React y el servidor. Ve a [localhost:3000/checkout](http://localhost:3000/checkout) para ver tu página del proceso de compra. ```bash python3 -m flask run --port=4242 ``` ### Ejecutar la aplicación Ejecuta tu servidor de Python y ve a [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash python3 -m flask run --port=4242 ``` ### Ejecuta la aplicación de servidor Ejecuta la aplicación React y el servidor. Ve a [localhost:3000/checkout](http://localhost:3000/checkout) para ver tu página del proceso de compra. ```bash php -S 127.0.0.1:4242 --docroot=public ``` ### Ejecutar la aplicación Ejecuta tu servidor y ve a [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash php -S 127.0.0.1:4242 --docroot=public ``` ### Ejecuta la aplicación de servidor Ejecuta la aplicación React y el servidor. Ve a [localhost:3000/checkout](http://localhost:3000/checkout) para ver tu página del proceso de compra. ```bash go run server.go ``` ### Ejecutar la aplicación Ejecuta tu servidor de Go y ve a [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash go run server.go ``` ### Ejecuta la aplicación de servidor Ejecuta la aplicación React y el servidor. Ve a [localhost:3000/checkout](http://localhost:3000/checkout) para ver tu página del proceso de compra. ```bash dotnet run ``` ### Ejecutar la aplicación Ejecuta tu servidor de ASP.NET MVC y ve a [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash dotnet run ``` ### Ejecutar la aplicación Ejecuta tu servidor y ve a [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash java -cp target/sample-jar-with-dependencies.jar com.stripe.sample.Server ``` ### Ejecuta la aplicación de servidor Ejecuta la aplicación React y el servidor. Ve a [localhost:3000/checkout](http://localhost:3000/checkout) para ver tu página del proceso de compra. ```bash java -cp target/sample-jar-with-dependencies.jar com.stripe.sample.Server ``` ### Ejecutar la aplicación Ejecuta la aplicación React y ve a [localhost:3000/checkout](http://localhost:3000/checkout). ```bash npm start ``` ### Efectuar un pago de prueba Para verificar que tu integración funciona, haz un pago de prueba utilizando los [datos de pago de prueba](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=elements&api-integration=paymentintents#web-test-the-integration). ### Ver tu pago en el Dashboard Ve al [Dashboard de Stripe](https://dashboard.stripe.com/test/payments) para ver tu pago de prueba. ## Aceptar pagos y mejorar tu integración Ya puedes aceptar pagos con Stripe. Sigue los siguientes pasos para añadir más funciones. ### Automatizar el pago de impuestos Calcula y recauda los impuestos correctos de tus transacciones de Stripe. Antes de usar Stripe Tax, debes activarlo en el [Dashboard](https://dashboard.stripe.com/tax). Obtén más información sobre [Stripe Tax](https://docs.stripe.com/tax.md) y [cómo añadirlo a tu integración de Payments](https://docs.stripe.com/tax/custom.md). ### Usar la API de Stripe Tax para calcular los impuestos Usa la [API Stripe Tax](https://docs.stripe.com/api/tax/calculations/create.md) para calcular los impuestos de la transacción. Proporciona la `currency`, los `customer_details` y las `line_items` del pedido en el cuerpo de la solicitud. Utiliza el atributo `tax_amount_exclusive` del cálculo de impuestos resultante para añadir los impuestos no incluidos al total del pedido. ### Registrar una transacción de impuestos tras un pago realizado correctamente Vincula el cálculo de impuestos al PaymentIntent usando `hooks[inputs][tax][calculation].` Esto registra los impuestos recaudados en tu cuenta de Stripe, que posteriormente puedes exportar con fines contables, y activa otras [acciones de Stripe](https://docs.stripe.com/tax/payment-intent.md#automatic-actions). ### Envía un recibo por correo electrónico Stripe puede enviar por correo electrónico a tu cliente un recibo que utilice el logotipo de tu marca y tu paleta de colores, que puedes configurar en el [Dashboard](https://dashboard.stripe.com/settings/branding). ### Recolecta la dirección de correo electrónico del cliente Añade a tu formulario de pago un campo de entrada para recolectar la dirección de correo electrónico. ### Añade un correo electrónico al estado Añade una variable para realizar el seguimiento del correo electrónico que el cliente introduce. ### Añade un correo electrónico al estado Añade una variable para realizar el seguimiento del correo electrónico que el cliente introduce. ### Proporciona la dirección de correo electrónico a Stripe Define en `receipt_email` la dirección de correo electrónico proporcionada. Stripe envía un recibo por correo electrónico cuando el pago se realiza correctamente en modo activo (pero no lo enviará en un *entorno de prueba* (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)). ### Guardar los datos de pago después del pago A menudo los utilizan empresas de e-commerce o de SaaS (software como servicio) con los clientes que regresan ### Importa más recursos de Stripe Importa los paquetes de Stripe `customer` y `paymentmethod`. Usa estos paquetes para almacenar información sobre tu cliente. ### Importa más recursos de Stripe Importa los modelos PaymentMethod y Customer de Stripe. Usa estos modelos para almacenar información sobre tu cliente. ### Crear un cliente Stripe almacena la tarjeta en un objeto *Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments). Crea un objeto Customer nuevo antes de crear un PaymentIntent. En Customer, también puedes almacenar el nombre, el correo electrónico, la dirección de envío y otros datos. ### Crear un cliente Stripe almacena la tarjeta en un objeto [Cuenta](https://docs.stripe.com/api/v2/core/accounts/object.md) representativo del [cliente](https://docs.stripe.com/connect/account-capabilities.md?accounts-namespace=v2#customer). Crea una cuenta nueva antes de crear un PaymentIntent. En la cuenta también puedes almacenar el nombre, correo electrónico, dirección de envío y otros datos. ### Añade el cliente al PaymentIntent Transfiere el ID de cliente al PaymentIntents y configura `setup_future_usage` como `off_session`. `setup_future_usage` indica a Stripe cómo planeas utilizar el método de pago; algunas regiones, como Europa y la India, tienen requisitos sobre la reutilización de los datos de pago. [Más información sobre](https://docs.stripe.com/payments/payment-intents.md#future-usage) sobre la forma más eficaz de aplicar `setup_future_usage`. También puedes ver una [lista de métodos de pago admitidos](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability). Una vez que el PaymentIntent se realiza correctamente, Stripe [adjunta](https://docs.stripe.com/api/payment_methods/attach.md) automáticamente los detalles de pago (en un objeto *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs)) a tu cliente. ### Añade el cliente al PaymentIntent Pasa el ID de la cuenta a PaymentIntent y establece `setup_future_usage` to `off_session`. `setup_future_usage`le indica a Stripe cómo piensas utilizar el método de pago; algunas regiones, como Europa y la India, tienen requisitos en cuanto a la reutilización de los datos de pago.[Obtén](https://docs.stripe.com/payments/payment-intents.md#future-usage) más información sobre la forma más eficaz de aplicar `setup_future_usage`. También puedes consultar una [lista de métodos de pago soportados](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability). Una vez que PaymentIntent se ha completado con éxito, Stripe [adjunta](https://docs.stripe.com/api/payment_methods/attach.md) automáticamente los detalles del pago (en un objeto *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs)) a la cuenta configurada por el cliente. ### Cobra el PaymentMethod guardado Cuando quieras volver a aceptar el PaymentMethod, crea un nuevo PaymentIntent con el ID del Customer, el ID del PaymentMethod al que quieres efectuar el cargo, y establece las marcas `off_session` y `confirm` como verdaderas. ### Instala la biblioteca Stripe Node Instala el paquete e impórtalo a tu código. Como alternativa, si estás empezando de cero y necesitas un archivo package.json, descarga los archivos del proyecto con el enlace de descarga que encontrarás en el editor de código. #### npm Instala la biblioteca: ```bash npm install --save stripe ``` #### GitHub O descarga directamente el código fuente de la biblioteca stripe-node [desde GitHub](https://github.com/stripe/stripe-node). ### Instala la biblioteca Stripe Ruby Instala la gema Ruby de Stripe y solicítala en tu código. Como alternativa, si estás empezando de cero y necesitas un Gemfile, descarga los archivos del proyecto con el enlace de descarga que encontrarás en el editor de código. #### Terminal Instala la gema: ```bash gem install stripe ``` #### Bundler Añade esta línea a tu Gemfile: ```bash gem 'stripe' ``` #### GitHub O descarga el código fuente de la gema stripe-ruby directamente [desde GitHub](https://github.com/stripe/stripe-ruby). ### Instala la biblioteca de Stripe Java Añade la dependencia a tu diseño e importa la biblioteca. Como alternativa, si estás empezando de cero y necesitas un archivo pom.xml de muestra (para Maven), descarga los archivos del proyecto con el enlace de descarga que encontrarás en el editor de código. #### Maven Añade la dependencia siguiente 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 Añade 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). ### Instala el paquete Stripe Python Instala el paquete de Stripe e impórtalo a tu código. Como alternativa, si estás empezando de cero y necesitas un archivo requirements.txt, descarga los archivos del proyecto con el enlace de descarga que encontrarás en el editor de código. #### pip Instala el paquete a través de pip: ```bash pip3 install stripe ``` #### GitHub Descarga directamente el código fuente de la biblioteca stripe-python [desde GitHub](https://github.com/stripe/stripe-python). ### Instala la biblioteca Stripe PHP Utiliza Composer para instalar la biblioteca e inicializa la clave secreta de tu API. Como alternativa, si estás empezando de cero y necesitas un archivo composer.json, descarga los archivos con el enlace de descarga que encontrarás en el editor de código. #### Composer Instala la biblioteca: ```bash composer require stripe/stripe-php ``` #### GitHub O descarga directamente el código fuente de la biblioteca stripe-php [desde GitHub](https://github.com/stripe/stripe-php). ### Configura tu servidor Añade la dependencia a tu diseño e importa la biblioteca. Como alternativa, si estás empezando de cero y necesitas un archivo go.mod, descarga los archivos del proyecto con el enlace de descarga que encontrarás en el editor de código. #### Go Asegúrate de que inicializas con Go Modules: ```bash go get -u github.com/stripe/stripe-go/v85 ``` #### GitHub O descarga directamente el código fuente del módulo stripe-go [desde GitHub](https://github.com/stripe/stripe-go). ### Instalar la biblioteca Stripe.net Instala el paquete con .NET o NuGet. Como alternativa, si estás empezando de cero, descarga los archivos que tienen 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 descarga el código fuente de la biblioteca Stripe.net directamente [desde GitHub](https://github.com/stripe/stripe-dotnet). ### Instala las bibliotecas de Stripe Instala los paquetes e impórtalos a tu código. Como alternativa, si estás empezando de cero y necesitas un archivo `package.json`, descarga los archivos del proyecto con el enlace de descarga que encontrarás en el editor de código. Instala las bibliotecas: ```bash npm install --save stripe @stripe/stripe-js next ``` ### Crea un PaymentIntent Añade a tu servidor un punto de conexión que cree un [PaymentIntent](https://docs.stripe.com/api/payment_intents.md). El PaymentIntent hace un seguimiento del ciclo de vida del pago del cliente, mantiene un registro de los intentos de pago fallidos y se asegura de que se le cobre al cliente solo una vez. Devuelve el *secreto de cliente* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) del PaymentIntent en la respuesta para finalizar el pago del lado del cliente. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Instalar el SDK El SDK de Stripe para iOS es de [fuente abierta](https://github.com/stripe/stripe-ios), [está completamente documentado](https://stripe.dev/stripe-ios/) y es compatible con las aplicaciones que aceptan iOS 13 o versiones superiores. Importa el SDK de Stripe al controlador de vista de la pantalla de tu proceso de compra. #### Administrador de paquetes Swift En Xcode, elige **Archivo** > **Añadir dependencias de paquetes…** e introduce `https://github.com/stripe/stripe-ios-spm` como la URL del repositorio. Elige el número de versión más reciente en nuestra [página de lanzamientos](https://github.com/stripe/stripe-ios/releases) y añade el módulo `StripePaymentSheet` al destino de tu aplicación. #### CocoaPods Añade esta línea a tu Podfile y, de aquí en adelante, usa el archivo .xcworkspace (en vez de .xcodeproj) para abrir tu proyecto en Xcode. ```bash pod 'StripePaymentSheet' ``` #### Carthage Añade esta línea a tu Cartfile. ```bash github "stripe/stripe-ios" ``` #### Plataforma manual Para incluir Stripe en tu proyecto, descarga y descomprime Stripe.xcframework.zip de una [versión en GitHub](https://github.com/stripe/stripe-ios/releases). Arrastra los archivos xcframework necesarios a la configuración de «Binarios integrados» en tu proyecto de Xcode. Asegúrate de elegir «Copiar elementos si es necesario». ### Configura el SDK Configura el SDK de Stripe con tu [clave de API publicable](https://docs.stripe.com/keys.md#obtain-api-keys) de Stripe. La codificación de la clave de API publicable en el SDK es solo para demostración. En una aplicación de producción, debes recuperar la clave de API del servidor. ### Obtén un PaymentIntent Solicita un PaymentIntents a tu servidor en cuanto se cargue la vista. Almacena una referencia al *secreto de cliente del PaymentIntent* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) devuelto por el servidor; el Payment Sheet utiliza este secreto para completar el pago más tarde. ### Configura y presenta la Payment Sheet Crea una instancia de `PaymentSheet` usando el secreto de cliente recuperado anteriormente y preséntalo desde tu controlador de vista. Utiliza la estructura `PaymentSheet.Configuration` para [personalizar](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html) la Payment Sheet. ### Gestionar el resultado del pago Usa el bloque de finalización para gestionar el resultado del pago. Si el pago falla con un [error](https://docs.stripe.com/error-codes.md), muéstrale a tu cliente el mensaje correspondiente para que actúe y vuelva a intentarlo. Si no se ha producido ningún error, indica a tu cliente que el pago se ha realizado correctamente. ### Efectuar un pago de prueba #### iOS Para verificar que tu integración funciona, haz un pago de prueba utilizando los [datos de pago de prueba](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios#ios-test-the-integration). #### Android Para verificar que tu integración funciona, haz un pago de prueba utilizando los [datos de pago de prueba](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=android#android-test-the-integration). ### Ver tu pago en el Dashboard Ve al [Dashboard de Stripe](https://dashboard.stripe.com/test/payments) para ver tu pago de prueba. ## Aceptar pagos y mejorar tu integración Ya puedes aceptar pagos con Stripe. Sigue los siguientes pasos para añadir más funciones. ### Automatizar el pago de impuestos Calcula y recauda los impuestos correctos de tus transacciones de Stripe. Antes de usar Stripe Tax, debes activarlo en el [Dashboard](https://dashboard.stripe.com/tax). Obtén más información sobre [Stripe Tax](https://docs.stripe.com/tax.md) y [cómo añadirlo a tu integración de Payments](https://docs.stripe.com/tax/custom.md). ### Usar la API de Stripe Tax para calcular los impuestos Usa la [API Stripe Tax](https://docs.stripe.com/api/tax/calculations/create.md) para calcular los impuestos de la transacción. Proporciona la `currency`, los `customer_details` y las `line_items` del pedido en el cuerpo de la solicitud. Utiliza el atributo `tax_amount_exclusive` del cálculo de impuestos resultante para añadir los impuestos no incluidos al total del pedido. ### Registrar una transacción de impuestos tras un pago realizado correctamente Vincula el cálculo de impuestos al PaymentIntent usando `hooks[inputs][tax][calculation].` Esto registra los impuestos recaudados en tu cuenta de Stripe, que posteriormente puedes exportar con fines contables, y activa otras [acciones de Stripe](https://docs.stripe.com/tax/payment-intent.md#automatic-actions). ### Permitir métodos de pago diferido Algunos métodos de pago no garantizan que recibirás los fondos del cliente al finalizar el proceso de compra, ya que tardan en liquidarse (por ejemplo, la mayoría de los adeudos bancarios, como SEPA o ACH) o requieren una acción por parte del cliente para completarlos (por ejemplo, OXXO, Konbini, Boleto). Utiliza este indicador para habilitar los métodos de pago diferido. Si habilitas esta función, asegúrate de que la integración de tu servidor reciba notificaciones de los [webhooks](https://docs.stripe.com/payments/payment-methods.md#payment-notification) sobre si el pago se ha efectuado correctamente o no. ### Añadir compatibilidad con Apple Pay Para habilitar Apple Pay, proporciona tu [ID de comerciante de Apple Pay](https://support.stripe.com/questions/enable-apple-pay-on-your-stripe-account) y el [código de país](https://dashboard.stripe.com/settings/account) de tu cuenta de Stripe. ### Añadir compatibilidad con Google Pay Para usar Google Pay, primero habilita la API de Google Pay en tu AndroidManifest.xml. Habilita Google Pay especificando un objeto [PaymentSheet.GooglePayConfiguration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-google-pay-configuration/index.html) con el entorno (de producción o de prueba) de Google Pay y el [código de país de tu empresa](https://dashboard.stripe.com/settings/account) al inicializar [PaymentSheet.Configuration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-configuration/index.html). ### Personaliza el color del botón principal Considera la posibilidad de usar un color personalizado para el botón principal que coincida mejor con la identidad visual de tu marca o aplicación. ### Habilita el escaneo de tarjetas El escaneo de tarjetas puede ayudarte a aumentar tu tasa de conversión, ya que elimina la fricción de la introducción manual de tarjetas. Para habilitar el escaneo de tarjetas, establece `NSCameraUsageDescription` en `Info.plist` de tu aplicación y proporciona un motivo para acceder a la cámara (por ejemplo, «Para escanear tarjetas»). > El escaneo de tarjetas solo es compatible con dispositivos con iOS 13 o versiones superiores. ### Habilita el escaneo de tarjetas El escaneo de tarjetas puede ayudarte a aumentar tu tasa de conversión, ya que elimina la fricción de la introducción manual de tarjetas. Para habilitar el escaneo de tarjetas, añade `stripecardscan` al bloque `dependencies` de tu archivo [app/build.gradle](https://developer.android.com/studio/build/dependencies): #### Groovy ```groovy implementation 'com.stripe:stripecardscan:23.3.0' ``` ### Guardar los datos de pago después del pago A menudo los utilizan empresas de e-commerce o de SaaS (software como servicio) con los clientes que regresan ### Importa más recursos de Stripe Importa los paquetes de Stripe `customer` y `paymentmethod`. Usa estos paquetes para almacenar información sobre tu cliente. ### Importa más recursos de Stripe Importa los modelos PaymentMethod y Customer de Stripe. Usa estos modelos para almacenar información sobre tu cliente. ### Crear un cliente Stripe almacena la tarjeta en un objeto *Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments). Crea un objeto Customer nuevo antes de crear un PaymentIntent. En Customer, también puedes almacenar el nombre, el correo electrónico, la dirección de envío y otros datos. ### Crear un cliente Stripe almacena la tarjeta en un objeto [Cuenta](https://docs.stripe.com/api/v2/core/accounts/object.md) representativo del [cliente](https://docs.stripe.com/connect/account-capabilities.md?accounts-namespace=v2#customer). Crea una cuenta nueva antes de crear un PaymentIntent. En la cuenta también puedes almacenar el nombre, correo electrónico, dirección de envío y otros datos. ### Añade el cliente al PaymentIntent Transfiere el ID de cliente al PaymentIntents y configura `setup_future_usage` como `off_session`. `setup_future_usage` indica a Stripe cómo planeas utilizar el método de pago; algunas regiones, como Europa y la India, tienen requisitos sobre la reutilización de los datos de pago. [Más información sobre](https://docs.stripe.com/payments/payment-intents.md#future-usage) sobre la forma más eficaz de aplicar `setup_future_usage`. También puedes ver una [lista de métodos de pago admitidos](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability). Una vez que el PaymentIntent se realiza correctamente, Stripe [adjunta](https://docs.stripe.com/api/payment_methods/attach.md) automáticamente los detalles de pago (en un objeto *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs)) a tu cliente. ### Añade el cliente al PaymentIntent Pasa el ID de la cuenta a PaymentIntent y establece `setup_future_usage` to `off_session`. `setup_future_usage`le indica a Stripe cómo piensas utilizar el método de pago; algunas regiones, como Europa y la India, tienen requisitos en cuanto a la reutilización de los datos de pago.[Obtén](https://docs.stripe.com/payments/payment-intents.md#future-usage) más información sobre la forma más eficaz de aplicar `setup_future_usage`. También puedes consultar una [lista de métodos de pago soportados](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability). Una vez que PaymentIntent se ha completado con éxito, Stripe [adjunta](https://docs.stripe.com/api/payment_methods/attach.md) automáticamente los detalles del pago (en un objeto *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs)) a la cuenta configurada por el cliente. ### Cobra el PaymentMethod guardado Cuando quieras volver a aceptar el PaymentMethod, crea un nuevo PaymentIntent con el ID del Customer, el ID del PaymentMethod al que quieres efectuar el cargo, y establece las marcas `off_session` y `confirm` como verdaderas. ### Recolecta direcciones usando el Address Element Recolecta las direcciones de envío o facturación locales e internacionales de tus clientes. ### Recolecta direcciones usando el Address Element Recolecta las direcciones de envío o facturación locales e internacionales de tus clientes. Si utilizas el Address Element, también puedes usar el [SDK de Google Places](https://developers.google.com/maps/documentation/places/android-sdk/overview) para obtener sugerencias de autocompletado de direcciones. Para habilitar las sugerencias de autocompletar, añade `places` al bloque de dependencias de tu archivo [app/build.gradle](https://developer.android.com/studio/build/dependencies): #### Groovy ```groovy implementation 'com.google.android.libraries.places:places:2.6.0' ``` ### Instala la biblioteca Stripe Node Instala el paquete e impórtalo a tu código. Como alternativa, si estás empezando de cero y necesitas un archivo package.json, descarga los archivos del proyecto con el enlace de descarga que encontrarás en el editor de código. #### npm Instala la biblioteca: ```bash npm install --save stripe ``` #### GitHub O descarga directamente el código fuente de la biblioteca stripe-node [desde GitHub](https://github.com/stripe/stripe-node). ### Instala la biblioteca Stripe Ruby Instala la gema Ruby de Stripe y solicítala en tu código. Como alternativa, si estás empezando de cero y necesitas un Gemfile, descarga los archivos del proyecto con el enlace de descarga que encontrarás en el editor de código. #### Terminal Instala la gema: ```bash gem install stripe ``` #### Bundler Añade esta línea a tu Gemfile: ```bash gem 'stripe' ``` #### GitHub O descarga el código fuente de la gema stripe-ruby directamente [desde GitHub](https://github.com/stripe/stripe-ruby). ### Instala la biblioteca de Stripe Java Añade la dependencia a tu diseño e importa la biblioteca. Como alternativa, si estás empezando de cero y necesitas un archivo pom.xml de muestra (para Maven), descarga los archivos del proyecto con el enlace de descarga que encontrarás en el editor de código. #### Maven Añade la dependencia siguiente 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 Añade 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). ### Instala el paquete Stripe Python Instala el paquete de Stripe e impórtalo a tu código. Como alternativa, si estás empezando de cero y necesitas un archivo requirements.txt, descarga los archivos del proyecto con el enlace de descarga que encontrarás en el editor de código. #### pip Instala el paquete a través de pip: ```bash pip3 install stripe ``` #### GitHub Descarga directamente el código fuente de la biblioteca stripe-python [desde GitHub](https://github.com/stripe/stripe-python). ### Instala la biblioteca Stripe PHP Utiliza Composer para instalar la biblioteca e inicializa la clave secreta de tu API. Como alternativa, si estás empezando de cero y necesitas un archivo composer.json, descarga los archivos con el enlace de descarga que encontrarás en el editor de código. #### Composer Instala la biblioteca: ```bash composer require stripe/stripe-php ``` #### GitHub O descarga directamente el código fuente de la biblioteca stripe-php [desde GitHub](https://github.com/stripe/stripe-php). ### Configura tu servidor Añade la dependencia a tu diseño e importa la biblioteca. Como alternativa, si estás empezando de cero y necesitas un archivo go.mod, descarga los archivos del proyecto con el enlace de descarga que encontrarás en el editor de código. #### Go Asegúrate de que inicializas con Go Modules: ```bash go get -u github.com/stripe/stripe-go/v85 ``` #### GitHub O descarga directamente el código fuente del módulo stripe-go [desde GitHub](https://github.com/stripe/stripe-go). ### Instalar la biblioteca Stripe.net Instala el paquete con .NET o NuGet. Como alternativa, si estás empezando de cero, descarga los archivos que tienen 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 descarga el código fuente de la biblioteca Stripe.net directamente [desde GitHub](https://github.com/stripe/stripe-dotnet). ### Instala las bibliotecas de Stripe Instala los paquetes e impórtalos a tu código. Como alternativa, si estás empezando de cero y necesitas un archivo `package.json`, descarga los archivos del proyecto con el enlace de descarga que encontrarás en el editor de código. Instala las bibliotecas: ```bash npm install --save stripe @stripe/stripe-js next ``` ### Crea un PaymentIntent Añade a tu servidor un punto de conexión que cree un [PaymentIntent](https://docs.stripe.com/api/payment_intents.md). El PaymentIntent hace un seguimiento del ciclo de vida del pago del cliente, mantiene un registro de los intentos de pago fallidos y se asegura de que se le cobre al cliente solo una vez. Devuelve el *secreto de cliente* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) del PaymentIntent en la respuesta para finalizar el pago del lado del cliente. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Configura los métodos de pago Stripe habilita tarjetas y otros métodos de pago comunes de forma predeterminada con [métodos de pago dinámicos](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puedes actualizar y configurar los métodos de pago desde el [Dashboard](https://dashboard.stripe.com/settings/payment_methods) sin necesidad de programación. Stripe filtra los métodos de pago según su elegibilidad y las preferencias configuradas, luego los ordena y muestra según la probabilidad de uso, teniendo en cuenta factores como el importe, la moneda y la ubicación del comprador. ### Instalar el SDK El SDK de Stripe para Android es de [fuente abierta](https://github.com/stripe/stripe-android), está [completamente documentado](https://stripe.dev/stripe-android/) y es compatible con dispositivos que ejecutan Android 5.0 (API level 21) y versiones posteriores. Para instalar el SDK, agrega `stripe-android` al bloque de dependencias de tu archivo `build.gradle`: #### Groovy ```groovy implementation 'com.stripe:stripe-android:23.3.0' ``` > Para obtener más información sobre la versión más reciente y sobre las versiones anteriores del SDK, consulta la [página Versiones](https://github.com/stripe/stripe-android/releases) en GitHub. ### Configura el SDK Configura el SDK de Stripe con tu [clave de API publicable](https://docs.stripe.com/keys.md#obtain-api-keys) de Stripe. La codificación de la clave de API publicable en el SDK es solo para demostración. En una aplicación de producción, debes recuperar la clave de API del servidor. ### Obtén un PaymentIntent Solicita un PaymentIntents a tu servidor en cuanto se cargue la vista. Almacena una referencia al *secreto de cliente del PaymentIntent* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) devuelto por el servidor; el Payment Sheet utiliza este secreto para completar el pago más tarde. ### Configura y presenta la Payment Sheet Crea una instancia de `PaymentSheet` usando el secreto de cliente recuperado anteriormente y preséntalo desde tu controlador de vista. Utiliza la estructura `PaymentSheet.Configuration` para [personalizar](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html) la Payment Sheet. ### Gestionar el resultado del pago Usa el bloque de finalización para gestionar el resultado del pago. Si el pago falla con un [error](https://docs.stripe.com/error-codes.md), muéstrale a tu cliente el mensaje correspondiente para que actúe y vuelva a intentarlo. Si no se ha producido ningún error, indica a tu cliente que el pago se ha realizado correctamente. ### Efectuar un pago de prueba #### iOS Para verificar que tu integración funciona, haz un pago de prueba utilizando los [datos de pago de prueba](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios#ios-test-the-integration). #### Android Para verificar que tu integración funciona, haz un pago de prueba utilizando los [datos de pago de prueba](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=android#android-test-the-integration). ### Ver tu pago en el Dashboard Ve al [Dashboard de Stripe](https://dashboard.stripe.com/test/payments) para ver tu pago de prueba. ## Aceptar pagos y mejorar tu integración Ya puedes aceptar pagos con Stripe. Sigue los siguientes pasos para añadir más funciones. ### Automatizar el pago de impuestos Calcula y recauda los impuestos correctos de tus transacciones de Stripe. Antes de usar Stripe Tax, debes activarlo en el [Dashboard](https://dashboard.stripe.com/tax). Obtén más información sobre [Stripe Tax](https://docs.stripe.com/tax.md) y [cómo añadirlo a tu integración de Payments](https://docs.stripe.com/tax/custom.md). ### Usar la API de Stripe Tax para calcular los impuestos Usa la [API Stripe Tax](https://docs.stripe.com/api/tax/calculations/create.md) para calcular los impuestos de la transacción. Proporciona la `currency`, los `customer_details` y las `line_items` del pedido en el cuerpo de la solicitud. Utiliza el atributo `tax_amount_exclusive` del cálculo de impuestos resultante para añadir los impuestos no incluidos al total del pedido. ### Registrar una transacción de impuestos tras un pago realizado correctamente Vincula el cálculo de impuestos al PaymentIntent usando `hooks[inputs][tax][calculation].` Esto registra los impuestos recaudados en tu cuenta de Stripe, que posteriormente puedes exportar con fines contables, y activa otras [acciones de Stripe](https://docs.stripe.com/tax/payment-intent.md#automatic-actions). ### Permitir métodos de pago diferido Algunos métodos de pago no garantizan que recibirás los fondos del cliente al finalizar el proceso de compra, ya que tardan en liquidarse (por ejemplo, la mayoría de los adeudos bancarios, como SEPA o ACH) o requieren una acción por parte del cliente para completarlos (por ejemplo, OXXO, Konbini, Boleto). Utiliza este indicador para habilitar los métodos de pago diferido. Si habilitas esta función, asegúrate de que la integración de tu servidor reciba notificaciones de los [webhooks](https://docs.stripe.com/payments/payment-methods.md#payment-notification) sobre si el pago se ha efectuado correctamente o no. ### Añadir compatibilidad con Apple Pay Para habilitar Apple Pay, proporciona tu [ID de comerciante de Apple Pay](https://support.stripe.com/questions/enable-apple-pay-on-your-stripe-account) y el [código de país](https://dashboard.stripe.com/settings/account) de tu cuenta de Stripe. ### Añadir compatibilidad con Google Pay Para usar Google Pay, primero habilita la API de Google Pay en tu AndroidManifest.xml. Habilita Google Pay especificando un objeto [PaymentSheet.GooglePayConfiguration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-google-pay-configuration/index.html) con el entorno (de producción o de prueba) de Google Pay y el [código de país de tu empresa](https://dashboard.stripe.com/settings/account) al inicializar [PaymentSheet.Configuration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-configuration/index.html). ### Personaliza el color del botón principal Considera la posibilidad de usar un color personalizado para el botón principal que coincida mejor con la identidad visual de tu marca o aplicación. ### Habilita el escaneo de tarjetas El escaneo de tarjetas puede ayudarte a aumentar tu tasa de conversión, ya que elimina la fricción de la introducción manual de tarjetas. Para habilitar el escaneo de tarjetas, establece `NSCameraUsageDescription` en `Info.plist` de tu aplicación y proporciona un motivo para acceder a la cámara (por ejemplo, «Para escanear tarjetas»). > El escaneo de tarjetas solo es compatible con dispositivos con iOS 13 o versiones superiores. ### Habilita el escaneo de tarjetas El escaneo de tarjetas puede ayudarte a aumentar tu tasa de conversión, ya que elimina la fricción de la introducción manual de tarjetas. Para habilitar el escaneo de tarjetas, añade `stripecardscan` al bloque `dependencies` de tu archivo [app/build.gradle](https://developer.android.com/studio/build/dependencies): #### Groovy ```groovy implementation 'com.stripe:stripecardscan:23.3.0' ``` ### Guardar los datos de pago después del pago A menudo los utilizan empresas de e-commerce o de SaaS (software como servicio) con los clientes que regresan ### Importa más recursos de Stripe Importa los paquetes de Stripe `customer` y `paymentmethod`. Usa estos paquetes para almacenar información sobre tu cliente. ### Importa más recursos de Stripe Importa los modelos PaymentMethod y Customer de Stripe. Usa estos modelos para almacenar información sobre tu cliente. ### Crear un cliente Stripe almacena la tarjeta en un objeto *Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments). Crea un objeto Customer nuevo antes de crear un PaymentIntent. En Customer, también puedes almacenar el nombre, el correo electrónico, la dirección de envío y otros datos. ### Crear un cliente Stripe almacena la tarjeta en un objeto [Cuenta](https://docs.stripe.com/api/v2/core/accounts/object.md) representativo del [cliente](https://docs.stripe.com/connect/account-capabilities.md?accounts-namespace=v2#customer). Crea una cuenta nueva antes de crear un PaymentIntent. En la cuenta también puedes almacenar el nombre, correo electrónico, dirección de envío y otros datos. ### Añade el cliente al PaymentIntent Transfiere el ID de cliente al PaymentIntents y configura `setup_future_usage` como `off_session`. `setup_future_usage` indica a Stripe cómo planeas utilizar el método de pago; algunas regiones, como Europa y la India, tienen requisitos sobre la reutilización de los datos de pago. [Más información sobre](https://docs.stripe.com/payments/payment-intents.md#future-usage) sobre la forma más eficaz de aplicar `setup_future_usage`. También puedes ver una [lista de métodos de pago admitidos](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability). Una vez que el PaymentIntent se realiza correctamente, Stripe [adjunta](https://docs.stripe.com/api/payment_methods/attach.md) automáticamente los detalles de pago (en un objeto *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs)) a tu cliente. ### Añade el cliente al PaymentIntent Pasa el ID de la cuenta a PaymentIntent y establece `setup_future_usage` to `off_session`. `setup_future_usage`le indica a Stripe cómo piensas utilizar el método de pago; algunas regiones, como Europa y la India, tienen requisitos en cuanto a la reutilización de los datos de pago.[Obtén](https://docs.stripe.com/payments/payment-intents.md#future-usage) más información sobre la forma más eficaz de aplicar `setup_future_usage`. También puedes consultar una [lista de métodos de pago soportados](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability). Una vez que PaymentIntent se ha completado con éxito, Stripe [adjunta](https://docs.stripe.com/api/payment_methods/attach.md) automáticamente los detalles del pago (en un objeto *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs)) a la cuenta configurada por el cliente. ### Cobra el PaymentMethod guardado Cuando quieras volver a aceptar el PaymentMethod, crea un nuevo PaymentIntent con el ID del Customer, el ID del PaymentMethod al que quieres efectuar el cargo, y establece las marcas `off_session` y `confirm` como verdaderas. ### Recolecta direcciones usando el Address Element Recolecta las direcciones de envío o facturación locales e internacionales de tus clientes. ### Recolecta direcciones usando el Address Element Recolecta las direcciones de envío o facturación locales e internacionales de tus clientes. Si utilizas el Address Element, también puedes usar el [SDK de Google Places](https://developers.google.com/maps/documentation/places/android-sdk/overview) para obtener sugerencias de autocompletado de direcciones. Para habilitar las sugerencias de autocompletar, añade `places` al bloque de dependencias de tu archivo [app/build.gradle](https://developer.android.com/studio/build/dependencies): #### Groovy ```groovy implementation 'com.google.android.libraries.places:places:2.6.0' ``` ## Próximos pasos #### Web #### [Recopila datos de la dirección de facturación](https://docs.stripe.com/elements/address-element.md) De forma predeterminada, el Payment Element solo recopila los datos necesarios de la dirección de facturación. Para recopilar la dirección de facturación completa de un cliente (con el fin de calcular el impuesto sobre bienes y servicios digitales, por ejemplo) o su dirección de envío, utiliza el Address Element. #### iOS #### Android #### [Transferencias](https://docs.stripe.com/payouts.md) Aprende a cómo transferir fondos de tu cuenta de Stripe a tu cuenta bancaria #### [Reembolsos](https://docs.stripe.com/refunds.md) Gestiona las solicitudes de reembolso con la API de Stripe o el Dashboard. #### [Cumplimiento](https://docs.stripe.com/webhooks/quickstart.md) Crea un destino de eventos para enviar eventos a tu punto de conexión de webhooks con el fin de completar los pedidos después de que se efectúe correctamente el pago y para gestionar otros eventos críticos.