# Creare un'integrazione iniziale Istruzioni per gli LLM: Stripe consiglia di utilizzare l’API Checkout Sessions con Payment Element anziché Payment Intents per la maggior parte delle integrazioni. Checkout Sessions copre casi d’uso simili a quelli di Payment Intents (raccolta di pagamenti di base utilizzando `price_data` o creazione di un checkout completo con voci riga, imposte e così via). Alcune funzioni, come Adaptive Pricing, sono disponibili solo con Checkout Sessions. Non utilizzare l’API Payment Intent a meno che l’utente non lo richieda esplicitamente, poiché richiede una quantità di codice significativamente maggiore. Ulteriori informazioni sugli elementi con l’API Checkout Sessions: https://docs.stripe.com/payments/quickstart-checkout-sessions. con Checkout Sessions (`ui_mode: "elements"`) e Payment Element, `client_secret` inizializza Checkout stesso (`stripe.initCheckoutElementsSdk`, oppure utilizza CheckoutElementsProvider con React) e tu confermi il pagamento sul lato client in modo diverso. Se utilizzi React, assicurati di importare da `@stripe/react-stripe-js/checkout`, utilizza `CheckoutElementsProvider` con la chiave privata client e conferma utilizzando `checkout.confirm`. Se utilizzi HTML, assicurati di utilizzare `checkout = stripe.initCheckoutElementsSdk({clientSecret: promise}); checkout.createPaymentElement(); paymentElement = checkout.createPaymentElement(); paymentElement.mount("#payment-element");` e conferma con `loadActionsResult = await checkout.loadActions(); actions = loadActionsResult.actions; error = await actions.confirm();`. # Creazione di una pagina di completamento della transazione con l’API Payment Intents Integrare un modulo di pagamento Stripe personalizzato nel tuo sito web o applicazione Il codice lato client e lato server crea un modulo di pagamento con gli elementi [Web](https://docs.stripe.com/payments/elements.md) o [Mobile](https://docs.stripe.com/payments/mobile.md) di Stripe per consentirti di accettare i pagamenti. Per creare un’integrazione personalizzata che vada oltre le nozioni di base di questa guida rapida, consulta [Accettare un pagamento](https://docs.stripe.com/payments/accept-a-payment.md?&ui=elements). Per conoscere i diversi scenari di pagamento, come gli [abbonamenti](https://docs.stripe.com/billing/subscriptions/build-subscriptions.md?payment-ui=elements) e altri prodotti Stripe, [confronta le integrazioni di pagamento](https://docs.stripe.com/payments/online-payments.md#compare-features-and-availability). > #### Ti interessa utilizzare Stripe Tax, sconti, spedizione o conversione di valuta? > > Stripe dispone di un’integrazione Payment Element che gestisce per tuo conto tasse, sconti, spedizioni e conversioni di valuta. Vedi [Creazione di una pagina di completamento della transazione](https://docs.stripe.com/payments/quickstart-checkout-sessions.md) per saperne di più. // 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 ~~~ ### Installare la libreria Node di Stripe Installa il pacchetto e importalo nel tuo codice. In alternativa, se inizi da zero e hai bisogno di un file package.json, scarica i file del progetto utilizzando il link Download nell’editor del codice. #### npm Installa la libreria: ```bash npm install --save stripe ``` #### GitHub In alternativa scarica il codice sorgente della libreria stripe-node direttamente [da GitHub](https://github.com/stripe/stripe-node). ### Installare la libreria Ruby di Stripe Installa il ruby gem di Stripe e importalo nel tuo codice. In alternativa, se inizi da zero e hai bisogno di un Gemfile, scarica i file del progetto utilizzando il link Download nell’editor del codice. #### Terminal Installa il gem: ```bash gem install stripe ``` #### Bundler Aggiungi questa riga al Gemfile: ```bash gem 'stripe' ``` #### GitHub In alternativa scarica il codice sorgente della libreria stripe-ruby direttamente [da GitHub](https://github.com/stripe/stripe-ruby). ### Installare la libreria Java di Stripe Aggiungi la dipendenza alla tua build e importa la libreria. In alternativa, se inizi da zero e hai bisogno di un file pom.xml (per Maven), scarica i file del progetto utilizzando il link Download nell’editor del codice. #### Maven Aggiungi la seguente dipendenza al tuo POM e sostituisci {VERSION} con il numero di versione che vuoi utilizzare. ```bash \ncom.stripe\nstripe-java\n{VERSION}\n ``` #### Gradle Aggiungi la dipendenza al tuo file build.gradle e sostituisci {VERSION} con il numero di versione che vuoi utilizzare. ```bash implementation "com.stripe:stripe-java:{VERSION}" ``` #### GitHub Scarica il JAR direttamente [da GitHub](https://github.com/stripe/stripe-java/releases/latest). ### Installare il pacchetto Python di Stripe Installa il pacchetto Stripe e importalo nel tuo codice. In alternativa, se inizi da zero e hai bisogno di un file requirements.txt, scarica i file del progetto utilizzando il link Download nell’editor del codice. #### pip Installa il pacchetto tramite pip: ```bash pip3 install stripe ``` #### GitHub Scarica il codice sorgente della libreria stripe-python direttamente [da GitHub](https://github.com/stripe/stripe-python). ### Installare la libreria PHP di Stripe Installa la libreria con composer e inizializzala con la tua chiave API privata. In alternativa, se inizi da zero e hai bisogno di un file composer.json, scarica i file utilizzando il link Download nell’editor del codice. #### Composer Installa la libreria: ```bash composer require stripe/stripe-php ``` #### GitHub In alternativa scarica il codice sorgente della libreria stripe-php direttamente [da GitHub](https://github.com/stripe/stripe-php). ### Configurare il server Aggiungi la dipendenza alla tua build e importa la libreria. In alternativa, se inizi da zero e hai bisogno di un file go.mod, scarica i file del progetto utilizzando il link Download nell’editor del codice. #### Go Assicurati di eseguire l’inizializzazione con Go Modules: ```bash go get -u github.com/stripe/stripe-go/v85 ``` #### GitHub In alternativa scarica il codice sorgente della libreria stripe-go direttamente [da GitHub](https://github.com/stripe/stripe-go). ### Installare la libreria Stripe.net Installa il pacchetto con dotnet o NuGet. In alternativa, se inizi da zero, scarica i file contenenti un file .csproj configurato. #### dotnet Installa la libreria: ```bash dotnet add package Stripe.net ``` #### NuGet Installa la libreria: ```bash Install-Package Stripe.net ``` #### GitHub In alternativa scarica il codice sorgente della libreria Stripe.net direttamente [da GitHub](https://github.com/stripe/stripe-dotnet). ### Installare le librerie Stripe Installa i pacchetti e importali nel tuo codice. In alternativa, se inizi da zero e hai bisogno di un file `package.json`, scarica i file del progetto utilizzando il link nell’editor del codice. Installa le librerie: ```bash npm install --save stripe @stripe/stripe-js next ``` ### Creare un PaymentIntent Aggiungi sul server un endpoint che crei un [PaymentIntent](https://docs.stripe.com/api/payment_intents.md). Un PaymentIntent segue il ciclo di vita del pagamento del cliente tenendo traccia di eventuali tentativi di pagamento non riusciti per garantire che l’importo venga addebitato solo una volta. Per completare il pagamento sul client, restituisci la *chiave privata client* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) del PaymentIntent nella risposta. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Aggiungere Stripe all’app React Usa *Stripe.js* (Use Stripe.js’ APIs to tokenize customer information, collect sensitive card data, and accept payments with browser payment APIs) e la [libreria dell’interfaccia utente di Stripe Elements](https://docs.stripe.com/sdks/stripejs-react.md) per garantire la *conformità 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) assicurandoti che i dati di pagamento vengano inviati direttamente a Stripe senza passare mai sul tuo server. ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` ### Aggiungere Stripe all’app React Usa *Stripe.js* (Use Stripe.js’ APIs to tokenize customer information, collect sensitive card data, and accept payments with browser payment APIs) e la [libreria dell’interfaccia utente di Stripe Elements](https://docs.stripe.com/sdks/stripejs-react.md) per garantire la *conformità 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) assicurandoti che i dati di pagamento vengano inviati direttamente a Stripe senza passare mai sul tuo server. ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` ### Caricare la libreria Stripe.js Per configurare la libreria Stripe, chiama `loadStripe()` con la tua [chiave API pubblicabile](https://docs.stripe.com/keys.md#obtain-api-keys) di Stripe. ### Caricare la libreria Stripe.js Per configurare la libreria Stripe, chiama `loadStripe()` con la tua [chiave API pubblicabile](https://docs.stripe.com/keys.md#obtain-api-keys) di Stripe. ### Caricare la libreria Stripe.js Usa *Stripe.js* (Use Stripe.js’ APIs to tokenize customer information, collect sensitive card data, and accept payments with browser payment APIs) per mantenere la *conformità alle norme 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) assicurandoti che i dati di pagamento siano inviati direttamente a Stripe senza che vengano memorizzati sul tuo server. Carica sempre Stripe.js da js.stripe.com per garantire la conformità. Non includere lo script in un pacchetto e non utilizzarne una copia in self-hosting. ### Definire il modulo di pagamento Aggiungi un segnaposto vuoto `div` al tuo modulo di pagamento per ogni Element che monterai. Stripe inserisce un iframe in ogni `div` per raccogliere in modo sicuro l’indirizzo email e i dati di pagamento del cliente. ### Inizializzare Stripe.js Inizializza Stripe.js con la tua [chiave API pubblicabile](https://docs.stripe.com/keys.md#obtain-api-keys). Utilizzerai Stripe.js per creare il Payment Element e completare il pagamento sul client. ### Recuperare un PaymentIntent Invia immediatamente una richiesta all’endpoint sul tuo server per creare un nuovo PaymentIntent non appena viene caricata la pagina di pagamento. Il parametro `clientSecret` restituito dall’endpoint viene utilizzato per completare il pagamento. ### Inizializzare Stripe Elements Specifica la promessa restituita da `loadStripe` nel provider di Elements. Ciò consente ai componenti secondari di accedere al servizio Stripe con l’utente Elements. Inoltre, specifica la chiave privata client come opzione al provider di Elements. ### Inizializzare Stripe Elements Specifica la promessa restituita da `loadStripe` nel provider di Elements. Ciò consente ai componenti secondari di accedere al servizio Stripe tramite l’utente Elements. Inoltre, specifica la chiave privata client come opzione al provider di Elements. ### Inizializzare Stripe Elements Inizializza la [libreria Stripe Elements UI](https://docs.stripe.com/js/elements_object/create) con la chiave privata client. Elements gestisce i componenti dell’interfaccia utente necessari per raccogliere i dati di pagamento. ### Configurare lo stato Inizializza uno stato per tenere traccia del pagamento, visualizzare gli errori e gestire l’interfaccia utente. ### Configurare lo stato Inizializza uno stato per tenere traccia del pagamento, visualizzare gli errori e gestire l’interfaccia utente. ### Memorizzare un riferimento a Stripe Accedi alla libreria Stripe nel componente CheckoutForm utilizzando gli hook `useStripe()` e `useElements()`. Se hai bisogno di accedere a Elements con un componente di classe, utilizza invece [ElementsConsumer](https://docs.stripe.com/sdks/stripejs-react.md#elements-consumer). ### Memorizzare un riferimento a Stripe Accedi alla libreria Stripe nel componente CheckoutForm utilizzando gli hook `useStripe()` e `useElements()`. Se hai bisogno di accedere a Elements tramite un componente di classe, utilizza invece [ElementsConsumer](https://docs.stripe.com/sdks/stripejs-react.md#elements-consumer). ### Aggiungere il PaymentElement Aggiungi il [PaymentElement](https://docs.stripe.com/js/elements_object/create_payment_element) al modulo di pagamento. Incorpora un iframe con un modulo dinamico che raccoglie i dati di pagamento per una serie di metodi di pagamento. Il cliente può scegliere un tipo di metodo di pagamento e il modulo raccoglie automaticamente tutti i dati di pagamento necessari per la selezione. ### Aggiungere il PaymentElement Aggiungi il [PaymentElement](https://docs.stripe.com/js/elements_object/create_payment_element) al modulo di pagamento. Incorpora un iframe con un modulo dinamico che raccoglie i dati di pagamento per una serie di metodi di pagamento. Il cliente può scegliere un tipo di metodo di pagamento e il modulo raccoglie automaticamente tutti i dati di pagamento necessari per la selezione. ### Creare il PaymentElement Crea un [PaymentElement](https://docs.stripe.com/js/elements_object/create_payment_element) e inseriscilo nel segnaposto `
` del tuo modulo di pagamento. Viene incorporato un iframe con un modulo dinamico che visualizza i tipi di metodo di pagamento configurati disponibili nel PaymentIntent, consentendo al cliente di selezionare un metodo di pagamento. Il modulo raccoglie automaticamente i dati di pagamento associati al tipo di metodo di pagamento selezionato. ### (Facoltativo) Definire lo stile di Payment Element Personalizza l’interfaccia utente dell’elemento di pagamento creando un [oggetto Appearance](https://docs.stripe.com/elements/appearance-api.md) e passandolo come opzione al provider Elements. Utilizza la combinazione di colori e il carattere tipografico della tua azienda per uniformare lo stile della pagina di completamento della transazione. Usa font personalizzati (ad esempio, da Google Fonts) inizializzando Elements con un [set di font](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-fonts). Assicurati di aprire l’anteprima a destra per visualizzare le modifiche live. > Alcune parti della demo di anteprima potrebbero non corrispondere alla pagina di completamento della transazione effettiva. Le impostazioni sopra riportate rappresentano solo un sottoinsieme delle variabili dell’[oggetto Appearance](https://docs.stripe.com/elements/appearance-api.md), e l’[oggetto Appearance](https://docs.stripe.com/elements/appearance-api.md) controlla solo alcuni attributi di Stripe Elements. Sei responsabile dello styling del resto della pagina di completamento della transazione. ### (Facoltativo) Definire lo stile di Payment Element Personalizza l’interfaccia utente dell’elemento di pagamento creando un [oggetto Appearance](https://docs.stripe.com/elements/appearance-api.md) e passandolo come opzione al provider Elements. Utilizza la combinazione di colori e il carattere tipografico della tua azienda per uniformare lo stile della pagina di completamento della transazione. Usa font personalizzati (ad esempio, da Google Fonts) inizializzando Elements con un [set di font](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-fonts). Assicurati di aprire l’anteprima a destra per visualizzare le modifiche live. > Alcune parti dell’anteprima di dimostrazione potrebbero non corrispondere all’effettiva pagina di pagamento. Le impostazioni sopra riportate rappresentano solo un sottoinsieme delle variabili dell’oggetto Appearance e l’oggetto Appearance controlla solo alcuni attributi di Stripe Elements. Sei responsabile dello stile del resto della pagina di pagamento. ### (Facoltativo) Definire lo stile di Payment Element Personalizza l’interfaccia utente dell’Elemento di pagamento creando un [oggetto Appearance](https://docs.stripe.com/elements/appearance-api.md) e inizializzando Elements con esso. Utilizza la combinazione di colori e il carattere tipografico della tua azienda per uniformare lo stile della pagina di completamento della transazione. Usa font personalizzati (ad esempio, da Google Fonts) inizializzando Elements con un [set di font](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-fonts). Assicurati di aprire l’anteprima a destra per visualizzare le modifiche live. > Alcune parti della demo di anteprima potrebbero non corrispondere alla pagina di completamento della transazione effettiva. Le impostazioni sopra riportate rappresentano solo un sottoinsieme delle variabili dell’[oggetto Appearance](https://docs.stripe.com/elements/appearance-api.md), e l’[oggetto Appearance](https://docs.stripe.com/elements/appearance-api.md) controlla solo alcuni attributi di Stripe Elements. Sei responsabile dello styling del resto della pagina di completamento della transazione. ### Gestire l’evento di invio Ascolta l’evento di invio del modulo per sapere quando confermare il pagamento tramite l’API Stripe. ### Completare il pagamento Quando il cliente fa clic sul pulsante di pagamento, chiama [confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) con PaymentElement e passa un [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) per indicare dove Stripe reindirizza il cliente dopo che ha completato il pagamento. Per i pagamenti che richiedono l’autenticazione, Stripe mostra una finestra modale per l’autenticazione *3D Secure* (3D Secure (3DS) provides an additional layer of authentication for credit card transactions that protects businesses from liability for fraudulent card payments) o reindirizza il cliente a una pagina di autenticazione, a seconda del metodo di pagamento. Dopo che il cliente ha completato il processo di autenticazione, viene reindirizzato a `return_url`. ### Completare il pagamento Quando il cliente fa clic sul pulsante di pagamento, chiama [confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) con PaymentElement e passa un [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) per indicare dove Stripe reindirizza il cliente dopo che ha completato il pagamento. Per i pagamenti che richiedono l’autenticazione, Stripe mostra una finestra modale per l’autenticazione *3D Secure* (3D Secure (3DS) provides an additional layer of authentication for credit card transactions that protects businesses from liability for fraudulent card payments) o reindirizza il cliente a una pagina di autenticazione, a seconda del metodo di pagamento. Dopo che il cliente ha completato il processo di autenticazione, viene reindirizzato a `return_url`. ### Completare il pagamento Chiama [confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) con l’istanza Element e un [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) per indicare dove Stripe reindirizza il cliente dopo che ha completato il pagamento. Per i pagamenti che richiedono l’autenticazione, Stripe visualizza una finestra modale per l’autenticazione *3D Secure* (3D Secure (3DS) provides an additional layer of authentication for credit card transactions that protects businesses from liability for fraudulent card payments) o reindirizza il cliente a una pagina di autenticazione, a seconda del metodo di pagamento. Dopo che il cliente ha completato il processo di autenticazione, viene reindirizzato a `return_url`. ### Gestire gli errori Se si verificano [errori](https://docs.stripe.com/error-codes.md) immediati (ad es. la carta del cliente viene rifiutata), Stripe.js restituisce un errore. Mostra quell’errore al cliente in modo tale che possa riprovare. ### Mostrare un messaggio sullo stato del pagamento Quando Stripe reindirizza il cliente al `return_url`, il parametro di ricerca `payment_intent_client_secret` viene aggiunto da Stripe.js. Utilizzalo per recuperare l’[aggiornamento dello stato del PaymentIntent](https://docs.stripe.com/payments/payment-intents/verifying-status.md) e determinare cosa mostrare al cliente. ### Mostrare un messaggio sullo stato del pagamento Quando Stripe reindirizza il cliente a `return_url`, il parametro di ricerca `payment_intent` viene aggiunto da Stripe.js. Utilizzalo per recuperare l’[aggiornamento dello stato del PaymentIntent](https://docs.stripe.com/payments/payment-intents/verifying-status.md) e determinare cosa mostrare al cliente. ### Utilizzare un webhook Stripe invia più eventi durante la procedura di pagamento e al completamento del pagamento. Crea una [destinazione evento](https://docs.stripe.com/event-destinations.md) per un [endpoint del webhook](https://docs.stripe.com/webhooks/quickstart.md) per ricevere questi eventi ed eseguire azioni come l’invio di un’email per la conferma di un ordine al cliente, la registrazione della vendita in un database o l’avvio del flusso di lavoro per una spedizione. Stripe consiglia di gestire gli eventi [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). Ascolta questi eventi invece di attendere una chiamata di ritorno dal client. Sul client, il cliente potrebbe chiudere la finestra del browser o uscire dall’app prima dell’esecuzione della chiamata di ritorno e i client malintenzionati potrebbero manipolare la risposta. La configurazione dell’integrazione per l’ascolto di eventi asincroni ti consente di accettare [diversi tipi di modalità di pagamento](https://stripe.com/payments/payment-methods-guide) con una sola integrazione. ### Eseguire l’applicazione Esegui l’app React e il server. Vai a [localhost:3000/checkout](http://localhost:3000/checkout) per visualizzare la pagina di pagamento. ```bash npm start ``` ### Eseguire l’applicazione Esegui l’app Next.js. Vai a [localhost:3000](http://localhost:3000) per visualizzare la pagina di pagamento. ```bash npm run dev ``` ### Eseguire l’applicazione Esegui il tuo server Node e accedi a [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash npm start ``` ### Eseguire l’applicazione server Esegui l’app React e il server. Vai a [localhost:3000/checkout](http://localhost:3000/checkout) per visualizzare la pagina di pagamento. ```bash ruby server.rb ``` ### Eseguire l’applicazione Esegui il tuo server Ruby e accedi a [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash ruby server.rb ``` ### Eseguire l’applicazione server Esegui l’app React e il server. Vai a [localhost:3000/checkout](http://localhost:3000/checkout) per visualizzare la pagina di pagamento. ```bash python3 -m flask run --port=4242 ``` ### Eseguire l’applicazione Esegui il tuo server Python e accedi a [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash python3 -m flask run --port=4242 ``` ### Eseguire l’applicazione server Esegui l’app React e il server. Vai a [localhost:3000/checkout](http://localhost:3000/checkout) per visualizzare la pagina di pagamento. ```bash php -S 127.0.0.1:4242 --docroot=public ``` ### Eseguire l’applicazione Esegui il tuo server e accedi a [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash php -S 127.0.0.1:4242 --docroot=public ``` ### Eseguire l’applicazione server Esegui l’app React e il server. Vai a [localhost:3000/checkout](http://localhost:3000/checkout) per visualizzare la pagina di pagamento. ```bash go run server.go ``` ### Eseguire l’applicazione Esegui il tuo server Go e accedi a [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash go run server.go ``` ### Eseguire l’applicazione server Esegui l’app React e il server. Vai a [localhost:3000/checkout](http://localhost:3000/checkout) per visualizzare la pagina di pagamento. ```bash dotnet run ``` ### Eseguire l’applicazione Esegui il tuo server ASP.NET MVC e accedi a [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash dotnet run ``` ### Eseguire l’applicazione Esegui il tuo server e accedi a [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash java -cp target/sample-jar-with-dependencies.jar com.stripe.sample.Server ``` ### Eseguire l’applicazione server Esegui l’app React e il server. Vai a [localhost:3000/checkout](http://localhost:3000/checkout) per visualizzare la pagina di pagamento. ```bash java -cp target/sample-jar-with-dependencies.jar com.stripe.sample.Server ``` ### Eseguire l’applicazione Esegui l’app React e accedi a [localhost:3000/checkout](http://localhost:3000/checkout). ```bash npm start ``` ### Effettuare un pagamento di test Per verificare che l’integrazione funzioni, effettua un pagamento di test utilizzando i [dettagli del pagamento di test](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=elements&api-integration=paymentintents#web-test-the-integration). ### Visualizzare il pagamento nella Dashboard Accedi alla [Dashboard Stripe](https://dashboard.stripe.com/test/payments) per visualizzare il tuo pagamento di test. ## Accettare i pagamenti e ottimizzare l’integrazione Adesso è tutto pronto per accettare i pagamenti con carta con Stripe. Per aggiungere altre funzionalità, continua con questa procedura. ### Automatizzare la riscossione delle imposte Calcola e riscuoti l’importo corretto dell’imposta sulle tue transazioni Stripe. Prima di utilizzare Stripe Tax, è necessario attivarlo nella [Dashboard](https://dashboard.stripe.com/tax). Scopri di più su [Stripe Tax](https://docs.stripe.com/tax.md) e su [come aggiungerlo alla tua integrazione Payments](https://docs.stripe.com/tax/custom.md). ### Utilizzare l’API Stripe Tax per calcolare le imposte Utilizza l’[API Stripe Tax](https://docs.stripe.com/api/tax/calculations/create.md) per calcolare l’imposta sulla transazione. Specifica `currency`, `customer_details` e `line_items` dell’ordine nel corpo della richiesta. Utilizza l’attributo `tax_amount_exclusive` del calcolo delle imposte risultante per aggiungere le imposte escluse al totale dell’ordine. ### Registrare una transazione fiscale dopo un pagamento riuscito Link il calcolo delle imposte al PaymentIntent utilizzando `hook[inputs][tassa][calcolo]`. In questo modo vengono registrate le imposte riscosse nel tuo account Stripe che potrai successivamente esportare a fini contabili e vengono attivate altre [azioni Stripe](https://docs.stripe.com/tax/payment-intent.md#automatic-actions). ### Inviare una ricevuta via email Stripe può inviare al cliente una ricevuta via email con il logo e il tema colori del tuo brand, configurabili nella [Dashboard](https://dashboard.stripe.com/settings/branding). ### Acquisire l’indirizzo email del cliente Per acquisire l’indirizzo email, aggiungi un campo di inserimento nel modulo di pagamento. ### Aggiungere l’email allo stato Aggiungi una variabile per tenere traccia dell’email inserita dal cliente. ### Aggiungere l’email allo stato Aggiungi una variabile per tenere traccia dell’email inserita dal cliente. ### Specificare indirizzo email con Stripe Specifica l’indirizzo email fornito come valore `receipt_email`. Stripe invia una ricevuta via email quando il pagamento va a buon fine in modalità live (ma non ne invia una in una *sandbox* (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)). ### Salvare i dati di pagamento dopo il pagamento Utilizzata spesso dalle aziende di e-commerce o SaaS con clienti ricorrenti. ### Importare ulteriori risorse di Stripe Importa i pacchetti `customer` e `paymentmethod` di Stripe e utilizzali per memorizzare le informazioni sul tuo cliente. ### Importare ulteriori risorse di Stripe Importa i modelli PaymentMethod e Customer di Stripe e utilizzali per memorizzare le informazioni sul tuo cliente. ### Creare un cliente Stripe memorizza la carta in un oggetto *Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments). Prima di creare un PaymentIntent, crea un nuovo oggetto Customer, dove puoi memorizzare anche nome, email, indirizzo di spedizione e altre informazioni sul cliente. ### Creare un cliente Stripe memorizza la carta in un oggetto [Account](https://docs.stripe.com/api/v2/core/accounts/object.md) che rappresenta il [cliente](https://docs.stripe.com/connect/account-capabilities.md?accounts-namespace=v2#customer). Prima di creare un PaymentIntent, crea un nuovo account, dove puoi anche memorizzare nome, email, indirizzo di spedizione e altri dettagli dell’account. ### Aggiungere il cliente al PaymentIntent Specifica l’ID cliente in PaymentIntent e imposta `setup_future_usage` su `off_session`. `setup_future_usage` indica a Stripe il modo in cui prevedi di utilizzare il metodo di pagamento. Alcune aree geografiche, ad esempio Europa e India, hanno requisiti specifici per il riutilizzo dei dati di pagamento. [Qui trovi ulteriori dettagli](https://docs.stripe.com/payments/payment-intents.md#future-usage) sul modo più efficace per applicare `setup_future_usage`. Puoi anche visualizzare un [elenco dei metodi di pagamento supportati](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability). Al termine del PaymentIntent, Stripe [associa](https://docs.stripe.com/api/payment_methods/attach.md) automaticamente i dati di pagamento (in un oggetto *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs)) al cliente. ### Aggiungere il cliente al PaymentIntent Specifica l’ID account nel PaymentIntent e imposta `setup_future_usage` su `off_session`. `setup_future_usage` indica a Stripe come prevedi di utilizzare il metodo di pagamento. Alcune aree geografiche, come l’Europa e l’India, hanno requisiti per il riutilizzo dei dati di pagamento. [Scopri](https://docs.stripe.com/payments/payment-intents.md#future-usage) come applicare `setup_future_usage` nel modo più efficace. Puoi anche visualizzare un [elenco dei metodi di pagamento](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability) supportati. Una volta che il PaymentIntent ha esito positivo, Stripe [associa](https://docs.stripe.com/api/payment_methods/attach.md) automaticamente i dati di pagamento (in un oggetto *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs)) all’account configurato dal cliente. ### Addebitare un importo sul PaymentMethod salvato Quando è tutto pronto per addebitare di nuovo l’importo sul PaymentMethod, crea un nuovo PaymentIntent con l’ID cliente, l’ID del PaymentMethod da utilizzare per l’addebito, e imposta i flag `off_session` e `confirm` su true. ### Installare la libreria Node di Stripe Installa il pacchetto e importalo nel tuo codice. In alternativa, se inizi da zero e hai bisogno di un file package.json, scarica i file del progetto utilizzando il link Download nell’editor del codice. #### npm Installa la libreria: ```bash npm install --save stripe ``` #### GitHub In alternativa scarica il codice sorgente della libreria stripe-node direttamente [da GitHub](https://github.com/stripe/stripe-node). ### Installare la libreria Ruby di Stripe Installa il ruby gem di Stripe e importalo nel tuo codice. In alternativa, se inizi da zero e hai bisogno di un Gemfile, scarica i file del progetto utilizzando il link Download nell’editor del codice. #### Terminal Installa il gem: ```bash gem install stripe ``` #### Bundler Aggiungi questa riga al Gemfile: ```bash gem 'stripe' ``` #### GitHub In alternativa scarica il codice sorgente della libreria stripe-ruby direttamente [da GitHub](https://github.com/stripe/stripe-ruby). ### Installare la libreria Java di Stripe Aggiungi la dipendenza alla tua build e importa la libreria. In alternativa, se inizi da zero e hai bisogno di un file pom.xml (per Maven), scarica i file del progetto utilizzando il link Download nell’editor del codice. #### Maven Aggiungi la seguente dipendenza al tuo POM e sostituisci {VERSION} con il numero di versione che vuoi utilizzare. ```bash \ncom.stripe\nstripe-java\n{VERSION}\n ``` #### Gradle Aggiungi la dipendenza al tuo file build.gradle e sostituisci {VERSION} con il numero di versione che vuoi utilizzare. ```bash implementation "com.stripe:stripe-java:{VERSION}" ``` #### GitHub Scarica il JAR direttamente [da GitHub](https://github.com/stripe/stripe-java/releases/latest). ### Installare il pacchetto Python di Stripe Installa il pacchetto Stripe e importalo nel tuo codice. In alternativa, se inizi da zero e hai bisogno di un file requirements.txt, scarica i file del progetto utilizzando il link Download nell’editor del codice. #### pip Installa il pacchetto tramite pip: ```bash pip3 install stripe ``` #### GitHub Scarica il codice sorgente della libreria stripe-python direttamente [da GitHub](https://github.com/stripe/stripe-python). ### Installare la libreria PHP di Stripe Installa la libreria con composer e inizializzala con la tua chiave API privata. In alternativa, se inizi da zero e hai bisogno di un file composer.json, scarica i file utilizzando il link Download nell’editor del codice. #### Composer Installa la libreria: ```bash composer require stripe/stripe-php ``` #### GitHub In alternativa scarica il codice sorgente della libreria stripe-php direttamente [da GitHub](https://github.com/stripe/stripe-php). ### Configurare il server Aggiungi la dipendenza alla tua build e importa la libreria. In alternativa, se inizi da zero e hai bisogno di un file go.mod, scarica i file del progetto utilizzando il link Download nell’editor del codice. #### Go Assicurati di eseguire l’inizializzazione con Go Modules: ```bash go get -u github.com/stripe/stripe-go/v85 ``` #### GitHub In alternativa scarica il codice sorgente della libreria stripe-go direttamente [da GitHub](https://github.com/stripe/stripe-go). ### Installare la libreria Stripe.net Installa il pacchetto con dotnet o NuGet. In alternativa, se inizi da zero, scarica i file contenenti un file .csproj configurato. #### dotnet Installa la libreria: ```bash dotnet add package Stripe.net ``` #### NuGet Installa la libreria: ```bash Install-Package Stripe.net ``` #### GitHub In alternativa scarica il codice sorgente della libreria Stripe.net direttamente [da GitHub](https://github.com/stripe/stripe-dotnet). ### Installare le librerie Stripe Installa i pacchetti e importali nel tuo codice. In alternativa, se inizi da zero e hai bisogno di un file `package.json`, scarica i file del progetto utilizzando il link nell’editor del codice. Installa le librerie: ```bash npm install --save stripe @stripe/stripe-js next ``` ### Creare un PaymentIntent Aggiungi sul server un endpoint che crei un [PaymentIntent](https://docs.stripe.com/api/payment_intents.md). Un PaymentIntent segue il ciclo di vita del pagamento del cliente tenendo traccia di eventuali tentativi di pagamento non riusciti per garantire che l’importo venga addebitato solo una volta. Per completare il pagamento sul client, restituisci la *chiave privata client* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) del PaymentIntent nella risposta. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Installare l’SDK L’SDK per iOS di Stripe è [open source](https://github.com/stripe/stripe-ios), [completamente documentato](https://stripe.dev/stripe-ios/) e compatibile con le app che supportano iOS 13 o versioni successive. Importa l’SDK di Stripe nel controller di visualizzazione della schermata di pagamento. #### Swift Package Manager In Xcode, seleziona **File** > **Aggiungi dipendenze pacchetto…** e inserisci `https://github.com/stripe/stripe-ios-spm` come URL repository. Seleziona il numero dell’ultima versione dalla nostra [pagina delle release](https://github.com/stripe/stripe-ios/releases) e aggiungi il modulo `StripePaymentSheet` alla destinazione della tua app. #### CocoaPods Aggiungi questa riga al Podfile e d’ora in poi utilizza il file .xcworkspace per aprire il progetto in Xcode, anziché il file .xcodeproj file. ```bash pod 'StripePaymentSheet' ``` #### Carthage Aggiungi questa riga al Cartfile. ```bash github "stripe/stripe-ios" ``` #### Framework manuale Per includere Stripe nel progetto, scarica e decomprimi Stripe.xcframework.zip da una [versione su GitHub](https://github.com/stripe/stripe-ios/releases). Trascina i file xcframework richiesti nelle impostazioni “Embedded Binaries” nel tuo progetto Xcode. Assicurati di selezionare “Copy items if needed”. ### Configurare l’SDK Configura l’SDK Stripe con la tua [chiave API pubblicabile](https://docs.stripe.com/keys.md#obtain-api-keys) di Stripe. La codifica della chiave API pubblicabile nell’SDK è solo a scopo dimostrativo. In un’app di produzione, devi recuperare la chiave API dal server. ### Recuperare un PaymentIntent Non appena la vista viene caricata, invia al tuo server una richiesta per un PaymentIntent. Memorizza il riferimento alla *chiave privata client* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) del PaymentIntent restituita dal server. Payment Sheet utilizza questa chiave privata per completare il pagamento in seguito. ### Configurare e presentare il Payment Sheet Crea un’istanza di `PaymentSheet` utilizzando la chiave privata client recuperata in precedenza e presentala dal controller di visualizzazione. Utilizza la struct `PaymentSheet.Configuration` per [personalizzare](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html) il Payment Sheet. ### Gestire l’esito del pagamento Utilizza il blocco di completamento per gestire il risultato del pagamento. Se il pagamento non va a buon fine con un [errore](https://docs.stripe.com/error-codes.md), mostra il messaggio appropriato al cliente in modo che possa intervenire e riprovare. Se non si è verificato alcun errore, informa il cliente che il pagamento è riuscito. ### Effettuare un pagamento di test #### iOS Per verificare che l’integrazione funzioni, effettua un pagamento di test utilizzando i [dettagli del pagamento di test](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios#ios-test-the-integration). #### Android Per verificare che l’integrazione funzioni, effettua un pagamento di test utilizzando i [dettagli del pagamento di test](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=android#android-test-the-integration). ### Visualizzare il pagamento nella Dashboard Accedi alla [Dashboard Stripe](https://dashboard.stripe.com/test/payments) per visualizzare il tuo pagamento di test. ## Accettare i pagamenti e ottimizzare l’integrazione Adesso è tutto pronto per accettare i pagamenti con carta con Stripe. Per aggiungere altre funzionalità, continua con questa procedura. ### Automatizzare la riscossione delle imposte Calcola e riscuoti l’importo corretto dell’imposta sulle tue transazioni Stripe. Prima di utilizzare Stripe Tax, è necessario attivarlo nella [Dashboard](https://dashboard.stripe.com/tax). Scopri di più su [Stripe Tax](https://docs.stripe.com/tax.md) e su [come aggiungerlo alla tua integrazione Payments](https://docs.stripe.com/tax/custom.md). ### Utilizzare l’API Stripe Tax per calcolare le imposte Utilizza l’[API Stripe Tax](https://docs.stripe.com/api/tax/calculations/create.md) per calcolare l’imposta sulla transazione. Specifica `currency`, `customer_details` e `line_items` dell’ordine nel corpo della richiesta. Utilizza l’attributo `tax_amount_exclusive` del calcolo delle imposte risultante per aggiungere le imposte escluse al totale dell’ordine. ### Registrare una transazione fiscale dopo un pagamento riuscito Collega il calcolo delle imposte al PaymentIntent utilizzando `hooks[inputs][tax][calculation]`. In questo modo vengono registrate le imposte riscosse nel tuo account Stripe che potrai successivamente esportare a fini contabili e vengono attivate altre [azioni Stripe](https://docs.stripe.com/tax/payment-intent.md#automatic-actions). ### Consentire metodi di pagamento ritardati Alcuni metodi di pagamento non possono garantire che riceverai i fondi dal cliente al termine del completamento della transazione perché richiedono tempo per il regolamento (ad es. la maggior parte degli addebiti bancari, ad esempio SEPA o ACH) o richiedono un’azione da parte del cliente per essere completati (ad es. OXXO, Konbini, Boleto). Usa questo flag per abilitare il metodo di pagamento ritardato. Se abiliti questa funzionalità, assicurati che l’integrazione del tuo server ascolti i [webhook](https://docs.stripe.com/payments/payment-methods.md#payment-notification) per ricevere le notifiche sull’esito del pagamento. ### Aggiungere il supporto per Apple Pay Per abilitare Apple Pay, fornisci il tuo [ID esercente Apple Pay](https://support.stripe.com/questions/enable-apple-pay-on-your-stripe-account) e il [codice Paese](https://dashboard.stripe.com/settings/account) del tuo account Stripe. ### Aggiungere il supporto per Google Pay Per utilizzare Google Pay, abilita innanzitutto l’API Google Pay nel tuo AndroidManifest.xml. Abilita Google Pay specificando un oggetto [PaymentSheet.GooglePayConfiguration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-google-pay-configuration/index.html) con l’ambiente Google Pay (produzione o test) e il [codice Paese della tua attività](https://dashboard.stripe.com/settings/account) durante l’inizializzazione di [PaymentSheet. Configurazione](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-configuration/index.html). ### Personalizzare il colore del pulsante principale Valuta l’utilizzo di un colore personalizzato per il pulsante principale che corrisponda meglio all’identità visiva del tuo brand o della tua app. ### Abilitare la scansione delle carte La scansione delle carte può aiutarti ad aumentare il tasso di conversione eliminando i problemi legati all’inserimento manuale delle carte. Per abilitare la scansione delle carte, imposta `NSCameraUsageDescription` nel file `Info.plist` della tua applicazione e indica un motivo per accedere alla fotocamera (ad es. “Per acquisire le carte”). > La scansione delle carte è supportata solo su dispositivi con iOS 13 o versioni successive. ### Abilitare la scansione delle carte La scansione delle carte può aiutarti ad aumentare il tasso di conversione eliminando i problemi legati all’inserimento manuale delle carte. Per abilitare la scansione delle carte, aggiungi `stripecardscan` al blocco `dependencies` del tuo file [app/build.gradle](https://developer.android.com/studio/build/dependencies): #### Groovy ```groovy implementation 'com.stripe:stripecardscan:23.3.0' ``` ### Salvare i dati di pagamento dopo il pagamento Utilizzata spesso dalle aziende di e-commerce o SaaS con clienti ricorrenti. ### Importare ulteriori risorse di Stripe Importa i pacchetti `customer` e `paymentmethod` di Stripe e utilizzali per memorizzare le informazioni sul tuo cliente. ### Importare ulteriori risorse di Stripe Importa i modelli PaymentMethod e Customer di Stripe e utilizzali per memorizzare le informazioni sul tuo cliente. ### Creare un cliente Stripe memorizza la carta in un oggetto *Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments). Prima di creare un PaymentIntent, crea un nuovo oggetto Customer, dove puoi memorizzare anche nome, email, indirizzo di spedizione e altre informazioni sul cliente. ### Creare un cliente Stripe memorizza la carta in un oggetto [Account](https://docs.stripe.com/api/v2/core/accounts/object.md) che rappresenta il [cliente](https://docs.stripe.com/connect/account-capabilities.md?accounts-namespace=v2#customer). Prima di creare un PaymentIntent, crea un nuovo account, dove puoi anche memorizzare nome, email, indirizzo di spedizione e altri dettagli dell’account. ### Aggiungere il cliente al PaymentIntent Specifica l’ID cliente in PaymentIntent e imposta `setup_future_usage` su `off_session`. `setup_future_usage` indica a Stripe il modo in cui prevedi di utilizzare il metodo di pagamento. Alcune aree geografiche, ad esempio Europa e India, hanno requisiti specifici per il riutilizzo dei dati di pagamento. [Qui trovi ulteriori dettagli](https://docs.stripe.com/payments/payment-intents.md#future-usage) sul modo più efficace per applicare `setup_future_usage`. Puoi anche visualizzare un [elenco dei metodi di pagamento supportati](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability). Al termine del PaymentIntent, Stripe [associa](https://docs.stripe.com/api/payment_methods/attach.md) automaticamente i dati di pagamento (in un oggetto *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs)) al cliente. ### Aggiungere il cliente al PaymentIntent Specifica l’ID account nel PaymentIntent e imposta `setup_future_usage` su `off_session`. `setup_future_usage` indica a Stripe come prevedi di utilizzare il metodo di pagamento. Alcune aree geografiche, come l’Europa e l’India, hanno requisiti per il riutilizzo dei dati di pagamento. [Scopri](https://docs.stripe.com/payments/payment-intents.md#future-usage) come applicare `setup_future_usage` nel modo più efficace. Puoi anche visualizzare un [elenco dei metodi di pagamento](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability) supportati. Una volta che il PaymentIntent ha esito positivo, Stripe [associa](https://docs.stripe.com/api/payment_methods/attach.md) automaticamente i dati di pagamento (in un oggetto *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs)) all’account configurato dal cliente. ### Addebitare un importo sul PaymentMethod salvato Quando è tutto pronto per addebitare di nuovo l’importo sul PaymentMethod, crea un nuovo PaymentIntent con l’ID cliente, l’ID del PaymentMethod da utilizzare per l’addebito, e imposta i flag `off_session` e `confirm` su true. ### Raccogliere gli indirizzi con Address Element Raccogli gli indirizzi di spedizione o fatturazione locali e internazionali dai tuoi clienti. ### Raccogliere gli indirizzi con Address Element Raccogli gli indirizzi di spedizione o fatturazione locali e internazionali dai tuoi clienti. Se utilizzi Address Element, puoi eventualmente utilizzare [Google Places SDK](https://developers.google.com/maps/documentation/places/android-sdk/overview) per recuperare i suggerimenti di completamento automatico dell’indirizzo. Per abilitare i suggerimenti di completamento automatico, aggiungi `places` al blocco di dipendenza del file [app/build.gradle](https://developer.android.com/studio/build/dependencies): #### Groovy ```groovy implementation 'com.google.android.libraries.places:places:2.6.0' ``` ### Installare la libreria Node di Stripe Installa il pacchetto e importalo nel tuo codice. In alternativa, se inizi da zero e hai bisogno di un file package.json, scarica i file del progetto utilizzando il link Download nell’editor del codice. #### npm Installa la libreria: ```bash npm install --save stripe ``` #### GitHub In alternativa scarica il codice sorgente della libreria stripe-node direttamente [da GitHub](https://github.com/stripe/stripe-node). ### Installare la libreria Ruby di Stripe Installa il ruby gem di Stripe e importalo nel tuo codice. In alternativa, se inizi da zero e hai bisogno di un Gemfile, scarica i file del progetto utilizzando il link Download nell’editor del codice. #### Terminal Installa il gem: ```bash gem install stripe ``` #### Bundler Aggiungi questa riga al Gemfile: ```bash gem 'stripe' ``` #### GitHub In alternativa scarica il codice sorgente della libreria stripe-ruby direttamente [da GitHub](https://github.com/stripe/stripe-ruby). ### Installare la libreria Java di Stripe Aggiungi la dipendenza alla tua build e importa la libreria. In alternativa, se inizi da zero e hai bisogno di un file pom.xml (per Maven), scarica i file del progetto utilizzando il link Download nell’editor del codice. #### Maven Aggiungi la seguente dipendenza al tuo POM e sostituisci {VERSION} con il numero di versione che vuoi utilizzare. ```bash \ncom.stripe\nstripe-java\n{VERSION}\n ``` #### Gradle Aggiungi la dipendenza al tuo file build.gradle e sostituisci {VERSION} con il numero di versione che vuoi utilizzare. ```bash implementation "com.stripe:stripe-java:{VERSION}" ``` #### GitHub Scarica il JAR direttamente [da GitHub](https://github.com/stripe/stripe-java/releases/latest). ### Installare il pacchetto Python di Stripe Installa il pacchetto Stripe e importalo nel tuo codice. In alternativa, se inizi da zero e hai bisogno di un file requirements.txt, scarica i file del progetto utilizzando il link Download nell’editor del codice. #### pip Installa il pacchetto tramite pip: ```bash pip3 install stripe ``` #### GitHub Scarica il codice sorgente della libreria stripe-python direttamente [da GitHub](https://github.com/stripe/stripe-python). ### Installare la libreria PHP di Stripe Installa la libreria con composer e inizializzala con la tua chiave API privata. In alternativa, se inizi da zero e hai bisogno di un file composer.json, scarica i file utilizzando il link Download nell’editor del codice. #### Composer Installa la libreria: ```bash composer require stripe/stripe-php ``` #### GitHub In alternativa scarica il codice sorgente della libreria stripe-php direttamente [da GitHub](https://github.com/stripe/stripe-php). ### Configurare il server Aggiungi la dipendenza alla tua build e importa la libreria. In alternativa, se inizi da zero e hai bisogno di un file go.mod, scarica i file del progetto utilizzando il link Download nell’editor del codice. #### Go Assicurati di eseguire l’inizializzazione con Go Modules: ```bash go get -u github.com/stripe/stripe-go/v85 ``` #### GitHub In alternativa scarica il codice sorgente della libreria stripe-go direttamente [da GitHub](https://github.com/stripe/stripe-go). ### Installare la libreria Stripe.net Installa il pacchetto con dotnet o NuGet. In alternativa, se inizi da zero, scarica i file contenenti un file .csproj configurato. #### dotnet Installa la libreria: ```bash dotnet add package Stripe.net ``` #### NuGet Installa la libreria: ```bash Install-Package Stripe.net ``` #### GitHub In alternativa scarica il codice sorgente della libreria Stripe.net direttamente [da GitHub](https://github.com/stripe/stripe-dotnet). ### Installare le librerie Stripe Installa i pacchetti e importali nel tuo codice. In alternativa, se inizi da zero e hai bisogno di un file `package.json`, scarica i file del progetto utilizzando il link nell’editor del codice. Installa le librerie: ```bash npm install --save stripe @stripe/stripe-js next ``` ### Creare un PaymentIntent Aggiungi sul server un endpoint che crei un [PaymentIntent](https://docs.stripe.com/api/payment_intents.md). Un PaymentIntent segue il ciclo di vita del pagamento del cliente tenendo traccia di eventuali tentativi di pagamento non riusciti per garantire che l’importo venga addebitato solo una volta. Per completare il pagamento sul client, restituisci la *chiave privata client* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) del PaymentIntent nella risposta. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Configurare i metodi di pagamento Per impostazione predefinita, Stripe abilita le carte e altri metodi di pagamento diffusi con [metodi di pagamento dinamici](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Puoi aggiornare e configurare i metodi di pagamento dalla [Dashboard](https://dashboard.stripe.com/settings/payment_methods) senza scrivere codice. Stripe filtra i metodi di pagamento in base all’idoneità e alle preferenze dei metodi di pagamento, poi ordina e visualizza per probabilità in base a fattori quali importo, valuta e posizione dell’acquirente. ### Installare l’SDK L’SDK di Stripe per Android è [open source](https://github.com/stripe/stripe-android) e [completamente documentato](https://stripe.dev/stripe-android/) e compatibile con i dispositivi con Android 5.0 (API livello 21) o versioni successive. Per installare l’SDK, aggiungi `stripe-android` al blocco di dipendenze del file `build.gradle`: #### Groovy ```groovy implementation 'com.stripe:stripe-android:23.3.0' ``` > Per ulteriori informazioni sulla versione più recente e su quelle precedenti dell’SDK, consulta la [pagina delle versioni](https://github.com/stripe/stripe-android/releases) su GitHub. ### Configurare l’SDK Configura l’SDK Stripe con la tua [chiave API pubblicabile](https://docs.stripe.com/keys.md#obtain-api-keys) di Stripe. La codifica della chiave API pubblicabile nell’SDK è solo a scopo dimostrativo. In un’app di produzione, devi recuperare la chiave API dal server. ### Recuperare un PaymentIntent Non appena la vista viene caricata, invia al tuo server una richiesta per un PaymentIntent. Memorizza il riferimento alla *chiave privata client* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) del PaymentIntent restituita dal server. Payment Sheet utilizza questa chiave privata per completare il pagamento in seguito. ### Configurare e presentare il Payment Sheet Crea un’istanza di `PaymentSheet` utilizzando la chiave privata client recuperata in precedenza e presentala dal controller di visualizzazione. Utilizza la struct `PaymentSheet.Configuration` per [personalizzare](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html) il Payment Sheet. ### Gestire l’esito del pagamento Utilizza il blocco di completamento per gestire il risultato del pagamento. Se il pagamento non va a buon fine con un [errore](https://docs.stripe.com/error-codes.md), mostra il messaggio appropriato al cliente in modo che possa intervenire e riprovare. Se non si è verificato alcun errore, informa il cliente che il pagamento è riuscito. ### Effettuare un pagamento di test #### iOS Per verificare che l’integrazione funzioni, effettua un pagamento di test utilizzando i [dettagli del pagamento di test](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios#ios-test-the-integration). #### Android Per verificare che l’integrazione funzioni, effettua un pagamento di test utilizzando i [dettagli del pagamento di test](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=android#android-test-the-integration). ### Visualizzare il pagamento nella Dashboard Accedi alla [Dashboard Stripe](https://dashboard.stripe.com/test/payments) per visualizzare il tuo pagamento di test. ## Accettare i pagamenti e ottimizzare l’integrazione Adesso è tutto pronto per accettare i pagamenti con carta con Stripe. Per aggiungere altre funzionalità, continua con questa procedura. ### Automatizzare la riscossione delle imposte Calcola e riscuoti l’importo corretto dell’imposta sulle tue transazioni Stripe. Prima di utilizzare Stripe Tax, è necessario attivarlo nella [Dashboard](https://dashboard.stripe.com/tax). Scopri di più su [Stripe Tax](https://docs.stripe.com/tax.md) e su [come aggiungerlo alla tua integrazione Payments](https://docs.stripe.com/tax/custom.md). ### Utilizzare l’API Stripe Tax per calcolare le imposte Utilizza l’[API Stripe Tax](https://docs.stripe.com/api/tax/calculations/create.md) per calcolare l’imposta sulla transazione. Specifica `currency`, `customer_details` e `line_items` dell’ordine nel corpo della richiesta. Utilizza l’attributo `tax_amount_exclusive` del calcolo delle imposte risultante per aggiungere le imposte escluse al totale dell’ordine. ### Registrare una transazione fiscale dopo un pagamento riuscito Collega il calcolo delle imposte al PaymentIntent utilizzando `hooks[inputs][tax][calculation]`. In questo modo vengono registrate le imposte riscosse nel tuo account Stripe che potrai successivamente esportare a fini contabili e vengono attivate altre [azioni Stripe](https://docs.stripe.com/tax/payment-intent.md#automatic-actions). ### Consentire metodi di pagamento ritardati Alcuni metodi di pagamento non possono garantire che riceverai i fondi dal cliente al termine del completamento della transazione perché richiedono tempo per il regolamento (ad es. la maggior parte degli addebiti bancari, ad esempio SEPA o ACH) o richiedono un’azione da parte del cliente per essere completati (ad es. OXXO, Konbini, Boleto). Usa questo flag per abilitare il metodo di pagamento ritardato. Se abiliti questa funzionalità, assicurati che l’integrazione del tuo server ascolti i [webhook](https://docs.stripe.com/payments/payment-methods.md#payment-notification) per ricevere le notifiche sull’esito del pagamento. ### Aggiungere il supporto per Apple Pay Per abilitare Apple Pay, fornisci il tuo [ID esercente Apple Pay](https://support.stripe.com/questions/enable-apple-pay-on-your-stripe-account) e il [codice Paese](https://dashboard.stripe.com/settings/account) del tuo account Stripe. ### Aggiungere il supporto per Google Pay Per utilizzare Google Pay, abilita innanzitutto l’API Google Pay nel tuo AndroidManifest.xml. Abilita Google Pay specificando un oggetto [PaymentSheet.GooglePayConfiguration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-google-pay-configuration/index.html) con l’ambiente Google Pay (produzione o test) e il [codice Paese della tua attività](https://dashboard.stripe.com/settings/account) durante l’inizializzazione di [PaymentSheet. Configurazione](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-configuration/index.html). ### Personalizzare il colore del pulsante principale Valuta l’utilizzo di un colore personalizzato per il pulsante principale che corrisponda meglio all’identità visiva del tuo brand o della tua app. ### Abilitare la scansione delle carte La scansione delle carte può aiutarti ad aumentare il tasso di conversione eliminando i problemi legati all’inserimento manuale delle carte. Per abilitare la scansione delle carte, imposta `NSCameraUsageDescription` nel file `Info.plist` della tua applicazione e indica un motivo per accedere alla fotocamera (ad es. “Per acquisire le carte”). > La scansione delle carte è supportata solo su dispositivi con iOS 13 o versioni successive. ### Abilitare la scansione delle carte La scansione delle carte può aiutarti ad aumentare il tasso di conversione eliminando i problemi legati all’inserimento manuale delle carte. Per abilitare la scansione delle carte, aggiungi `stripecardscan` al blocco `dependencies` del tuo file [app/build.gradle](https://developer.android.com/studio/build/dependencies): #### Groovy ```groovy implementation 'com.stripe:stripecardscan:23.3.0' ``` ### Salvare i dati di pagamento dopo il pagamento Utilizzata spesso dalle aziende di e-commerce o SaaS con clienti ricorrenti. ### Importare ulteriori risorse di Stripe Importa i pacchetti `customer` e `paymentmethod` di Stripe e utilizzali per memorizzare le informazioni sul tuo cliente. ### Importare ulteriori risorse di Stripe Importa i modelli PaymentMethod e Customer di Stripe e utilizzali per memorizzare le informazioni sul tuo cliente. ### Creare un cliente Stripe memorizza la carta in un oggetto *Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments). Prima di creare un PaymentIntent, crea un nuovo oggetto Customer, dove puoi memorizzare anche nome, email, indirizzo di spedizione e altre informazioni sul cliente. ### Creare un cliente Stripe memorizza la carta in un oggetto [Account](https://docs.stripe.com/api/v2/core/accounts/object.md) che rappresenta il [cliente](https://docs.stripe.com/connect/account-capabilities.md?accounts-namespace=v2#customer). Prima di creare un PaymentIntent, crea un nuovo account, dove puoi anche memorizzare nome, email, indirizzo di spedizione e altri dettagli dell’account. ### Aggiungere il cliente al PaymentIntent Specifica l’ID cliente in PaymentIntent e imposta `setup_future_usage` su `off_session`. `setup_future_usage` indica a Stripe il modo in cui prevedi di utilizzare il metodo di pagamento. Alcune aree geografiche, ad esempio Europa e India, hanno requisiti specifici per il riutilizzo dei dati di pagamento. [Qui trovi ulteriori dettagli](https://docs.stripe.com/payments/payment-intents.md#future-usage) sul modo più efficace per applicare `setup_future_usage`. Puoi anche visualizzare un [elenco dei metodi di pagamento supportati](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability). Al termine del PaymentIntent, Stripe [associa](https://docs.stripe.com/api/payment_methods/attach.md) automaticamente i dati di pagamento (in un oggetto *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs)) al cliente. ### Aggiungere il cliente al PaymentIntent Specifica l’ID account nel PaymentIntent e imposta `setup_future_usage` su `off_session`. `setup_future_usage` indica a Stripe come prevedi di utilizzare il metodo di pagamento. Alcune aree geografiche, come l’Europa e l’India, hanno requisiti per il riutilizzo dei dati di pagamento. [Scopri](https://docs.stripe.com/payments/payment-intents.md#future-usage) come applicare `setup_future_usage` nel modo più efficace. Puoi anche visualizzare un [elenco dei metodi di pagamento](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability) supportati. Una volta che il PaymentIntent ha esito positivo, Stripe [associa](https://docs.stripe.com/api/payment_methods/attach.md) automaticamente i dati di pagamento (in un oggetto *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs)) all’account configurato dal cliente. ### Addebitare un importo sul PaymentMethod salvato Quando è tutto pronto per addebitare di nuovo l’importo sul PaymentMethod, crea un nuovo PaymentIntent con l’ID cliente, l’ID del PaymentMethod da utilizzare per l’addebito, e imposta i flag `off_session` e `confirm` su true. ### Raccogliere gli indirizzi con Address Element Raccogli gli indirizzi di spedizione o fatturazione locali e internazionali dai tuoi clienti. ### Raccogliere gli indirizzi con Address Element Raccogli gli indirizzi di spedizione o fatturazione locali e internazionali dai tuoi clienti. Se utilizzi Address Element, puoi eventualmente utilizzare [Google Places SDK](https://developers.google.com/maps/documentation/places/android-sdk/overview) per recuperare i suggerimenti di completamento automatico dell’indirizzo. Per abilitare i suggerimenti di completamento automatico, aggiungi `places` al blocco di dipendenza del file [app/build.gradle](https://developer.android.com/studio/build/dependencies): #### Groovy ```groovy implementation 'com.google.android.libraries.places:places:2.6.0' ``` ## Passaggi successivi #### Web #### [Raccogliere i dati sull’indirizzo di fatturazione](https://docs.stripe.com/elements/address-element.md) Per impostazione predefinita, Payment Element raccoglie solo i dettagli relativi all’indirizzo di fatturazione necessari. Per acquisire l’indirizzo di fatturazione completo di un cliente (ad esempio, per calcolare l’imposta su beni e servizi digitali) o l’indirizzo di spedizione, utilizza Address Element. #### iOS #### Android #### [Bonifici](https://docs.stripe.com/payouts.md) Scopri come trasferire i fondi da Stripe al tuo conto bancario. #### [Rimborsi](https://docs.stripe.com/refunds.md) Gestisci le richieste di rimborsi utilizzando l’API Stripe o la Dashboard. #### [Evasione degli ordini](https://docs.stripe.com/webhooks/quickstart.md) Crea una destinazione dell’evento per inviare eventi all’endpoint del webhook per evadere gli ordini dopo che un pagamento è andato a buon fine e per gestire altri eventi critici.