# Criar uma integração avançada Instruções para LLMs: A Stripe recomenda usar a API Checkout Sessions com o Payment Element em vez de Payment Intents na maioria das integrações. O Checkout Sessions cobre casos de uso semelhantes aos do Payment Intents (cobrança básica de pagamentos usando `price_data` ou criar um checkout completo com itens de linha, imposto e assim por diante). Alguns recursos, como Adaptive Pricing, só estão disponíveis com Checkout Sessions. Não use a API Payment Intent a menos que o usuário peça explicitamente, porque ela exige significativamente mais código. Saiba mais sobre Elements com a API Checkout Sessions: https://docs.stripe.com/payments/quickstart-checkout-sessions. Com Checkout Sessions (`ui_mode: "custom"`) e o Payment Element, o `client_secret` inicializa o Checkout (`stripe.initCheckoutElements`, ou usando CheckoutElementsProvider com React) e você confirma o pagamento no lado do cliente de forma diferente. Se estiver usando React, certifique-se de importar de `@stripe/react-stripe-js/checkout`, usar `CheckoutElementsProvider` com o client secret e confirmar usando `checkout.confirm`. Se estiver usando HTML, certifique-se de usar `checkout = stripe.initCheckoutElements({clientSecret: promise}); checkout.createPaymentElement(); paymentElement = checkout.createPaymentElement(); paymentElement.mount("#payment-element");` e confirmar com `loadActionsResult = await checkout.loadActions(); actions = loadActionsResult.actions; error = await actions.confirm();`. # Crie uma página de checkout com a API Payment Intents Saiba como integrar um formulário de pagamento personalizado da Stripe ao seu site ou aplicativo. O código no lado do cliente e do servidor cria um formulário de checkout com os elementos da [web](https://docs.stripe.com/payments/elements.md) ou de [dispositivos móveis](https://docs.stripe.com/payments/mobile.md) da Stripe para permitir que você aceite pagamentos. Para criar uma integração personalizada que vá além do básico neste início rápido, consulte [Aceitar um pagamento](https://docs.stripe.com/payments/accept-a-payment.md?&ui=elements). Para aprender sobre diferentes cenários de pagamento, como[ assinaturas](https://docs.stripe.com/billing/subscriptions/build-subscriptions.md?payment-ui=elements), e outros produtos Stripe,[compare integrações de pagamento](https://docs.stripe.com/payments/online-payments.md#compare-features-and-availability). > #### Você tem interesse em usar o Stripe Tax, descontos, envio ou conversão de moedas? > > A Stripe tem uma integração do Payment Element que gerencia impostos, descontos, envio e conversão de moedas para você. Consulte o site [construindo uma pagina de checkout](https://docs.stripe.com/payments/quickstart-checkout-sessions.md) para saber mais. // 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 ~~~ ### Instale a biblioteca Node da Stripe Instale o pacote e importe-o para seu código. Se estiver começando do zero e precisar de um arquivo package.json, baixe os arquivos do projeto pelo link de download no editor de código. #### npm Instale a biblioteca: ```bash npm install --save stripe ``` #### GitHub Ou baixe o código-fonte da biblioteca stripe-node diretamente [do GitHub](https://github.com/stripe/stripe-node). ### Instalar a biblioteca Ruby da Stripe Instale o gem do Ruby da Stripe e exija-o no seu código. Alternativamente, se estiver começando do zero e precisar de um Gemfile, baixe os arquivos do projeto usando o link de download no editor de código. #### Terminal Instale o gem: ```bash gem install stripe ``` #### Bundler Adicione esta linha ao seu Gemfile: ```bash gem 'stripe' ``` #### GitHub Ou baixe o código-fonte do gem stripe-ruby diretamente [do GitHub](https://github.com/stripe/stripe-ruby). ### Instalar a biblioteca Java da Stripe Adicione a dependência à compilação e importe a biblioteca. Se você estiver começando do zero e precisar de um modelo de arquivo pom.xml (para Maven), baixe os arquivos do projeto usando o link de download no editor de código. #### Maven Adicione a dependência a seguir ao POM e substitua {VERSION} pelo número de versão que você quer usar. ```bash \ncom.stripe\nstripe-java\n{VERSION}\n ``` #### Gradle Adicione a dependência ao arquivo build.gradle e substitua {VERSION} pelo número de versão que você quer usar. ```bash implementation "com.stripe:stripe-java:{VERSION}" ``` #### GitHub Baixe o JAR diretamente [do GitHub](https://github.com/stripe/stripe-java/releases/latest). ### Instalar o pacote Python da Stripe Instale o pacote da Stripe e importe-o no seu código. Se você estiver começando do zero e precisar de um arquivo requirements.txt, baixe os arquivos do projeto usando o link de download no editor de código. #### pip Instale o pacote usando pip: ```bash pip3 install stripe ``` #### GitHub Faça o download diretamente o código-fonte da biblioteca Stripe-Python [do GitHub](https://github.com/stripe/stripe-python). ### Instalar a biblioteca PHP da Stripe Instale a biblioteca com o composer e inicialize-a com sua chave de API secreta. Se você estiver começando do zero e precisar de um arquivo composer.json, baixe os arquivos usando o link de download no editor de código. #### Composer Instale a biblioteca: ```bash composer require stripe/stripe-php ``` #### GitHub Ou baixe o código-fonte da biblioteca stripe-php diretamente [do GitHub](https://github.com/stripe/stripe-php). ### Configurar o servidor Adicione a dependência à compilação e importe a biblioteca. Se você estiver começando do zero e precisar de um arquivo go.mod, baixe os arquivos do projeto usando o link de download no editor de código. #### Go Não se esqueça de inicializar com Go Modules: ```bash go get -u github.com/stripe/stripe-go/v85 ``` #### GitHub Ou baixe o código-fonte do módulo stripe-go diretamente [do GitHub](https://github.com/stripe/stripe-go). ### Instalar a biblioteca Stripe.net Instale o pacote como .NET ou NuGet. Se estiver começando do zero, você também pode baixar os arquivos com um .csproj configurado. #### dotnet Instale a biblioteca: ```bash dotnet add package Stripe.net ``` #### NuGet Instale a biblioteca: ```bash Install-Package Stripe.net ``` #### GitHub Ou baixe o código-fonte da biblioteca Stripe.net diretamente [do GitHub](https://github.com/stripe/stripe-dotnet). ### Instalar as bibliotecas da Stripe Instale os pacotes e importe-os para o código. Se estiver começando do zero e precisar de um arquivo `package.json`, baixe os arquivos do projeto pelo link de download no editor de código. Instale as bibliotecas: ```bash npm install --save stripe @stripe/stripe-js next ``` ### Criar um PaymentIntent Adicione um endpoint ao servidor que cria um [PaymentIntent](https://docs.stripe.com/api/payment_intents.md). Um PaymentIntent acompanha o ciclo de vida de pagamento do cliente, registrando todas as tentativas com falha e garantindo que a cobrança seja efetuada uma só vez. Retorne o *segredo do 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)) do PaymentIntent na resposta para finalizar o pagamento no cliente. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Adicionar a Stripe ao aplicativo React Use o *Stripe.js* (Use Stripe.js’ APIs to tokenize customer information, collect sensitive card data, and accept payments with browser payment APIs) e a [biblioteca de IU Stripe Elements](https://docs.stripe.com/sdks/stripejs-react.md) para manter a *conformidade com 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), garantindo que os dados de pagamento sejam enviados diretamente para a Stripe e nunca passem pelo servidor. ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` ### Adicionar a Stripe ao aplicativo React Use o *Stripe.js* (Use Stripe.js’ APIs to tokenize customer information, collect sensitive card data, and accept payments with browser payment APIs) e a [biblioteca de IU Stripe Elements](https://docs.stripe.com/sdks/stripejs-react.md) para manter a *conformidade com 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), garantindo que os dados de pagamento sejam enviados diretamente para a Stripe e nunca passem pelo servidor. ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` ### Carregar o Stripe.js Chame `loadStripe()` com sua [chave de API publicável](https://docs.stripe.com/keys.md#obtain-api-keys) da Stripe para configurar a biblioteca Stripe. ### Carregar o Stripe.js Chame `loadStripe()` com sua [chave de API publicável](https://docs.stripe.com/keys.md#obtain-api-keys) da Stripe para configurar a biblioteca Stripe. ### Carregar o Stripe.js Use o *Stripe.js* (Use Stripe.js’ APIs to tokenize customer information, collect sensitive card data, and accept payments with browser payment APIs) para manter a *conformidade com o 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), garantindo que os dados de pagamento sejam enviados diretamente para a Stripe e nunca passem pelo servidor. Sempre carregue o Stripe.js de js.stripe.com para manter a conformidade. Não inclua o script em um pacote nem o hospede. ### Defina o formulário de pagamentos Adicione um `div` de espaço reservado vazio ao seu formulário de checkout para cada Element que você montar. A Stripe insere um iframe em cada `div` para recolher com segurança o endereço de e-mail e os dados de pagamento do cliente. ### Inicializar o Stripe.js Inicialize o Stripe.js com sua [chave de API publicável](https://docs.stripe.com/keys.md#obtain-api-keys). Você usará o Stripe.js para criar o Payment Element e concluir o pagamento no cliente. ### Acessar um PaymentIntent Faça imediatamente uma solicitação ao endpoint no seu servidor para criar um PaymentIntent assim que a página de checkout for carregada. O `clientSecret` retornado pelo seu endpoint é utilizado para concluir o pagamento. ### Inicializar o Stripe Elements Passe a promessa resultante do `loadStripe` para o provedor do Elements. Isso permite que os componentes secundários acessem o serviço da Stripe com o consumidor do Elements. Além disso, passe o segredo do cliente como uma opção para o provedor do Elements. ### Inicializar o Stripe Elements Passe a promessa resultante do `loadStripe` para o provedor do Elements. Isso permite que os componentes secundários acessem o serviço da Stripe por meio do consumidor do Elements. Além disso, passe o segredo do cliente como uma opção para o provedor do Elements. ### Inicializar o Stripe Elements Inicialize a [biblioteca de IU do Stripe Elements](https://docs.stripe.com/js/elements_object/create) com o segredo do cliente. O Elements gerencia os componentes de IU necessários para coletar dados de pagamento. ### Configurar o estado Inicialize algum estado para acompanhar o pagamento, mostrar erros e gerenciar a interface do usuário. ### Configurar o estado Inicialize algum estado para acompanhar o pagamento, mostrar erros e gerenciar a interface do usuário. ### Armazenar uma referência para a Stripe Acesse a biblioteca da Stripe no componente CheckoutForm utilizando os hooks `useStripe()` e `useElements()`. Se precisar acessar o Elements com um componente de classe, use [ElementsConsumer](https://docs.stripe.com/sdks/stripejs-react.md#elements-consumer). ### Armazenar uma referência para a Stripe Acesse a biblioteca da Stripe no componente CheckoutForm utilizando os hooks `useStripe()` e `useElements()`. Se precisar acessar o Elements por meio de um componente de classe, use [ElementsConsumer](https://docs.stripe.com/sdks/stripejs-react.md#elements-consumer). ### Adicionar o PaymentElement Adicione o [PaymentElement](https://docs.stripe.com/js/elements_object/create_payment_element) ao seu formulário de pagamento. Ele incorpora um iframe com um formulário dinâmico que coleta dados de pagamento de várias formas de pagamento. Seu cliente pode escolher um tipo de pagamento, e o formulário coleta automaticamente todos os dados de pagamento necessários. ### Adicionar o PaymentElement Adicione o [PaymentElement](https://docs.stripe.com/js/elements_object/create_payment_element) ao formulário de pagamento. Ele incorpora um iframe com um formulário dinâmico que coleta dados de pagamento de várias formas de pagamento. Seu cliente pode escolher um tipo de pagamento, e o formulário coleta automaticamente todos os dados de pagamento necessários. ### Criar o PaymentElement Crie um [PaymentElement](https://docs.stripe.com/js/elements_object/create_payment_element) e monte-o no espaço reservado `
` no formulário de pagamento. Isso incorpora um iframe com um formulário dinâmico que exibe os tipos de formas de pagamento configuradas disponíveis no PaymentIntent, permitindo que seu cliente selecione uma forma de pagamento. O formulário coleta automaticamente os dados de pagamento associados ao tipo de pagamento selecionado. ### (Opcional) Defina o estilo do Payment Element Personalize a IU do pagamento Element criando um [objeto Appearance](https://docs.stripe.com/API.md), que pode ser passado como uma opção ao provedor do Elements. Adapte a paleta de cores e tipografia para manter a consistência visual com a sua página de Checkout. Utilize fontes personalizadas (como Google Fonts) inicializando Elements com um [conjunto das fontes](https://docs.stripe.com/js/Elements_object/create#stripe_elements-options-fonts). Abra a prévia à direita para ver as alterações no modo de produção. > Algumas partes da demonstração do preview podem não corresponder à sua página de checkout real. As configurações acima representam apenas um subconjunto das variáveis do [objeto Appearance](https://docs.stripe.com/ElementsAPI.md), e os [Appearance object](https://docs.stripe.com/elements/appearance-api.md) controlam apenas certos atributos do Stripe Elements. Você é responsável por personalizar o estilo do resto da sua página de checkout. ### (Opcional) Defina o estilo do Payment Element Personalize a IU do pagamento Element criando um [objeto Appearance](https://docs.stripe.com/API.md), que pode ser passado como uma opção ao provedor do Elements. Adapte a paleta de cores e tipografia para manter a consistência visual com a sua página de Checkout. Utilize fontes personalizadas (como Google Fonts) inicializando Elements com um [conjunto das fontes](https://docs.stripe.com/js/Elements_object/create#stripe_elements-options-fonts). Abra a prévia à direita para ver as alterações no modo de produção. > Partes da demonstração da prévia podem não corresponder à página de checkout real. As configurações acima representam apenas um subconjunto das variáveis do objeto Appearance, e o objeto Appearance controla apenas determinados atributos do Stripe Elements. Você é responsável por estilizar o restante da página de checkout. ### (Opcional) Defina o estilo do Payment Element Personalize a interface do componente de pagamento Element criando um [objeto Appearance](https://docs.stripe.com/APIElements.md). Adapte a paleta de cores e tipografia para manter a consistência visual com a sua página de Checkout. Utilize fontes personalizadas (como Google Fonts) inicializando Elements com um [conjunto das fontes](https://docs.stripe.com/js/Elements_object/create#stripe_elements-options-fonts). Abra a prévia à direita para ver as alterações no modo de produção. > Algumas partes da demonstração do preview podem não corresponder à sua página de checkout real. As configurações acima representam apenas um subconjunto das variáveis do [objeto Appearance](https://docs.stripe.com/ElementsAPI.md), e os [Appearance object](https://docs.stripe.com/elements/appearance-api.md) controlam apenas certos atributos do Stripe Elements. Você é responsável por personalizar o estilo do resto da sua página de checkout. ### Gerenciar o evento de envio Escute o evento de envio do formulário para saber quando confirmar o pagamento pela API da Stripe. ### Finalizar o pagamento Quando seu cliente clicar no botão de pagamento, chame [confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) com o PaymentElement e passe um [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) para indicar para onde a Stripe deve redirecionar o cliente após a finalização do pagamento. Para pagamentos que exigem autenticação, a Stripe exibe uma janela modal para autenticação *3D Secure* (3D Secure (3DS) provides an additional layer of authentication for credit card transactions that protects businesses from liability for fraudulent card payments) ou redireciona o cliente para uma página de autenticação, dependendo do método de pagamento. Após a autenticação ser concluída, o cliente é redirecionado para o `return_url`. ### Finalizar o pagamento Quando seu cliente clicar no botão de pagamento, chame [confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) com o PaymentElement e passe um [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) para indicar para onde a Stripe deve redirecionar o cliente após a finalização do pagamento. Para pagamentos que exigem autenticação, a Stripe exibe uma janela modal para autenticação *3D Secure* (3D Secure (3DS) provides an additional layer of authentication for credit card transactions that protects businesses from liability for fraudulent card payments) ou redireciona o cliente para uma página de autenticação, dependendo do método de pagamento. Após a autenticação ser concluída, o cliente é redirecionado para o `return_url`. ### Finalizar o pagamento Chame [confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) com a instância do Element e um [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) para indicar para onde a Stripe deve redirecionar o cliente após o pagamento. Nos casos em que a autenticação é necessária, a Stripe exibirá uma janela modal de *3D Secure* (3D Secure (3DS) provides an additional layer of authentication for credit card transactions that protects businesses from liability for fraudulent card payments) ou redirecionará o cliente para uma página de autenticação. Depois de finalizado o processo de autenticação, o cliente é levado para o `return_url`. ### Gerenciar erros Se houver [erros](https://docs.stripe.com/error-codes.md) imediatos (por exemplo, o cartão do cliente é recusado), o Stripe.js retornará um erro. Mostre essa mensagem de erro para que o cliente possa tentar novamente. ### Mostrar uma mensagem de status do pagamento Quando a Stripe redireciona o cliente para `return_url`, o parâmetro de consulta `payment_intent_client_secret` é acrescentado pelo Stripe.js. Use para obter a [atualização do status do PaymentIntent](https://docs.stripe.com/payments/payment-intents/verifying-status.md) e determinar o que exibir ao cliente. ### Mostrar uma mensagem de status do pagamento Quando a Stripe redireciona o cliente para `return_url`, o parâmetro de consulta `payment_intent` é acrescentado pelo Stripe.js. Use-o para obter a [atualização do status do PaymentIntent](https://docs.stripe.com/payments/payment-intents/verifying-status.md) e determinar o que exibir ao cliente. ### Usar um webhook A Stripe envia vários eventos durante e após a conclusão do pagamento. Crie um [destino de evento](https://docs.stripe.com/event-destinations.md) para que um [endpoint de webhook](https://docs.stripe.com/webhooks/quickstart.md) receba esses eventos e execute ações, como enviar um e-mail de confirmação de pedido ao cliente, registrar a venda em um banco de dados ou iniciar um fluxo de trabalho de envio. A Stripe recomenda gerenciar os 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) e [payment_intent.payment_failed](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.payment_failed). Escute esses eventos em vez de aguardar um retorno de chamada do cliente. No cliente, o consumidor pode fechar a janela do navegador ou sair do aplicativo antes da execução do retorno de chamada, o que permite que clientes mal-intencionados manipulem a resposta. Configurar sua integração para escutar eventos assíncronos é o que permite a você aceitar [diferentes tipos de formas de pagamento](https://stripe.com/payments/payment-methods-guide) com uma única integração. ### Executar o aplicativo Execute o aplicativo React e o servidor. Acesse [localhost:3000/checkout](http://localhost:3000/checkout) para ver sua página de checkout. ```bash npm start ``` ### Executar o aplicativo Execute o aplicativo Next.js. Acesse [localhost:3000](http://localhost:3000) para ver sua página de checkout. ```bash npm run dev ``` ### Executar o aplicativo Execute o servidor Node e acesse [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash npm start ``` ### Executar o aplicativo do servidor Execute o aplicativo React e o servidor. Acesse [localhost:3000/checkout](http://localhost:3000/checkout) para ver sua página de checkout. ```bash ruby server.rb ``` ### Executar o aplicativo Execute o servidor Ruby e acesse [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash ruby server.rb ``` ### Executar o aplicativo do servidor Execute o aplicativo React e o servidor. Acesse [localhost:3000/checkout](http://localhost:3000/checkout) para ver sua página de checkout. ```bash python3 -m flask run --port=4242 ``` ### Executar o aplicativo Execute o servidor Python e acesse [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash python3 -m flask run --port=4242 ``` ### Executar o aplicativo do servidor Execute o aplicativo React e o servidor. Acesse [localhost:3000/checkout](http://localhost:3000/checkout) para ver sua página de checkout. ```bash php -S 127.0.0.1:4242 --docroot=public ``` ### Executar o aplicativo Execute o servidor e acesse [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash php -S 127.0.0.1:4242 --docroot=public ``` ### Executar o aplicativo do servidor Execute o aplicativo React e o servidor. Acesse [localhost:3000/checkout](http://localhost:3000/checkout) para ver sua página de checkout. ```bash go run server.go ``` ### Executar o aplicativo Execute o servidor Go e acesse [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash go run server.go ``` ### Executar o aplicativo do servidor Execute o aplicativo React e o servidor. Acesse [localhost:3000/checkout](http://localhost:3000/checkout) para ver sua página de checkout. ```bash dotnet run ``` ### Executar o aplicativo Execute o servidor ASP.NET MVC e acesse [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash dotnet run ``` ### Executar o aplicativo Execute o servidor e acesse [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash java -cp target/sample-jar-with-dependencies.jar com.stripe.sample.Server ``` ### Executar o aplicativo do servidor Execute o aplicativo React e o servidor. Acesse [localhost:3000/checkout](http://localhost:3000/checkout) para ver sua página de checkout. ```bash java -cp target/sample-jar-with-dependencies.jar com.stripe.sample.Server ``` ### Executar o aplicativo Execute o aplicativo React e acesse [localhost:3000/checkout](http://localhost:3000/checkout). ```bash npm start ``` ### Fazer um pagamento de teste Para verificar se sua integração funciona, faça um pagamento de teste usando os [dados de pagamento de teste](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=elements&api-integration=paymentintents#web-test-the-integration). ### Veja seu pagamento no Dashboard Acesse o [Stripe Dashboard](https://dashboard.stripe.com/test/payments) para ver seu pagamento de teste. ## Aceite pagamentos e aprimore sua integração Está tudo pronto para você receber pagamentos com cartão usando a Stripe. Siga as etapas abaixo para adicionar mais recursos. ### Automatizar o recolhimento de impostos Calcule e recolha o valor correto de impostos sobre suas transações da Stripe. Antes de usar o Stripe Tax, você precisa ativá-lo no [Dashboard](https://dashboard.stripe.com/tax). Saiba mais sobre o [Stripe Tax](https://docs.stripe.com/tax.md) e [como adicioná-lo à sua integração do Payments](https://docs.stripe.com/tax/custom.md). ### Use a API Stripe Tax para calcular impostos Use a [API Stripe Tax](https://docs.stripe.com/api/tax/calculations/create.md) para calcular o imposto sobre a transação. Informe `currency`, `customer_details` e `line_items` do pedido no corpo da solicitação. Use o atributo `tax_amount_exclusive` do cálculo de tributo resultante para adicionar os impostos não incluídos ao total do pedido. ### Registrar uma transação fiscal após o pagamento bem-sucedido Vincule o cálculo de impostos ao PaymentIntent usando `hooks[inputs][tax][calculation]`. Isso registra os impostos recolhidos na sua conta Stripe que você pode exportar posteriormente para fins contábeis e desencadeia outras [ações da Stripe](https://docs.stripe.com/tax/payment-intent.md#automatic-actions). ### Enviar um recibo por e-mail A Stripe pode enviar um recibo por e-mail ao seu cliente usando o logotipo e o tema de cores da sua marca, que podem ser configurados no [Dashboard](https://dashboard.stripe.com/settings/branding). ### Coletar o e-mail do cliente Adicione um campo de entrada ao formulário de pagamento para coletar o e-mail. ### Adicionar e-mail ao estado Adicione uma variável para acompanhar o e-mail inserido pelo cliente. ### Adicionar e-mail ao estado Adicione uma variável para acompanhar o e-mail inserido pelo cliente. ### Fornecer o e-mail à Stripe Passe o e-mail fornecido como o valor de `receipt_email`. A Stripe envia um recibo por e-mail quando o pagamento é realizado no modo de produção (mas não faz isso em uma *área restrita* (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)). ### Salvar dados de pagamento após o pagamento Normalmente utilizado por empresas de SaaS ou e-commerce com clientes recorrentes. ### Importar recursos adicionais da Stripe Importe os pacotes `customer` e `paymentmethod` da Stripe. Use esses pacotes para armazenar dados sobre seu cliente. ### Importar recursos adicionais da Stripe Importe os modelos PaymentMethod e Customer da Stripe. Use-os para armazenar dados sobre o Customer. ### Criar um cliente A Stripe armazena o cartão em um objeto *Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments). Crie um Customer antes de criar um PaymentIntent. Também é possível armazenar o nome da loja, e-mail, endereço de entrega e outros dados no Customer. ### Criar um cliente A Stripe armazena o cartão em um objeto [Conta](https://docs.stripe.com/api/v2/core/accounts/object.md) que representa o [cliente](https://docs.stripe.com/connect/account-capabilities.md?accounts-namespace=v2#customer). Crie uma nova Conta antes de criar um PaymentIntent. Você também pode armazenar nome, e-mail, endereço de entrega e outros dados na Conta. ### Adicionar o cliente ao PaymentIntent Passe o ID do Customer para o PaymentIntent e defina `setup_future_usage` como `off_session`. `setup_future_usage` informa à Stripe como você pretende usar a forma de pagamento. Algumas regiões, como Europa e Índia, têm requisitos para a reutilização de dados de pagamento. [Saiba mais](https://docs.stripe.com/payments/payment-intents.md#future-usage) sobre a forma mais eficaz de aplicar `setup_future_usage`. Você também pode ver uma [lista de formas de pagamento aceitas](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability). Após a conclusão do PaymentIntent, a Stripe [anexa](https://docs.stripe.com/api/payment_methods/attach.md) automaticamente os dados do pagamento (em um objeto *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs)) ao Customer. ### Adicionar o cliente ao PaymentIntent Passe o ID da Conta para o PaymentIntent e defina`setup_future_usage` para`off_session`.`setup_future_usage` informa a Stripe como você planeja usar a formas de pagamento — certas regiões, como Europa e Índia, têm requisitos sobre reutilização de detalhes de pagamento.[Saiba mais](https://docs.stripe.com/payments/payment-intents.md#future-usage) sobre a forma mais eficaz de se candidatar`setup_future_usage`. Você também pode visualizar uma[lista de formas de pagamento suportados](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability). Após o sucesso do PaymentIntent, a Stripe automaticamente[anexa](https://docs.stripe.com/api/payment_methods/attach.md) os detalhes de pagamento (em um *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) object) para a Conta configurada pelo cliente. ### Cobrar o PaymentMethod salvo Quando estiver pronto para cobrar o PaymentMethod novamente, crie um PaymentIntent com o ID do Customer, o ID do PaymentMethod que você deseja cobrar e defina as sinalizações `off_session` e `confirm` como verdadeiras. ### Instale a biblioteca Node da Stripe Instale o pacote e importe-o para seu código. Se estiver começando do zero e precisar de um arquivo package.json, baixe os arquivos do projeto pelo link de download no editor de código. #### npm Instale a biblioteca: ```bash npm install --save stripe ``` #### GitHub Ou baixe o código-fonte da biblioteca stripe-node diretamente [do GitHub](https://github.com/stripe/stripe-node). ### Instalar a biblioteca Ruby da Stripe Instale o gem do Ruby da Stripe e exija-o no seu código. Alternativamente, se estiver começando do zero e precisar de um Gemfile, baixe os arquivos do projeto usando o link de download no editor de código. #### Terminal Instale o gem: ```bash gem install stripe ``` #### Bundler Adicione esta linha ao seu Gemfile: ```bash gem 'stripe' ``` #### GitHub Ou baixe o código-fonte do gem stripe-ruby diretamente [do GitHub](https://github.com/stripe/stripe-ruby). ### Instalar a biblioteca Java da Stripe Adicione a dependência à compilação e importe a biblioteca. Se você estiver começando do zero e precisar de um modelo de arquivo pom.xml (para Maven), baixe os arquivos do projeto usando o link de download no editor de código. #### Maven Adicione a dependência a seguir ao POM e substitua {VERSION} pelo número de versão que você quer usar. ```bash \ncom.stripe\nstripe-java\n{VERSION}\n ``` #### Gradle Adicione a dependência ao arquivo build.gradle e substitua {VERSION} pelo número de versão que você quer usar. ```bash implementation "com.stripe:stripe-java:{VERSION}" ``` #### GitHub Baixe o JAR diretamente [do GitHub](https://github.com/stripe/stripe-java/releases/latest). ### Instalar o pacote Python da Stripe Instale o pacote da Stripe e importe-o no seu código. Se você estiver começando do zero e precisar de um arquivo requirements.txt, baixe os arquivos do projeto usando o link de download no editor de código. #### pip Instale o pacote usando pip: ```bash pip3 install stripe ``` #### GitHub Faça o download diretamente o código-fonte da biblioteca Stripe-Python [do GitHub](https://github.com/stripe/stripe-python). ### Instalar a biblioteca PHP da Stripe Instale a biblioteca com o composer e inicialize-a com sua chave de API secreta. Se você estiver começando do zero e precisar de um arquivo composer.json, baixe os arquivos usando o link de download no editor de código. #### Composer Instale a biblioteca: ```bash composer require stripe/stripe-php ``` #### GitHub Ou baixe o código-fonte da biblioteca stripe-php diretamente [do GitHub](https://github.com/stripe/stripe-php). ### Configurar o servidor Adicione a dependência à compilação e importe a biblioteca. Se você estiver começando do zero e precisar de um arquivo go.mod, baixe os arquivos do projeto usando o link de download no editor de código. #### Go Não se esqueça de inicializar com Go Modules: ```bash go get -u github.com/stripe/stripe-go/v85 ``` #### GitHub Ou baixe o código-fonte do módulo stripe-go diretamente [do GitHub](https://github.com/stripe/stripe-go). ### Instalar a biblioteca Stripe.net Instale o pacote como .NET ou NuGet. Se estiver começando do zero, você também pode baixar os arquivos com um .csproj configurado. #### dotnet Instale a biblioteca: ```bash dotnet add package Stripe.net ``` #### NuGet Instale a biblioteca: ```bash Install-Package Stripe.net ``` #### GitHub Ou baixe o código-fonte da biblioteca Stripe.net diretamente [do GitHub](https://github.com/stripe/stripe-dotnet). ### Instalar as bibliotecas da Stripe Instale os pacotes e importe-os para o código. Se estiver começando do zero e precisar de um arquivo `package.json`, baixe os arquivos do projeto pelo link de download no editor de código. Instale as bibliotecas: ```bash npm install --save stripe @stripe/stripe-js next ``` ### Criar um PaymentIntent Adicione um endpoint ao servidor que cria um [PaymentIntent](https://docs.stripe.com/api/payment_intents.md). Um PaymentIntent acompanha o ciclo de vida de pagamento do cliente, registrando todas as tentativas com falha e garantindo que a cobrança seja efetuada uma só vez. Retorne o *segredo do 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)) do PaymentIntent na resposta para finalizar o pagamento no cliente. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Instalar o SDK O SDK para iOS da Stripe é de [código aberto](https://github.com/stripe/stripe-ios), [totalmente documentado](https://stripe.dev/stripe-ios/) e compatível com aplicativos que aceitam iOS 13 ou superior. Importe o SDK da Stripe para o View Controller da tela de checkout. #### Gerenciador de pacotes Swift No Xcode, selecione **Arquivo** > **Adicionar dependências de pacote…** e insira `https://github.com/stripe/stripe-ios-spm` como URL do repositório. Selecione o número da versão mais recente da nossa [página de lançamentos](https://github.com/stripe/stripe-ios/releases) e adicione o módulo `StripePaymentSheet` ao destino do seu aplicativo. #### CocoaPods Adicione esta linha ao Podfile e passe a usar o arquivo .xcworkspace para abrir o projeto no Xcode (em vez do arquivo .xcodeproj). ```bash pod 'StripePaymentSheet' ``` #### Carthage Adicione esta linha ao Cartfile. ```bash github "stripe/stripe-ios" ``` #### Estrutura manual Para incluir a Stripe no seu projeto, baixe e descompacte o arquivo Stripe.framework.zip de uma [versão no GitHub](https://github.com/stripe/stripe-ios/releases). Arraste os arquivos necessários do XCFramework para as configurações de “Binários incorporados” no projeto do Xcode. Selecione “Copiar itens se necessário”. ### Configurar o SDK Configure o SDK da Stripe com sua [chave de API publicável](https://docs.stripe.com/keys.md#obtain-api-keys) da Stripe. A codificação da chave de API publicável no SDK é apenas para demonstração. Em um aplicativo de produção, você deve obter a chave da API no servidor. ### Acessar um PaymentIntent Faça uma solicitação ao seu servidor para um PaymentIntent assim que a exibição carregar. Armazene uma referência para o *segredo do 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)) do PaymentIntent retornado pelo servidor; o Payment Sheet usa esse segredo para concluir o pagamento posteriormente. ### Configurar e apresentar a descrição da compra Crie uma instância de `PaymentSheet` usando o segredo do cliente obtido anteriormente e apresente-o no controlador de exibição. Use a estrutura `PaymentSheet.Configuration` para [personalizar](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html) a descrição da compra. ### Gerenciar o resultado do pagamento Use o bloco de conclusão para gerenciar o resultado do pagamento. Se o pagamento falhar com um [erro](https://docs.stripe.com/error-codes.md), exiba a mensagem apropriada ao cliente para que ele possa agir e tentar novamente. Se nenhum erro ocorrer, informe ao cliente que o pagamento foi efetuado. ### Fazer um pagamento de teste #### iOS Para verificar se sua integração funciona, faça um pagamento de teste usando [dados de pagamento de teste](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios#ios-test-the-integration). #### Android Para verificar se sua integração funciona, faça um pagamento de teste usando [dados de pagamento de teste](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=android#android-test-the-integration). ### Veja seu pagamento no Dashboard Acesse o [Stripe Dashboard](https://dashboard.stripe.com/test/payments) para ver o pagamento de teste. ## Aceite pagamentos e aprimore sua integração Está tudo pronto para você receber pagamentos com cartão usando a Stripe. Siga as etapas abaixo para adicionar mais recursos. ### Automatizar o recolhimento de impostos Calcule e recolha o valor correto de impostos sobre suas transações da Stripe. Antes de usar o Stripe Tax, você precisa ativá-lo no [Dashboard](https://dashboard.stripe.com/tax). Saiba mais sobre o [Stripe Tax](https://docs.stripe.com/tax.md) e [como adicioná-lo à sua integração do Payments](https://docs.stripe.com/tax/custom.md). ### Use a API Stripe Tax para calcular impostos Use a [API Stripe Tax](https://docs.stripe.com/api/tax/calculations/create.md) para calcular o imposto sobre a transação. Informe `currency`, `customer_details` e `line_items` do pedido no corpo da solicitação. Use o atributo `tax_amount_exclusive` do cálculo de tributo resultante para adicionar os impostos não incluídos ao total do pedido. ### Registrar uma transação fiscal após o pagamento bem-sucedido Vincule o cálculo de impostos ao PaymentIntent usando `hooks[inputs][tax][calculation]`. Isso registra os impostos recolhidos na sua conta Stripe que você pode exportar posteriormente para fins contábeis e desencadeia outras [ações da Stripe](https://docs.stripe.com/tax/payment-intent.md#automatic-actions). ### Permitir formas de pagamento postergadas Algumas formas de pagamento não conseguem garantir que você receberá fundos do seu cliente no final do checkout porque podem demorar para fazer a liquidação (por exemplo, a maioria dos débitos bancários, como SEPA ou ACH) ou precisam que os clientes realizem ações para concluir (por exemplo, OXXO, Konbini, Boleto). Use esta sinalização para habilitar formas de pagamento postergadas. Se habilitar esse recurso, verifique se sua integração do servidor escuta os [webhooks](https://docs.stripe.com/payments/payment-methods.md#payment-notification) para receber notificações em caso de conclusão ou falha no pagamento. ### Adicionar suporte do Apple Pay Para habilitar o Apple Pay, informe seu [ID de comerciante do Apple Pay](https://support.stripe.com/questions/enable-apple-pay-on-your-stripe-account) e o [código do país](https://dashboard.stripe.com/settings/account) da sua conta Stripe. ### Adicionar suporte do Google Pay Para usar o Google Pay, primeiro habilite a API do Google Pay no seu AndroidManifest.xml. Habilite o Google Pay passando um objeto [PaymentSheet.GooglePayConfiguration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-google-pay-configuration/index.html) com o ambiente do Google Pay (produção ou teste) e o [código do país da sua empresa](https://dashboard.stripe.com/settings/account) quando inicializar [PaymentSheet.Configuration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-configuration/index.html). ### Personalizar a cor principal do botão Considere usar uma cor personalizada para o botão principal que melhor corresponda à marca ou identidade visual do seu aplicativo. ### Habilitar leitura de cartões A leitura de cartão pode ajudar a aumentar sua taxa de conversão ao eliminar a complicação da inserção manual do cartão. Para habilitar a leitura do cartão, defina `NSCameraUsageDescription` na `Info.plist` do seu aplicativo e informe um motivo para acessar a câmera (por exemplo, “Para ler cartões”). > A leitura de cartão só é aceita em dispositivos que executam iOS 13 ou mais recente. ### Habilitar leitura de cartões A leitura de cartão pode ajudar a aumentar sua taxa de conversão, eliminando a complicação da inserção manual do cartão. Para ativar a leitura de cartões, adicione `stripecardscan` ao bloco `dependencies` do arquivo [app/build.gradle](https://developer.android.com/studio/build/dependencies): #### Excelente ```groovy implementation 'com.stripe:stripecardscan:23.3.0' ``` ### Salvar dados de pagamento após o pagamento Normalmente utilizado por empresas de SaaS ou e-commerce com clientes recorrentes. ### Importar recursos adicionais da Stripe Importe os pacotes `customer` e `paymentmethod` da Stripe. Use esses pacotes para armazenar dados sobre seu cliente. ### Importar recursos adicionais da Stripe Importe os modelos PaymentMethod e Customer da Stripe. Use-os para armazenar dados sobre o Customer. ### Criar um cliente A Stripe armazena o cartão em um objeto *Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments). Crie um Customer antes de criar um PaymentIntent. Também é possível armazenar o nome da loja, e-mail, endereço de entrega e outros dados no Customer. ### Criar um cliente A Stripe armazena o cartão em um objeto [Conta](https://docs.stripe.com/api/v2/core/accounts/object.md) que representa o [cliente](https://docs.stripe.com/connect/account-capabilities.md?accounts-namespace=v2#customer). Crie uma nova Conta antes de criar um PaymentIntent. Você também pode armazenar nome, e-mail, endereço de entrega e outros dados na Conta. ### Adicionar o cliente ao PaymentIntent Passe o ID do Customer para o PaymentIntent e defina `setup_future_usage` como `off_session`. `setup_future_usage` informa à Stripe como você pretende usar a forma de pagamento. Algumas regiões, como Europa e Índia, têm requisitos para a reutilização de dados de pagamento. [Saiba mais](https://docs.stripe.com/payments/payment-intents.md#future-usage) sobre a forma mais eficaz de aplicar `setup_future_usage`. Você também pode ver uma [lista de formas de pagamento aceitas](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability). Após a conclusão do PaymentIntent, a Stripe [anexa](https://docs.stripe.com/api/payment_methods/attach.md) automaticamente os dados do pagamento (em um objeto *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs)) ao Customer. ### Adicionar o cliente ao PaymentIntent Passe o ID da Conta para o PaymentIntent e defina`setup_future_usage` para`off_session`.`setup_future_usage` informa a Stripe como você planeja usar a formas de pagamento — certas regiões, como Europa e Índia, têm requisitos sobre reutilização de detalhes de pagamento.[Saiba mais](https://docs.stripe.com/payments/payment-intents.md#future-usage) sobre a forma mais eficaz de se candidatar`setup_future_usage`. Você também pode visualizar uma[lista de formas de pagamento suportados](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability). Após o sucesso do PaymentIntent, a Stripe automaticamente[anexa](https://docs.stripe.com/api/payment_methods/attach.md) os detalhes de pagamento (em um *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) object) para a Conta configurada pelo cliente. ### Cobrar o PaymentMethod salvo Quando estiver pronto para cobrar o PaymentMethod novamente, crie um PaymentIntent com o ID do Customer, o ID do PaymentMethod que você deseja cobrar e defina as sinalizações `off_session` e `confirm` como verdadeiras. ### Recolha endereços usando o Address Element Recolha endereços de entrega ou cobrança locais e internacionais de seus clientes. ### Recolha endereços usando o Address Element Recolha endereços de entrega ou cobrança locais e internacionais de seus clientes. Se você usa o Address Element, tem a opção de usar o [SDK do Google Places](https://developers.google.com/maps/documentation/places/android-sdk/overview) para obter sugestões de preenchimento automático de endereços. Para habilitar sugestões de preenchimento automático, adicione `places` ao bloco de dependências do arquivo [app/build.gradle](https://developer.android.com/studio/build/dependencies): #### Excelente ```groovy implementation 'com.google.android.libraries.places:places:2.6.0' ``` ### Instale a biblioteca Node da Stripe Instale o pacote e importe-o para seu código. Se estiver começando do zero e precisar de um arquivo package.json, baixe os arquivos do projeto pelo link de download no editor de código. #### npm Instale a biblioteca: ```bash npm install --save stripe ``` #### GitHub Ou baixe o código-fonte da biblioteca stripe-node diretamente [do GitHub](https://github.com/stripe/stripe-node). ### Instalar a biblioteca Ruby da Stripe Instale o gem do Ruby da Stripe e exija-o no seu código. Alternativamente, se estiver começando do zero e precisar de um Gemfile, baixe os arquivos do projeto usando o link de download no editor de código. #### Terminal Instale o gem: ```bash gem install stripe ``` #### Bundler Adicione esta linha ao seu Gemfile: ```bash gem 'stripe' ``` #### GitHub Ou baixe o código-fonte do gem stripe-ruby diretamente [do GitHub](https://github.com/stripe/stripe-ruby). ### Instalar a biblioteca Java da Stripe Adicione a dependência à compilação e importe a biblioteca. Se você estiver começando do zero e precisar de um modelo de arquivo pom.xml (para Maven), baixe os arquivos do projeto usando o link de download no editor de código. #### Maven Adicione a dependência a seguir ao POM e substitua {VERSION} pelo número de versão que você quer usar. ```bash \ncom.stripe\nstripe-java\n{VERSION}\n ``` #### Gradle Adicione a dependência ao arquivo build.gradle e substitua {VERSION} pelo número de versão que você quer usar. ```bash implementation "com.stripe:stripe-java:{VERSION}" ``` #### GitHub Baixe o JAR diretamente [do GitHub](https://github.com/stripe/stripe-java/releases/latest). ### Instalar o pacote Python da Stripe Instale o pacote da Stripe e importe-o no seu código. Se você estiver começando do zero e precisar de um arquivo requirements.txt, baixe os arquivos do projeto usando o link de download no editor de código. #### pip Instale o pacote usando pip: ```bash pip3 install stripe ``` #### GitHub Faça o download diretamente o código-fonte da biblioteca Stripe-Python [do GitHub](https://github.com/stripe/stripe-python). ### Instalar a biblioteca PHP da Stripe Instale a biblioteca com o composer e inicialize-a com sua chave de API secreta. Se você estiver começando do zero e precisar de um arquivo composer.json, baixe os arquivos usando o link de download no editor de código. #### Composer Instale a biblioteca: ```bash composer require stripe/stripe-php ``` #### GitHub Ou baixe o código-fonte da biblioteca stripe-php diretamente [do GitHub](https://github.com/stripe/stripe-php). ### Configurar o servidor Adicione a dependência à compilação e importe a biblioteca. Se você estiver começando do zero e precisar de um arquivo go.mod, baixe os arquivos do projeto usando o link de download no editor de código. #### Go Não se esqueça de inicializar com Go Modules: ```bash go get -u github.com/stripe/stripe-go/v85 ``` #### GitHub Ou baixe o código-fonte do módulo stripe-go diretamente [do GitHub](https://github.com/stripe/stripe-go). ### Instalar a biblioteca Stripe.net Instale o pacote como .NET ou NuGet. Se estiver começando do zero, você também pode baixar os arquivos com um .csproj configurado. #### dotnet Instale a biblioteca: ```bash dotnet add package Stripe.net ``` #### NuGet Instale a biblioteca: ```bash Install-Package Stripe.net ``` #### GitHub Ou baixe o código-fonte da biblioteca Stripe.net diretamente [do GitHub](https://github.com/stripe/stripe-dotnet). ### Instalar as bibliotecas da Stripe Instale os pacotes e importe-os para o código. Se estiver começando do zero e precisar de um arquivo `package.json`, baixe os arquivos do projeto pelo link de download no editor de código. Instale as bibliotecas: ```bash npm install --save stripe @stripe/stripe-js next ``` ### Criar um PaymentIntent Adicione um endpoint ao servidor que cria um [PaymentIntent](https://docs.stripe.com/api/payment_intents.md). Um PaymentIntent acompanha o ciclo de vida de pagamento do cliente, registrando todas as tentativas com falha e garantindo que a cobrança seja efetuada uma só vez. Retorne o *segredo do 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)) do PaymentIntent na resposta para finalizar o pagamento no cliente. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Configurar formas de pagamento A Stripe habilita cartões e outras formas de pagamento comuns por padrão com [formas de pagamento dinâmicas](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Você pode atualizar e configurar formas de pagamento no [Dashboard](https://dashboard.stripe.com/settings/payment_methods) com no-code exigido. A Stripe filtra formas de pagamento com base na elegibilidade e preferências de forma de pagamento, em seguida, ordena e exibe por probabilidade com base em fatores como valor, moeda e localização do comprador. ### Instalar o SDK O SDK para Android da Stripe é de [código aberto](https://github.com/stripe/stripe-android), tem uma [documentação completa](https://stripe.dev/stripe-android/) e é compatível com dispositivos que têm Android 5.0 (nível de API 21) ou mais recente. Para instalar o SDK, adicione `stripe-android` ao bloco de dependências do arquivo `build.gradle`: #### Excelente ```groovy implementation 'com.stripe:stripe-android:23.3.0' ``` > Para obter mais informações sobre a versão mais recente e as versões anteriores do SDK, consulte a página [Releases](https://github.com/stripe/stripe-android/releases) no GitHub. ### Configurar o SDK Configure o SDK da Stripe com sua [chave de API publicável](https://docs.stripe.com/keys.md#obtain-api-keys) da Stripe. A codificação da chave de API publicável no SDK é apenas para demonstração. Em um aplicativo de produção, você deve obter a chave da API no servidor. ### Acessar um PaymentIntent Faça uma solicitação ao seu servidor para um PaymentIntent assim que a exibição carregar. Armazene uma referência para o *segredo do 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)) do PaymentIntent retornado pelo servidor; o Payment Sheet usa esse segredo para concluir o pagamento posteriormente. ### Configurar e apresentar a descrição da compra Crie uma instância de `PaymentSheet` usando o segredo do cliente obtido anteriormente e apresente-o no controlador de exibição. Use a estrutura `PaymentSheet.Configuration` para [personalizar](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html) a descrição da compra. ### Gerenciar o resultado do pagamento Use o bloco de conclusão para gerenciar o resultado do pagamento. Se o pagamento falhar com um [erro](https://docs.stripe.com/error-codes.md), exiba a mensagem apropriada ao cliente para que ele possa agir e tentar novamente. Se nenhum erro ocorrer, informe ao cliente que o pagamento foi efetuado. ### Fazer um pagamento de teste #### iOS Para verificar se sua integração funciona, faça um pagamento de teste usando [dados de pagamento de teste](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios#ios-test-the-integration). #### Android Para verificar se sua integração funciona, faça um pagamento de teste usando [dados de pagamento de teste](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=android#android-test-the-integration). ### Veja seu pagamento no Dashboard Acesse o [Stripe Dashboard](https://dashboard.stripe.com/test/payments) para ver o pagamento de teste. ## Aceite pagamentos e aprimore sua integração Está tudo pronto para você receber pagamentos com cartão usando a Stripe. Siga as etapas abaixo para adicionar mais recursos. ### Automatizar o recolhimento de impostos Calcule e recolha o valor correto de impostos sobre suas transações da Stripe. Antes de usar o Stripe Tax, você precisa ativá-lo no [Dashboard](https://dashboard.stripe.com/tax). Saiba mais sobre o [Stripe Tax](https://docs.stripe.com/tax.md) e [como adicioná-lo à sua integração do Payments](https://docs.stripe.com/tax/custom.md). ### Use a API Stripe Tax para calcular impostos Use a [API Stripe Tax](https://docs.stripe.com/api/tax/calculations/create.md) para calcular o imposto sobre a transação. Informe `currency`, `customer_details` e `line_items` do pedido no corpo da solicitação. Use o atributo `tax_amount_exclusive` do cálculo de tributo resultante para adicionar os impostos não incluídos ao total do pedido. ### Registrar uma transação fiscal após o pagamento bem-sucedido Vincule o cálculo de impostos ao PaymentIntent usando `hooks[inputs][tax][calculation]`. Isso registra os impostos recolhidos na sua conta Stripe que você pode exportar posteriormente para fins contábeis e desencadeia outras [ações da Stripe](https://docs.stripe.com/tax/payment-intent.md#automatic-actions). ### Permitir formas de pagamento postergadas Algumas formas de pagamento não conseguem garantir que você receberá fundos do seu cliente no final do checkout porque podem demorar para fazer a liquidação (por exemplo, a maioria dos débitos bancários, como SEPA ou ACH) ou precisam que os clientes realizem ações para concluir (por exemplo, OXXO, Konbini, Boleto). Use esta sinalização para habilitar formas de pagamento postergadas. Se habilitar esse recurso, verifique se sua integração do servidor escuta os [webhooks](https://docs.stripe.com/payments/payment-methods.md#payment-notification) para receber notificações em caso de conclusão ou falha no pagamento. ### Adicionar suporte do Apple Pay Para habilitar o Apple Pay, informe seu [ID de comerciante do Apple Pay](https://support.stripe.com/questions/enable-apple-pay-on-your-stripe-account) e o [código do país](https://dashboard.stripe.com/settings/account) da sua conta Stripe. ### Adicionar suporte do Google Pay Para usar o Google Pay, primeiro habilite a API do Google Pay no seu AndroidManifest.xml. Habilite o Google Pay passando um objeto [PaymentSheet.GooglePayConfiguration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-google-pay-configuration/index.html) com o ambiente do Google Pay (produção ou teste) e o [código do país da sua empresa](https://dashboard.stripe.com/settings/account) quando inicializar [PaymentSheet.Configuration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-configuration/index.html). ### Personalizar a cor principal do botão Considere usar uma cor personalizada para o botão principal que melhor corresponda à marca ou identidade visual do seu aplicativo. ### Habilitar leitura de cartões A leitura de cartão pode ajudar a aumentar sua taxa de conversão ao eliminar a complicação da inserção manual do cartão. Para habilitar a leitura do cartão, defina `NSCameraUsageDescription` na `Info.plist` do seu aplicativo e informe um motivo para acessar a câmera (por exemplo, “Para ler cartões”). > A leitura de cartão só é aceita em dispositivos que executam iOS 13 ou mais recente. ### Habilitar leitura de cartões A leitura de cartão pode ajudar a aumentar sua taxa de conversão, eliminando a complicação da inserção manual do cartão. Para ativar a leitura de cartões, adicione `stripecardscan` ao bloco `dependencies` do arquivo [app/build.gradle](https://developer.android.com/studio/build/dependencies): #### Excelente ```groovy implementation 'com.stripe:stripecardscan:23.3.0' ``` ### Salvar dados de pagamento após o pagamento Normalmente utilizado por empresas de SaaS ou e-commerce com clientes recorrentes. ### Importar recursos adicionais da Stripe Importe os pacotes `customer` e `paymentmethod` da Stripe. Use esses pacotes para armazenar dados sobre seu cliente. ### Importar recursos adicionais da Stripe Importe os modelos PaymentMethod e Customer da Stripe. Use-os para armazenar dados sobre o Customer. ### Criar um cliente A Stripe armazena o cartão em um objeto *Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments). Crie um Customer antes de criar um PaymentIntent. Também é possível armazenar o nome da loja, e-mail, endereço de entrega e outros dados no Customer. ### Criar um cliente A Stripe armazena o cartão em um objeto [Conta](https://docs.stripe.com/api/v2/core/accounts/object.md) que representa o [cliente](https://docs.stripe.com/connect/account-capabilities.md?accounts-namespace=v2#customer). Crie uma nova Conta antes de criar um PaymentIntent. Você também pode armazenar nome, e-mail, endereço de entrega e outros dados na Conta. ### Adicionar o cliente ao PaymentIntent Passe o ID do Customer para o PaymentIntent e defina `setup_future_usage` como `off_session`. `setup_future_usage` informa à Stripe como você pretende usar a forma de pagamento. Algumas regiões, como Europa e Índia, têm requisitos para a reutilização de dados de pagamento. [Saiba mais](https://docs.stripe.com/payments/payment-intents.md#future-usage) sobre a forma mais eficaz de aplicar `setup_future_usage`. Você também pode ver uma [lista de formas de pagamento aceitas](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability). Após a conclusão do PaymentIntent, a Stripe [anexa](https://docs.stripe.com/api/payment_methods/attach.md) automaticamente os dados do pagamento (em um objeto *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs)) ao Customer. ### Adicionar o cliente ao PaymentIntent Passe o ID da Conta para o PaymentIntent e defina`setup_future_usage` para`off_session`.`setup_future_usage` informa a Stripe como você planeja usar a formas de pagamento — certas regiões, como Europa e Índia, têm requisitos sobre reutilização de detalhes de pagamento.[Saiba mais](https://docs.stripe.com/payments/payment-intents.md#future-usage) sobre a forma mais eficaz de se candidatar`setup_future_usage`. Você também pode visualizar uma[lista de formas de pagamento suportados](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability). Após o sucesso do PaymentIntent, a Stripe automaticamente[anexa](https://docs.stripe.com/api/payment_methods/attach.md) os detalhes de pagamento (em um *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) object) para a Conta configurada pelo cliente. ### Cobrar o PaymentMethod salvo Quando estiver pronto para cobrar o PaymentMethod novamente, crie um PaymentIntent com o ID do Customer, o ID do PaymentMethod que você deseja cobrar e defina as sinalizações `off_session` e `confirm` como verdadeiras. ### Recolha endereços usando o Address Element Recolha endereços de entrega ou cobrança locais e internacionais de seus clientes. ### Recolha endereços usando o Address Element Recolha endereços de entrega ou cobrança locais e internacionais de seus clientes. Se você usa o Address Element, tem a opção de usar o [SDK do Google Places](https://developers.google.com/maps/documentation/places/android-sdk/overview) para obter sugestões de preenchimento automático de endereços. Para habilitar sugestões de preenchimento automático, adicione `places` ao bloco de dependências do arquivo [app/build.gradle](https://developer.android.com/studio/build/dependencies): #### Excelente ```groovy implementation 'com.google.android.libraries.places:places:2.6.0' ``` ## Próximas etapas #### Web #### [Recolha dados do endereço de cobrança](https://docs.stripe.com/elements/address-element.md) Por padrão, o Payment Element coleta apenas os dados necessários do endereço de cobrança. Para coletar o endereço de cobrança completo de um cliente (para calcular o imposto para mercadorias e serviços digitais, por exemplo) ou o endereço de entrega, use o Address Element. #### iOS #### Android #### [Repasses](https://docs.stripe.com/payouts.md) Saiba como mover fundos da conta Stripe para sua conta bancária. #### [Reembolsos](https://docs.stripe.com/refunds.md) Gerencie solicitações de reembolso usando a API da Stripe ou o Dashboard. #### [Execução](https://docs.stripe.com/webhooks/quickstart.md) Crie um destino de evento para enviar eventos ao seu endpoint de webhook para executar pedidos após a conclusão de um pagamento e para gerenciar outros eventos críticos.