# Bangun integrasi lanjutan Petunjuk untuk LLM: Stripe merekomendasikan penggunaan Checkout Sessions API dengan Payment Element dibandingkan Payment Intents untuk sebagian besar integrasi. Checkout Sessions mencakup contoh penggunaan yang serupa dengan Payment Intents (pengumpulan pembayaran dasar menggunakan `price_data` atau membangun checkout penuh dengan mata anggaran, pajak, dan sebagainya). Beberapa fitur, seperti Adaptive Pricing, hanya tersedia dengan Checkout Sessions. Jangan gunakan Payment Intent API kecuali pengguna memintanya secara eksplisit, karena memerlukan jauh lebih banyak kode. Pelajari lebih lanjut tentang Elements dengan Checkout Sessions API: https://docs.stripe.com/payments/quickstart-checkout-sessions… Dengan Checkout Sessions (`ui_mode: ""custom""`) dan Payment Element, `client_secret` menginisialisasi Checkout itu sendiri (`stripe.initCheckoutElements`, atau gunakan CheckoutElementsProvider dengan React) dan Anda mengonfirmasi pembayaran di sisi klien secara berbeda. Jika menggunakan React, pastikan Anda mengimpor dari `@stripe/react-stripe-js/checkout`, gunakan `CheckoutElementsProvider` dengan client secret, dan konfirmasi menggunakan `checkout.confirm`. Jika menggunakan HTML, pastikan Anda menggunakan `checkout = stripe.initCheckoutElements({clientSecret: promise}); checkout.createPaymentElement(); paymentElement = checkout.createPaymentElement(); paymentElement.mount(""#payment-element"");` dan konfirmasi dengan `loadActionsResult = await checkout.loadActions(); actions = loadActionsResult.actions; error = await actions.confirm();`. # Bangun halaman checkout dengan Payment Intents API Pelajari cara menyematkan formulir pembayaran Stripe custom di situs web atau aplikasi Anda. Kode sisi client dan server membuat formulir checkout dengan elemen [Web](https://docs.stripe.com/payments/elements.md) atau [Seluler](https://docs.stripe.com/payments/mobile.md) Stripe untuk memungkinkan Anda menerima pembayaran. Untuk membangun integrasi custom yang melampaui dasar-dasar mulai cepat ini, lihat [Terima pembayaran](https://docs.stripe.com/payments/accept-a-payment.md?&ui=elements). Untuk mempelajari tentang berbagai skenario pembayaran, seperti [langganan](https://docs.stripe.com/billing/subscriptions/build-subscriptions.md?payment-ui=elements), dan produk Stripe lainnya, [bandingkan integrasi pembayaran](https://docs.stripe.com/payments/online-payments.md#compare-features-and-availability). > #### Tertarik menggunakan Stripe Tax, diskon, pengiriman, atau konversi mata uang? > > Stripe memiliki integrasi Payment Element yang mengelola pajak, diskon, pengiriman, dan konversi mata uang. Lihat [buat halaman checkout](https://docs.stripe.com/payments/quickstart-checkout-sessions.md) untuk mempelajari lebih lanjut. // 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 ~~~ ### Instal pustaka Stripe Node Instal paket dan impor ke dalam kode Anda. Alternatifnya, jika Anda mulai dari nol dan memerlukan file package.json, unduh file proyek menggunakan tautan Unduh di editor kode. #### npm Instal pustaka: ```bash npm install --save stripe ``` #### GitHub Atau unduh kode pustaka stripe-node langsung [dari GitHub](https://github.com/stripe/stripe-node). ### Instal pustaka Stripe Ruby Instal ruby gem Stripe dan impor ke dalam kode Anda. Alternatifnya, jika Anda mulai dari nol dan memerlukan Gemfile, unduh file proyek menggunakan tautan di editor kode. #### Terminal Instal gem: ```bash gem install stripe ``` #### Bundler Tambahkan baris ini ke Gemfile Anda: ```bash gem 'stripe' ``` #### GitHub Atau unduh kode sumber modul stripe-ruby gem langsung [dari GitHub](https://github.com/stripe/stripe-ruby). ### Instal pustaka Java Stripe Tambahkan dependensi pada versi build Anda dan impor pustaka. Alternatifnya, jika Anda mulai dari nol dan memerlukan file pom.xml (untuk Maven), unduh file proyek menggunakan tautan Unduh di editor kode. #### Maven Tambahkan dependensi berikut pada POM Anda dan ganti {VERSION} dengan nomor versi yang ingin Anda gunakan. ```bash \ncom.stripe\nstripe-java\n{VERSION}\n ``` #### Gradle Tambahkan dependensi pada file build.gradle Anda dan ganti {VERSION} dengan nomor versi yang ingin Anda gunakan. ```bash implementation "com.stripe:stripe-java:{VERSION}" ``` #### GitHub Unduh JAR langsung [dari GitHub](https://github.com/stripe/stripe-java/releases/latest). ### Instal paket Stripe Python Instal paket Stripe dan impor ke dalam kode Anda. Alternatifnya, jika Anda mulai dari nol dan memerlukan file requirements.txt, unduh file proyek menggunakan tautan Unduh di editor kode. #### pip Instal paket melalui pip: ```bash pip3 install stripe ``` #### GitHub Unduh kode sumber pustaka stripe-python secara langsung [dari GitHub](https://github.com/stripe/stripe-python). ### Instal pustaka Stripe PHP Instal pustaka dengan composer dan inisialisasi dengan kunci API secret Anda. Alternatifnya, jika Anda mulai dari nol dan memerlukan file composer.json, unduh file ini menggunakan tautan Unduh di editor kode. #### Composer Instal pustaka: ```bash composer require stripe/stripe-php ``` #### GitHub Atau unduh kode pustaka stripe-php langsung [dari GitHub](https://github.com/stripe/stripe-php). ### Siapkan server Anda Tambahkan dependensi pada versi build Anda dan impor pustaka. Alternatifnya, jika Anda mulai dari nol dan memerlukan file go.mod, unduh file proyek menggunakan tautan Unduh di editor kode. #### Go Pastikan untuk menginisialisasi Modul Go: ```bash go get -u github.com/stripe/stripe-go/v85 ``` #### GitHub Atau unduh kode sumber modul stripe-go langsung [dari GitHub](https://github.com/stripe/stripe-go). ### Instal pustaka Stripe.net Instal paket dengan .NET atau NuGet. Alternatifnya, jika Anda mulai dari nol, unduh file yang berisi file .csproj yang telah dikonfigurasikan. #### dotnet Instal pustaka: ```bash dotnet add package Stripe.net ``` #### NuGet Instal pustaka: ```bash Install-Package Stripe.net ``` #### GitHub Atau unduh kode sumber pustaka Stripe.net langsung [dari GitHub](https://github.com/stripe/stripe-dotnet). ### Instal pustaka Stripe Instal paket dan impor ke dalam kode Anda. Alternatifnya, jika Anda mulai dari nol dan memerlukan file `package.json`, unduh file proyek menggunakan tautan di editor kode. Instal pustaka: ```bash npm install --save stripe @stripe/stripe-js next ``` ### Buat PaymentIntent Tambahkan endpoint pada server Anda yang membuat [PaymentIntent](https://docs.stripe.com/api/payment_intents.md). Sebuah PaymentIntent melacak siklus pembayaran pelanggan, memantau setiap upaya pembayaran yang gagal dan memastikan bahwa pelanggan hanya di-charge sekali. Kembalikan *client secret* (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)) PaymentIntent dalam tanggapan untuk menyelesaikan pembayaran pada client. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Tambahkan Stripe ke aplikasi React Gunakan *Stripe.js* (Use Stripe.js’ APIs to tokenize customer information, collect sensitive card data, and accept payments with browser payment APIs) dan [pustaka UI Stripe Elements](https://docs.stripe.com/sdks/stripejs-react.md) agar tetap mematuhi *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) dengan memastikan bahwa detail pembayaran langsung masuk ke Stripe dan tidak pernah mencapai server Anda. ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` ### Tambahkan Stripe ke aplikasi React Gunakan *Stripe.js* (Use Stripe.js’ APIs to tokenize customer information, collect sensitive card data, and accept payments with browser payment APIs) dan [pustaka UI Stripe Elements](https://docs.stripe.com/sdks/stripejs-react.md) agar tetap mematuhi *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) dengan memastikan bahwa detail pembayaran langsung masuk ke Stripe dan tidak pernah mencapai server Anda. ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` ### Muat Stripe.js Panggil `loadStripe()` dengan [kunci API yang dapat dipublikasikan](https://docs.stripe.com/keys.md#obtain-api-keys) Stripe Anda untuk mengonfigurasi pustaka Stripe. ### Muat Stripe.js Panggil `loadStripe()` dengan [kunci API yang dapat dipublikasikan](https://docs.stripe.com/keys.md#obtain-api-keys) Stripe Anda untuk mengonfigurasi pustaka Stripe. ### Muat Stripe.js Gunakan *Stripe.js* (Use Stripe.js’ APIs to tokenize customer information, collect sensitive card data, and accept payments with browser payment APIs) agar tetap mematuhi *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) dengan memastikan bahwa detail pembayaran dikirim langsung ke Stripe tanpa melewati server Anda. Selalu muat Stripe.js dari js.stripe.com agar tetap patuh. Jangan sertakan skrip dalam bundel atau meng-hosting sendiri. ### Definisikan formulir pembayaran Tambahkan satu placeholder `div` kosong ke formulir checkout Anda untuk setiap Element yang akan Anda pasang. Stripe menyisipkan iframe ke setiap `div` untuk mengumpulkan alamat email dan informasi pembayaran pelanggan dengan aman. ### Inisialisasi Stripe.js Inisialisasikan Stripe.js dengan [kunci API yang dapat dipublikasikan](https://docs.stripe.com/keys.md#obtain-api-keys). Anda akan menggunakan Stripe.js untuk membuat Payment Element dan menyelesaikan pembayaran pada client. ### Ambil PaymentIntent Segera buat permintaan ke endpoint pada server Anda untuk membuat PaymentIntent baru segera setelah halaman checkout dimuat. `clientSecret` yang dikembalikan endpoint digunakan untuk menyelesaikan pembayaran. ### Inisialisasi Stripe Elements Teruskan hasil yang dijanjikan dari `loadStripe` ke penyedia Elements. Hal ini memungkinkan komponen anak mengakses layanan Stripe dengan konsumen Elements. Selain itu, teruskan client secret sebagai opsi ke penyedia Elements. ### Inisialisasi Stripe Elements Teruskan hasil yang dijanjikan dari `loadStripe` ke penyedia Elements. Hal ini memungkinkan komponen anak mengakses layanan Stripe melalui konsumen Elements. Selain itu, teruskan client secret sebagai opsi ke penyedia Elements. ### Inisialisasi Stripe Elements Inisialisasikan [pustaka UI Stripe Elements](https://docs.stripe.com/js/elements_object/create) dengan client secret. Elements mengelola komponen UI yang Anda perlukan untuk mengumpulkan detail pembayaran. ### Siapkan status Inisialisasi beberapa status untuk melacak pembayaran, menampilkan kesalahan, dan mengelola antarmuka pengguna. ### Siapkan status Inisialisasi beberapa status untuk melacak pembayaran, menampilkan kesalahan, dan mengelola antarmuka pengguna. ### Simpan referensi ke Stripe Akses pustaka Stripe di komponen CheckoutForm Anda dengan menggunakan kaitan `useStripe()` dan `useElements()`. Jika Anda perlu mengakses Elements dengan komponen kelas, gunakan [ElementsConsumer](https://docs.stripe.com/sdks/stripejs-react.md#elements-consumer) sebagai gantinya. ### Simpan referensi ke Stripe Akses pustaka Stripe di komponen CheckoutForm Anda dengan menggunakan kaitan `useStripe()` dan `useElements()`. Jika Anda perlu mengakses Elements melalui komponen kelas, gunakan [ElementsConsumer](https://docs.stripe.com/sdks/stripejs-react.md#elements-consumer) sebagai gantinya. ### Tambahkan PaymentElement Tambahkan [PaymentElement](https://docs.stripe.com/js/elements_object/create_payment_element) ke formulir pembayaran Anda. Penyematan ini menyematkan iframe dengan formulir dinamis yang mengumpulkan detail pembayaran untuk berbagai metode pembayaran. Pelanggan Anda dapat memilih jenis metode pembayaran, dan formulir secara otomatis mengumpulkan semua detail pembayaran yang diperlukan untuk pilihannya ### Tambahkan PaymentElement Tambahkan [PaymentElement](https://docs.stripe.com/js/elements_object/create_payment_element) ke formulir pembayaran Anda. Penyematan ini menyematkan iframe dengan formulir dinamis yang mengumpulkan detail pembayaran untuk berbagai metode pembayaran. Pelanggan Anda dapat memilih jenis metode pembayaran, dan formulir secara otomatis mengumpulkan semua detail pembayaran yang diperlukan untuk pilihannya ### Buat PaymentElement Buat [PaymentElement](https://docs.stripe.com/js/elements_object/create_payment_element) dan pasangkan ke placeholder `
` di formulir pembayaran Anda. Hal ini menyematkan iframe dengan formulir dinamis yang menampilkan tipe metode pembayaran terkonfigurasi yang tersedia dari PaymentIntent, sehingga memungkinkan pelanggan Anda memilih metode pembayaran. Formulir secara otomatis mengumpulkan detail pembayaran terkait untuk tipe metode pembayaran yang dipilih. ### (Opsional) Buat gaya Payment Element Sesuaikan UI Elemen Pembayaran dengan membuat [Objek tampilan](https://docs.stripe.com/elements/appearance-api.md) dan meneruskannya sebagai opsi ke penyedia Elements. Gunakan skema warna dan font perusahaan Anda agar sesuai dengan bagian lain dari halaman checkout Anda. Gunakan font khusus (misalnya, dari Google Fonts) dengan menginisialisasi Elements dengan [set font](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-fonts). Pastikan membuka pratinjau di sebelah kanan untuk melihat perubahan Anda secara live. > Bagian dari demo pratinjau mungkin tidak sama dengan halaman pembayaran Anda yang sebenarnya. Pengaturan di atas hanya mewakili sebagian dari variabel [Objek tampilan](https://docs.stripe.com/elements/appearance-api.md), dan [Objek tampilan](https://docs.stripe.com/elements/appearance-api.md) hanya mengontrol atribut tertentu dari Stripe Elements. Anda bertanggung jawab untuk menata tampilan halaman checkout Anda. ### (Opsional) Buat gaya Payment Element Sesuaikan UI Elemen Pembayaran dengan membuat [Objek tampilan](https://docs.stripe.com/elements/appearance-api.md) dan meneruskannya sebagai opsi ke penyedia Elements. Gunakan skema warna dan font perusahaan Anda agar sesuai dengan bagian lain dari halaman checkout Anda. Gunakan font khusus (misalnya, dari Google Fonts) dengan menginisialisasi Elements dengan [set font](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-fonts). Pastikan membuka pratinjau di sebelah kanan untuk melihat perubahan Anda secara live. > Bagian dari demo pratinjau mungkin tidak sama dengan halaman checkout Anda yang sebenarnya. Pengaturan di atas hanya mewakili subset dari variabel objek Appearance, dan objek Appearance hanya mengontrol atribut Stripe Elements tertentu. Anda bertanggung jawab untuk menata gaya halaman checkout lainnya. ### (Opsional) Buat gaya Payment Element Sesuaikan UI Elemen Pembayaran dengan membuat [Objek tampilan](https://docs.stripe.com/elements/appearance-api.md) dan menginisialisasi Elements dengan objek tersebut. Gunakan skema warna dan font perusahaan Anda agar sesuai dengan bagian lain dari halaman checkout Anda. Gunakan font khusus (misalnya, dari Google Fonts) dengan menginisialisasi Elements dengan [set font](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-fonts). Pastikan membuka pratinjau di sebelah kanan untuk melihat perubahan Anda secara live. > Bagian dari demo pratinjau mungkin tidak sama dengan halaman pembayaran Anda yang sebenarnya. Pengaturan di atas hanya mewakili sebagian dari variabel [Objek tampilan](https://docs.stripe.com/elements/appearance-api.md), dan [Objek tampilan](https://docs.stripe.com/elements/appearance-api.md) hanya mengontrol atribut tertentu dari Stripe Elements. Anda bertanggung jawab untuk menata tampilan halaman checkout Anda. ### Tangani kejadian penyerahan Dengarkan kejadian penyerahan formulir untuk mengetahui waktu mengonfirmasi pembayaran melalui API Stripe. ### Selesaikan pembayaran Saat pelanggan Anda mengklik tombol bayar, panggil [confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) dengan PaymentElement dan sertakan [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) untuk menunjukkan ke mana Stripe akan mengarahkan pelanggan setelah mereka menyelesaikan pembayaran. Untuk pembayaran yang memerlukan autentikasi, Stripe akan menampilkan modal untuk autentikasi *3D Secure* (3D Secure (3DS) provides an additional layer of authentication for credit card transactions that protects businesses from liability for fraudulent card payments) atau mengarahkan pelanggan ke halaman autentikasi, tergantung pada metode pembayaran. Setelah pelanggan menyelesaikan proses autentikasi, mereka diarahkan ke `return_url`. ### Selesaikan pembayaran Saat pelanggan Anda mengklik tombol bayar, panggil [confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) dengan PaymentElement dan sertakan [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) untuk menunjukkan ke mana Stripe akan mengarahkan pelanggan setelah mereka menyelesaikan pembayaran. Untuk pembayaran yang memerlukan autentikasi, Stripe akan menampilkan modal untuk autentikasi *3D Secure* (3D Secure (3DS) provides an additional layer of authentication for credit card transactions that protects businesses from liability for fraudulent card payments) atau mengarahkan pelanggan ke halaman autentikasi, tergantung pada metode pembayaran. Setelah pelanggan menyelesaikan proses autentikasi, mereka diarahkan ke `return_url`. ### Selesaikan pembayaran Panggil [confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) dengan instance Element dan [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) untuk menunjukkan ke mana Stripe akan mengarahkan pelanggan setelah mereka menyelesaikan pembayaran. Untuk pembayaran yang memerlukan autentikasi, Stripe akan menampilkan modal untuk autentikasi *3D Secure* (3D Secure (3DS) provides an additional layer of authentication for credit card transactions that protects businesses from liability for fraudulent card payments) atau mengarahkan pelanggan ke halaman autentikasi, tergantung pada metode pembayaran. Setelah pelanggan menyelesaikan proses autentikasi, mereka diarahkan ke `return_url`. ### Tangani kesalahan Jika ada [kesalahan](https://docs.stripe.com/error-codes.md) langsung (misalnya, kartu pelanggan Anda ditolak), Stripe.js mengembalikan kesalahan. Tampilkan pesan kesalahan ini kepada pelanggan agar dapat mencoba lagi. ### Tampilkan pesan status pembayaran Saat Stripe mengalihkan pelanggan ke `return_url`, parameter query `payment_intent_client_secret` ditambahkan oleh Stripe.js. Gunakan ini untuk mengambil [pembaruan status PaymentIntent](https://docs.stripe.com/payments/payment-intents/verifying-status.md) dan menentukan apa yang akan ditampilkan kepada pelanggan Anda. ### Tampilkan pesan status pembayaran Bila Stripe mengalihkan pelanggan ke `return_url`, parameter query `payment_intent` ditambahkan oleh Stripe.js. Gunakan ini untuk mengambil [pembaruan status PaymentIntent](https://docs.stripe.com/payments/payment-intents/verifying-status.md) dan menentukan apa yang akan ditampilkan kepada pelanggan Anda. ### Gunakan webhook Stripe mengirim beberapa kejadian selama proses pembayaran dan setelah pembayaran selesai. Buat [tujuan kejadian](https://docs.stripe.com/event-destinations.md) bagi [endpoint webhook](https://docs.stripe.com/webhooks/quickstart.md) untuk menerima kejadian ini dan menjalankan tindakan, seperti mengirim email konfirmasi pesanan kepada pelanggan Anda, mencatat penjualan di database, atau memulai alur kerja pengiriman. Stripe merekomendasikan penanganan kejadian [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), dan [payment_intent.payment_failed](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.payment_failed). Dengarkan kejadian ini daripada menunggu callback dari client. Di client, pelanggan dapat menutup jendela browser atau keluar dari aplikasi sebelum callback mengeksekusi, dan klien jahat dapat memanipulasi respons. Penyiapan integrasi untuk mendengarkan kejadian asinkron memungkinkan Anda menyetujui [berbagai tipe metode pembayaran](https://stripe.com/payments/payment-methods-guide) dengan satu integrasi tunggal. ### Jalankan aplikasi Jalankan aplikasi React dan server. Buka [localhost:3000/checkout](http://localhost:3000/checkout) untuk melihat halaman checkout Anda. ```bash npm start ``` ### Jalankan aplikasi Jalankan aplikasi Next.js. Buka [localhost:3000](http://localhost:3000) untuk melihat halaman checkout Anda. ```bash npm run dev ``` ### Jalankan aplikasi Jalankan server Node Anda dan buka [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash npm start ``` ### Jalankan aplikasi server Jalankan aplikasi React dan server. Buka [localhost:3000/checkout](http://localhost:3000/checkout) untuk melihat halaman checkout Anda. ```bash ruby server.rb ``` ### Jalankan aplikasi Jalankan server Ruby Anda dan buka [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash ruby server.rb ``` ### Jalankan aplikasi server Jalankan aplikasi React dan server. Buka [localhost:3000/checkout](http://localhost:3000/checkout) untuk melihat halaman checkout Anda. ```bash python3 -m flask run --port=4242 ``` ### Jalankan aplikasi Jalankan server Python Anda dan buka [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash python3 -m flask run --port=4242 ``` ### Jalankan aplikasi server Jalankan aplikasi React dan server. Buka [localhost:3000/checkout](http://localhost:3000/checkout) untuk melihat halaman checkout Anda. ```bash php -S 127.0.0.1:4242 --docroot=public ``` ### Jalankan aplikasi Jalankan server Anda dan buka [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash php -S 127.0.0.1:4242 --docroot=public ``` ### Jalankan aplikasi server Jalankan aplikasi React dan server. Buka [localhost:3000/checkout](http://localhost:3000/checkout) untuk melihat halaman checkout Anda. ```bash go run server.go ``` ### Jalankan aplikasi Jalankan server Go Anda dan buka [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash go run server.go ``` ### Jalankan aplikasi server Jalankan aplikasi React dan server. Buka [localhost:3000/checkout](http://localhost:3000/checkout) untuk melihat halaman checkout Anda. ```bash dotnet run ``` ### Jalankan aplikasi Jalankan server MVC ASP.NET Anda dan buka [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash dotnet run ``` ### Jalankan aplikasi Jalankan server Anda dan buka [localhost:4242/checkout.html](http://localhost:4242/checkout.html). ```bash java -cp target/sample-jar-with-dependencies.jar com.stripe.sample.Server ``` ### Jalankan aplikasi server Jalankan aplikasi React dan server. Buka [localhost:3000/checkout](http://localhost:3000/checkout) untuk melihat halaman checkout Anda. ```bash java -cp target/sample-jar-with-dependencies.jar com.stripe.sample.Server ``` ### Jalankan aplikasi Jalankan aplikasi React dan buka [localhost:3000/checkout](http://localhost:3000/checkout). ```bash npm start ``` ### Buat pembayaran percobaan Untuk memverifikasi bahwa integrasi Anda berfungsi, lakukan pembayaran pengujian menggunakan [uji detail pembayaran](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=elements&api-integration=paymentintents#web-test-the-integration). ### Lihat pembayaran Anda di Dashboard Buka [Dashboard Stripe](https://dashboard.stripe.com/test/payments) untuk melihat pembayaran percobaan Anda. ## Terima pembayaran dan tingkatkan integrasi Anda Anda siap menerima pembayaran dengan Stripe. Lanjutkan dengan langkah-langkah di bawah untuk menambahkan fitur-fitur lainnya. ### Otomatiskan pemungutan pajak Hitung dan pungut jumlah pajak yang tepat untuk transaksi Stripe Anda. Sebelum menggunakan Stripe Tax, Anda perlu mengaktifkannya di [Dashboard](https://dashboard.stripe.com/tax). Pelajari selengkapnya tentang [Stripe Tax](https://docs.stripe.com/tax.md) dan [cara menambahkannya ke integrasi Payments Anda](https://docs.stripe.com/tax/custom.md). ### Gunakan Stripe Tax API untuk menghitung pajak Gunakan [Stripe Tax API](https://docs.stripe.com/api/tax/calculations/create.md) untuk menghitung pajak atas transaksi. Berikan `currency`, `customer_details`, dan `line_items` pesanan di isi permintaan. Gunakan atribut `tax_amount_exclusive` dari Perhitungan Pajak yang dihasilkan untuk menambahkan pajak eksklusif ke total pesanan. ### Catat Transaksi Pajak setelah Pembayaran berhasil Menautkan perhitungan pajak ke PaymentIntent menggunakan `kait[input][pajak][perhitungan]`. Halaman ini mencatat pajak yang dikumpulkan di akun Stripe Anda yang nantinya dapat Anda ekspor untuk tujuan akuntansi, dan memicu [tindakan Stripe](https://docs.stripe.com/tax/payment-intent.md#automatic-actions) lainnya. ### Kirim tanda terima email Stripe dapat mengirim tanda terima email ke pelanggan Anda menggunakan logo brand dan tema warna brand Anda, yang dapat dikonfigurasikan dalam [Dashboard](https://dashboard.stripe.com/settings/branding). ### Kumpulkan alamat email pelanggan Tambahkan bidang input ke formulir pembayaran Anda untuk mengumpulkan alamat email. ### Tambahkan email ke negara bagian Tambahkan variabel untuk terus melacak email yang dimasukkan pelanggan. ### Tambahkan email ke negara bagian Tambahkan variabel untuk terus melacak email yang dimasukkan pelanggan. ### Berikan alamat email ke Stripe Teruskan alamat email yang diberikan sebagai nilai `receipt_email`. Stripe mengirim email resi bila pembayaran berhasil dalam mode live (tetapi tidak akan mengirimnya dalam *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)). ### Simpan detail pembayaran setelah pembayaran Sering digunakan oleh SaaS atau bisnis e-commerce yang memiliki pelanggan rutin. ### Impor sumber daya Stripe tambahan Impor Stripe paket `customer` dan `paymentmethod`. Gunakan paket ini untuk menyimpan informasi tentang pelanggan Anda. ### Impor sumber daya Stripe tambahan Impor model Stripe PaymentMethod dan Pelanggan. Gunakan model-model ini untuk menyimpan informasi tentang Pelanggan Anda. ### Buat pelanggan Stripe menyimpan kartu pada objek *Pelanggan* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments). Buat Pelanggan baru sebelum membuat PaymentIntent. Anda dapat juga menyimpan nama, email, alamat pengiriman, dan detail lain pada Pelanggan. ### Buat pelanggan Stripe menyimpan kartu pada objek [Akun](https://docs.stripe.com/api/v2/core/accounts/object.md) yang mewakili [pelanggan](https://docs.stripe.com/connect/account-capabilities.md?accounts-namespace=v2#customer). Buat Akun baru sebelum membuat PaymentIntent. Anda juga dapat menyimpan nama, email, alamat pengiriman, dan detail lainnya pada Akun. ### Tambahkan pelanggan ke PaymentIntent Teruskan identifikasi Pelanggan ke PaymentIntent dan atur `setup_future_usage` ke `off_session`. `setup_future_usage` memberi tahu Stripe cara Anda berencana menggunakan metode pembayaran—wilayah tertentu, seperti Eropa dan India, memiliki persyaratan seputar penggunaan kembali detail pembayaran. [Pelajari lebih lanjut](https://docs.stripe.com/payments/payment-intents.md#future-usage) tentang cara paling efektif untuk menerapkan `setup_future_usage`. Anda juga dapat melihat [daftar metode pembayaran yang didukung](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability). Setelah PaymentIntent berhasil, Stripe secara otomatis [melampirkan](https://docs.stripe.com/api/payment_methods/attach.md) detail pembayaran (dalam objek *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs)) kepada Pelanggan Anda. ### Tambahkan pelanggan ke PaymentIntent Teruskan ID Akun ke PaymentIntent dan atur `setup_future_usage` ke `off_session`. `setup_future_usage` memberi tahu Stripe cara Anda berencana menggunakan metode pembayaran—wilayah tertentu, seperti Eropa dan India, memiliki persyaratan seputar penggunaan kembali detail pembayaran. [Pelajari selengkapnya](https://docs.stripe.com/payments/payment-intents.md#future-usage) tentang cara paling efektif untuk menerapkan `setup_future_usage`. Anda juga dapat melihat [daftar metode pembayaran yang didukung](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability). Setelah PaymentIntent berhasil, Stripe secara otomatis [melampirkan](https://docs.stripe.com/api/payment_methods/attach.md) detail pembayaran (dalam objek *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs)) ke Akun yang dikonfigurasi pelanggan. ### Charge PaymentMethod tersimpan Saat Anda siap men-charge PaymentMethod kembali, buat PaymentIntent baru dengan Identifikasi Pelanggan, identifikasi PaymentMethod yang ingin Anda charge, serta atur tanda `off_session` dan `confirm` ke true. ### Instal pustaka Stripe Node Instal paket dan impor ke dalam kode Anda. Alternatifnya, jika Anda mulai dari nol dan memerlukan file package.json, unduh file proyek menggunakan tautan Unduh di editor kode. #### npm Instal pustaka: ```bash npm install --save stripe ``` #### GitHub Atau unduh kode pustaka stripe-node langsung [dari GitHub](https://github.com/stripe/stripe-node). ### Instal pustaka Stripe Ruby Instal ruby gem Stripe dan impor ke dalam kode Anda. Alternatifnya, jika Anda mulai dari nol dan memerlukan Gemfile, unduh file proyek menggunakan tautan di editor kode. #### Terminal Instal gem: ```bash gem install stripe ``` #### Bundler Tambahkan baris ini ke Gemfile Anda: ```bash gem 'stripe' ``` #### GitHub Atau unduh kode sumber modul stripe-ruby gem langsung [dari GitHub](https://github.com/stripe/stripe-ruby). ### Instal pustaka Java Stripe Tambahkan dependensi pada versi build Anda dan impor pustaka. Alternatifnya, jika Anda mulai dari nol dan memerlukan file pom.xml (untuk Maven), unduh file proyek menggunakan tautan Unduh di editor kode. #### Maven Tambahkan dependensi berikut pada POM Anda dan ganti {VERSION} dengan nomor versi yang ingin Anda gunakan. ```bash \ncom.stripe\nstripe-java\n{VERSION}\n ``` #### Gradle Tambahkan dependensi pada file build.gradle Anda dan ganti {VERSION} dengan nomor versi yang ingin Anda gunakan. ```bash implementation "com.stripe:stripe-java:{VERSION}" ``` #### GitHub Unduh JAR langsung [dari GitHub](https://github.com/stripe/stripe-java/releases/latest). ### Instal paket Stripe Python Instal paket Stripe dan impor ke dalam kode Anda. Alternatifnya, jika Anda mulai dari nol dan memerlukan file requirements.txt, unduh file proyek menggunakan tautan Unduh di editor kode. #### pip Instal paket melalui pip: ```bash pip3 install stripe ``` #### GitHub Unduh kode sumber pustaka stripe-python secara langsung [dari GitHub](https://github.com/stripe/stripe-python). ### Instal pustaka Stripe PHP Instal pustaka dengan composer dan inisialisasi dengan kunci API secret Anda. Alternatifnya, jika Anda mulai dari nol dan memerlukan file composer.json, unduh file ini menggunakan tautan Unduh di editor kode. #### Composer Instal pustaka: ```bash composer require stripe/stripe-php ``` #### GitHub Atau unduh kode pustaka stripe-php langsung [dari GitHub](https://github.com/stripe/stripe-php). ### Siapkan server Anda Tambahkan dependensi pada versi build Anda dan impor pustaka. Alternatifnya, jika Anda mulai dari nol dan memerlukan file go.mod, unduh file proyek menggunakan tautan Unduh di editor kode. #### Go Pastikan untuk menginisialisasi Modul Go: ```bash go get -u github.com/stripe/stripe-go/v85 ``` #### GitHub Atau unduh kode sumber modul stripe-go langsung [dari GitHub](https://github.com/stripe/stripe-go). ### Instal pustaka Stripe.net Instal paket dengan .NET atau NuGet. Alternatifnya, jika Anda mulai dari nol, unduh file yang berisi file .csproj yang telah dikonfigurasikan. #### dotnet Instal pustaka: ```bash dotnet add package Stripe.net ``` #### NuGet Instal pustaka: ```bash Install-Package Stripe.net ``` #### GitHub Atau unduh kode sumber pustaka Stripe.net langsung [dari GitHub](https://github.com/stripe/stripe-dotnet). ### Instal pustaka Stripe Instal paket dan impor ke dalam kode Anda. Alternatifnya, jika Anda mulai dari nol dan memerlukan file `package.json`, unduh file proyek menggunakan tautan di editor kode. Instal pustaka: ```bash npm install --save stripe @stripe/stripe-js next ``` ### Buat PaymentIntent Tambahkan endpoint pada server Anda yang membuat [PaymentIntent](https://docs.stripe.com/api/payment_intents.md). Sebuah PaymentIntent melacak siklus pembayaran pelanggan, memantau setiap upaya pembayaran yang gagal dan memastikan bahwa pelanggan hanya di-charge sekali. Kembalikan *client secret* (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)) PaymentIntent dalam tanggapan untuk menyelesaikan pembayaran pada client. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Instal SDK SDK iOS Stripe adalah [sumber terbuka](https://github.com/stripe/stripe-ios), [didokumentasikan lengkap](https://stripe.dev/stripe-ios/), dan kompatibel dengan aplikasi yang mendukung iOS 13 atau yang terbaru. Impor SDK Stripe ke View Controller layar checkout Anda. #### Swift Package Manager Di Xcode, pilih **File** > **Tambahkan Dependensi Paket…** dan masukkan `https://github.com/stripe/stripe-ios-spm` sebagai URL repositori. Pilih nomor versi terbaru dari [halaman rilis](https://github.com/stripe/stripe-ios/releases) kami, dan tambahkan modul `StripePaymentSheet` ke target aplikasi Anda. #### CocoaPods Tambahkan baris ini ke Podfile Anda, dan gunakan .xcworkspace untuk membuka proyek Anda di Xcode, sebagai ganti file .xcodeproj, mulai sekarang. ```bash pod 'StripePaymentSheet' ``` #### Carthage Tambahkan baris ini ke Cartfile Anda. ```bash github "stripe/stripe-ios" ``` #### Kerangka Kerja Manual Untuk menyertakan Stripe dalam proyek Anda, unduh dan unzip Stripe.xcframework.zip dari [rilis di GitHub](https://github.com/stripe/stripe-ios/releases). Seret file xcframework yang diperlukan ke pengaturan “Embedded Binaries” di proyek Xcode Anda. Pastikan untuk memilih “Salin item jika diperlukan”. ### Siapkan SDK Konfigurasikan SDK Stripe dengan [kunci API yang dapat dipublikasikan](https://docs.stripe.com/keys.md#obtain-api-keys) Stripe Anda. Pengodean keras kunci API yang dapat dipublikasikan di SDK hanya untuk demonstrasi. Dalam aplikasi produksi, Anda harus mengambil kunci API dari server. ### Ambil PaymentIntent Buat permintaan ke server Anda untuk PaymentIntent segera setelah tampilan dimuat. Simpan referensi ke *client secret* (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)) PaymentIntent yang dikembalikan oleh server; Payment Sheet menggunakan rahasia ini untuk menyelesaikan pembayaran nanti. ### Konfigurasikan dan sajikan Payment Sheet Buat instance `PaymentSheet` menggunakan client secret yang diambil sebelumnya, dan sajikan dari pengontrol tampilan Anda. Gunakan struktur `PaymentSheet.Configuration` untuk [menyesuaikan](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html) Payment Sheet. ### Tangani hasil pembayaran Gunakan blok penyelesaian untuk menangani hasil pembayaran. Jika pembayaran gagal dengan [kesalahan](https://docs.stripe.com/error-codes.md), tampilkan pesan yang sesuai kepada pelanggan Anda sehingga pelanggan dapat mengambil tindakan dan mencoba lagi. Jika tidak terjadi kesalahan, sampaikan kepada pelanggan bahwa pembayaran berhasil. ### Buat pembayaran percobaan #### iOS Untuk memverifikasi bahwa integrasi Anda berfungsi, lakukan uji pembayaran menggunakan [uji detail pembayaran](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios#ios-test-the-integration). #### Android Untuk memverifikasi bahwa integrasi Anda berfungsi, lakukan uji pembayaran menggunakan [uji detail pembayaran](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=android#android-test-the-integration). ### Lihat pembayaran Anda di Dashboard Buka [Dashboard Stripe](https://dashboard.stripe.com/test/payments) untuk melihat pembayaran percobaan Anda. ## Terima pembayaran dan tingkatkan integrasi Anda Anda siap menerima pembayaran dengan Stripe. Lanjutkan dengan langkah-langkah di bawah untuk menambahkan fitur-fitur lainnya. ### Otomatiskan pemungutan pajak Hitung dan pungut jumlah pajak yang tepat untuk transaksi Stripe Anda. Sebelum menggunakan Stripe Tax, Anda perlu mengaktifkannya di [Dashboard](https://dashboard.stripe.com/tax). Pelajari selengkapnya tentang [Stripe Tax](https://docs.stripe.com/tax.md) dan [cara menambahkannya ke integrasi Payments Anda](https://docs.stripe.com/tax/custom.md). ### Gunakan Stripe Tax API untuk menghitung pajak Gunakan [Stripe Tax API](https://docs.stripe.com/api/tax/calculations/create.md) untuk menghitung pajak atas transaksi. Berikan `currency`, `customer_details`, dan `line_items` pesanan di isi permintaan. Gunakan atribut `tax_amount_exclusive` dari Perhitungan Pajak yang dihasilkan untuk menambahkan pajak eksklusif ke total pesanan. ### Catat Transaksi Pajak setelah Pembayaran berhasil Menautkan perhitungan pajak ke PaymentIntent menggunakan `kait[input][pajak][perhitungan]`. Halaman ini mencatat pajak yang dikumpulkan di akun Stripe Anda yang nantinya dapat Anda ekspor untuk tujuan akuntansi, dan memicu [tindakan Stripe](https://docs.stripe.com/tax/payment-intent.md#automatic-actions) lainnya. ### Izinkan metode pembayaran tertunda Beberapa metode pembayaran tidak dapat menjamin bahwa Anda akan menerima dana dari pelanggan di akhir proses checkout karena perlu waktu untuk menyelesaikannya (misalnya, sebagian besar debit bank, seperti SEPA atau ACH) atau mengharuskan tindakan pelanggan untuk menyelesaikannya (misalnya, OXXO, Konbini, Boleto). Gunakan tanda ini untuk mengaktifkan metode pembayaran yang tertunda. Jika Anda mengaktifkan fitur ini, pastikan integrasi server Anda mendengarkan [webhook](https://docs.stripe.com/payments/payment-methods.md#payment-notification) untuk notifikasi mengenai berhasil atau tidaknya pembayaran. ### Tambahkan dukungan Apple Pay Untuk mengaktifkan Apple Pay, berikan [Identifikasi Merchant Apple Pay](https://support.stripe.com/questions/enable-apple-pay-on-your-stripe-account) dan [kode negara](https://dashboard.stripe.com/settings/account) akun Stripe Anda. ### Tambahkan dukungan Google Pay Untuk menggunakan Google Pay, aktifkan Google Pay API terlebih dahulu di AndroidManifest.xml Anda. Aktifkan Google Pay dengan meneruskan objek [PaymentSheet.GooglePayConfiguration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-google-pay-configuration/index.html) bersama lingkungan Google Pay (produksi atau percobaan) dan [kode negara bisnis Anda](https://dashboard.stripe.com/settings/account) ketika menginisialisasi [PaymentSheet. Konfigurasi](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-configuration/index.html). ### Sesuaikan warna tombol utama Pertimbangkan untuk menggunakan warna custom untuk tombol utama yang lebih cocok dengan identitas visual brand atau aplikasi Anda. ### Aktifkan pemindaian kartu Pemindaian kartu dapat membantu meningkatkan rasio konversi Anda dengan menghilangkan hambatan entri kartu manual. Untuk mengaktifkan pemindaian kartu, atur `NSCameraUsageDescription` di `Info.plist` aplikasi Anda, dan berikan alasan untuk mengakses kamera (misalnya, “Untuk memindai kartu”). > Pemindaian kartu hanya didukung di perangkat yang menjalankan iOS 13 atau lebih tinggi. ### Aktifkan pemindaian kartu Pemindaian kartu dapat membantu meningkatkan rasio konversi Anda dengan menghilangkan hambatan entri kartu manual. Untuk mengaktifkan pemindaian kartu, tambahkan `stripecardscan` ke blok `dependencies` file [app/build.gradle](https://developer.android.com/studio/build/dependencies) Anda: #### Groovy ```groovy implementation 'com.stripe:stripecardscan:23.3.0' ``` ### Simpan detail pembayaran setelah pembayaran Sering digunakan oleh SaaS atau bisnis e-commerce yang memiliki pelanggan rutin. ### Impor sumber daya Stripe tambahan Impor Stripe paket `customer` dan `paymentmethod`. Gunakan paket ini untuk menyimpan informasi tentang pelanggan Anda. ### Impor sumber daya Stripe tambahan Impor model Stripe PaymentMethod dan Pelanggan. Gunakan model-model ini untuk menyimpan informasi tentang Pelanggan Anda. ### Buat pelanggan Stripe menyimpan kartu pada objek *Pelanggan* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments). Buat Pelanggan baru sebelum membuat PaymentIntent. Anda dapat juga menyimpan nama, email, alamat pengiriman, dan detail lain pada Pelanggan. ### Buat pelanggan Stripe menyimpan kartu pada objek [Akun](https://docs.stripe.com/api/v2/core/accounts/object.md) yang mewakili [pelanggan](https://docs.stripe.com/connect/account-capabilities.md?accounts-namespace=v2#customer). Buat Akun baru sebelum membuat PaymentIntent. Anda juga dapat menyimpan nama, email, alamat pengiriman, dan detail lainnya pada Akun. ### Tambahkan pelanggan ke PaymentIntent Teruskan identifikasi Pelanggan ke PaymentIntent dan atur `setup_future_usage` ke `off_session`. `setup_future_usage` memberi tahu Stripe cara Anda berencana menggunakan metode pembayaran—wilayah tertentu, seperti Eropa dan India, memiliki persyaratan seputar penggunaan kembali detail pembayaran. [Pelajari lebih lanjut](https://docs.stripe.com/payments/payment-intents.md#future-usage) tentang cara paling efektif untuk menerapkan `setup_future_usage`. Anda juga dapat melihat [daftar metode pembayaran yang didukung](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability). Setelah PaymentIntent berhasil, Stripe secara otomatis [melampirkan](https://docs.stripe.com/api/payment_methods/attach.md) detail pembayaran (dalam objek *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs)) kepada Pelanggan Anda. ### Tambahkan pelanggan ke PaymentIntent Teruskan ID Akun ke PaymentIntent dan atur `setup_future_usage` ke `off_session`. `setup_future_usage` memberi tahu Stripe cara Anda berencana menggunakan metode pembayaran—wilayah tertentu, seperti Eropa dan India, memiliki persyaratan seputar penggunaan kembali detail pembayaran. [Pelajari selengkapnya](https://docs.stripe.com/payments/payment-intents.md#future-usage) tentang cara paling efektif untuk menerapkan `setup_future_usage`. Anda juga dapat melihat [daftar metode pembayaran yang didukung](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability). Setelah PaymentIntent berhasil, Stripe secara otomatis [melampirkan](https://docs.stripe.com/api/payment_methods/attach.md) detail pembayaran (dalam objek *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs)) ke Akun yang dikonfigurasi pelanggan. ### Charge PaymentMethod tersimpan Saat Anda siap men-charge PaymentMethod kembali, buat PaymentIntent baru dengan Identifikasi Pelanggan, identifikasi PaymentMethod yang ingin Anda charge, serta atur tanda `off_session` dan `confirm` ke true. ### Kumpulkan alamat menggunakan Address Element Kumpulkan alamat pengiriman atau penagihan lokal dan internasional dari pelanggan Anda. ### Kumpulkan alamat menggunakan Address Element Kumpulkan alamat pengiriman atau penagihan lokal dan internasional dari pelanggan Anda. Jika menggunakan Address Element, Anda dapat menggunakan [Google Places SDK](https://developers.google.com/maps/documentation/places/android-sdk/overview) secara opsional untuk mengambil saran pengisian alamat otomatis. Untuk mengaktifkan saran pengisian otomatis, tambahkan `places` ke blok dependensi file [app/build.gradle](https://developer.android.com/studio/build/dependencies) Anda: #### Groovy ```groovy implementation 'com.google.android.libraries.places:places:2.6.0' ``` ### Instal pustaka Stripe Node Instal paket dan impor ke dalam kode Anda. Alternatifnya, jika Anda mulai dari nol dan memerlukan file package.json, unduh file proyek menggunakan tautan Unduh di editor kode. #### npm Instal pustaka: ```bash npm install --save stripe ``` #### GitHub Atau unduh kode pustaka stripe-node langsung [dari GitHub](https://github.com/stripe/stripe-node). ### Instal pustaka Stripe Ruby Instal ruby gem Stripe dan impor ke dalam kode Anda. Alternatifnya, jika Anda mulai dari nol dan memerlukan Gemfile, unduh file proyek menggunakan tautan di editor kode. #### Terminal Instal gem: ```bash gem install stripe ``` #### Bundler Tambahkan baris ini ke Gemfile Anda: ```bash gem 'stripe' ``` #### GitHub Atau unduh kode sumber modul stripe-ruby gem langsung [dari GitHub](https://github.com/stripe/stripe-ruby). ### Instal pustaka Java Stripe Tambahkan dependensi pada versi build Anda dan impor pustaka. Alternatifnya, jika Anda mulai dari nol dan memerlukan file pom.xml (untuk Maven), unduh file proyek menggunakan tautan Unduh di editor kode. #### Maven Tambahkan dependensi berikut pada POM Anda dan ganti {VERSION} dengan nomor versi yang ingin Anda gunakan. ```bash \ncom.stripe\nstripe-java\n{VERSION}\n ``` #### Gradle Tambahkan dependensi pada file build.gradle Anda dan ganti {VERSION} dengan nomor versi yang ingin Anda gunakan. ```bash implementation "com.stripe:stripe-java:{VERSION}" ``` #### GitHub Unduh JAR langsung [dari GitHub](https://github.com/stripe/stripe-java/releases/latest). ### Instal paket Stripe Python Instal paket Stripe dan impor ke dalam kode Anda. Alternatifnya, jika Anda mulai dari nol dan memerlukan file requirements.txt, unduh file proyek menggunakan tautan Unduh di editor kode. #### pip Instal paket melalui pip: ```bash pip3 install stripe ``` #### GitHub Unduh kode sumber pustaka stripe-python secara langsung [dari GitHub](https://github.com/stripe/stripe-python). ### Instal pustaka Stripe PHP Instal pustaka dengan composer dan inisialisasi dengan kunci API secret Anda. Alternatifnya, jika Anda mulai dari nol dan memerlukan file composer.json, unduh file ini menggunakan tautan Unduh di editor kode. #### Composer Instal pustaka: ```bash composer require stripe/stripe-php ``` #### GitHub Atau unduh kode pustaka stripe-php langsung [dari GitHub](https://github.com/stripe/stripe-php). ### Siapkan server Anda Tambahkan dependensi pada versi build Anda dan impor pustaka. Alternatifnya, jika Anda mulai dari nol dan memerlukan file go.mod, unduh file proyek menggunakan tautan Unduh di editor kode. #### Go Pastikan untuk menginisialisasi Modul Go: ```bash go get -u github.com/stripe/stripe-go/v85 ``` #### GitHub Atau unduh kode sumber modul stripe-go langsung [dari GitHub](https://github.com/stripe/stripe-go). ### Instal pustaka Stripe.net Instal paket dengan .NET atau NuGet. Alternatifnya, jika Anda mulai dari nol, unduh file yang berisi file .csproj yang telah dikonfigurasikan. #### dotnet Instal pustaka: ```bash dotnet add package Stripe.net ``` #### NuGet Instal pustaka: ```bash Install-Package Stripe.net ``` #### GitHub Atau unduh kode sumber pustaka Stripe.net langsung [dari GitHub](https://github.com/stripe/stripe-dotnet). ### Instal pustaka Stripe Instal paket dan impor ke dalam kode Anda. Alternatifnya, jika Anda mulai dari nol dan memerlukan file `package.json`, unduh file proyek menggunakan tautan di editor kode. Instal pustaka: ```bash npm install --save stripe @stripe/stripe-js next ``` ### Buat PaymentIntent Tambahkan endpoint pada server Anda yang membuat [PaymentIntent](https://docs.stripe.com/api/payment_intents.md). Sebuah PaymentIntent melacak siklus pembayaran pelanggan, memantau setiap upaya pembayaran yang gagal dan memastikan bahwa pelanggan hanya di-charge sekali. Kembalikan *client secret* (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)) PaymentIntent dalam tanggapan untuk menyelesaikan pembayaran pada client. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Konfigurasikan metode pembayaran Stripe mengaktifkan kartu dan metode pembayaran umum lainnya secara default dengan [metode pembayaran dinamis](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md). Anda dapat memperbarui dan mengonfigurasi metode pembayaran dari [Dashboard](https://dashboard.stripe.com/settings/payment_methods) tanpa perlu menulis kode. Stripe memfilter metode pembayaran berdasarkan kelayakan dan preferensi metode pembayaran, kemudian memesan dan menampilkannya berdasarkan probabilitas berdasarkan faktor-faktor termasuk jumlah, mata uang, dan lokasi pembeli. ### Instal SDK SDK Android Stripe adalah [sumber terbuka](https://github.com/stripe/stripe-android) dan [didokumentasikan lengkap](https://stripe.dev/stripe-android/) serta kompatibel dengan perangkat yang menjalankan Android 5.0 (API level 21) dan yang lebih baru. Untuk menginstal SDK, tambahkan `stripe-android` ke blok dependensi file `build.gradle` Anda: #### Groovy ```groovy implementation 'com.stripe:stripe-android:23.3.0' ``` > Untuk detail mengenai rilis SDK terbaru dan versi sebelumnya, lihat [halaman Rilis](https://github.com/stripe/stripe-android/releases) di GitHub. ### Siapkan SDK Konfigurasikan SDK Stripe dengan [kunci API yang dapat dipublikasikan](https://docs.stripe.com/keys.md#obtain-api-keys) Stripe Anda. Pengodean keras kunci API yang dapat dipublikasikan di SDK hanya untuk demonstrasi. Dalam aplikasi produksi, Anda harus mengambil kunci API dari server. ### Ambil PaymentIntent Buat permintaan ke server Anda untuk PaymentIntent segera setelah tampilan dimuat. Simpan referensi ke *client secret* (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)) PaymentIntent yang dikembalikan oleh server; Payment Sheet menggunakan rahasia ini untuk menyelesaikan pembayaran nanti. ### Konfigurasikan dan sajikan Payment Sheet Buat instance `PaymentSheet` menggunakan client secret yang diambil sebelumnya, dan sajikan dari pengontrol tampilan Anda. Gunakan struktur `PaymentSheet.Configuration` untuk [menyesuaikan](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html) Payment Sheet. ### Tangani hasil pembayaran Gunakan blok penyelesaian untuk menangani hasil pembayaran. Jika pembayaran gagal dengan [kesalahan](https://docs.stripe.com/error-codes.md), tampilkan pesan yang sesuai kepada pelanggan Anda sehingga pelanggan dapat mengambil tindakan dan mencoba lagi. Jika tidak terjadi kesalahan, sampaikan kepada pelanggan bahwa pembayaran berhasil. ### Buat pembayaran percobaan #### iOS Untuk memverifikasi bahwa integrasi Anda berfungsi, lakukan uji pembayaran menggunakan [uji detail pembayaran](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios#ios-test-the-integration). #### Android Untuk memverifikasi bahwa integrasi Anda berfungsi, lakukan uji pembayaran menggunakan [uji detail pembayaran](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=android#android-test-the-integration). ### Lihat pembayaran Anda di Dashboard Buka [Dashboard Stripe](https://dashboard.stripe.com/test/payments) untuk melihat pembayaran percobaan Anda. ## Terima pembayaran dan tingkatkan integrasi Anda Anda siap menerima pembayaran dengan Stripe. Lanjutkan dengan langkah-langkah di bawah untuk menambahkan fitur-fitur lainnya. ### Otomatiskan pemungutan pajak Hitung dan pungut jumlah pajak yang tepat untuk transaksi Stripe Anda. Sebelum menggunakan Stripe Tax, Anda perlu mengaktifkannya di [Dashboard](https://dashboard.stripe.com/tax). Pelajari selengkapnya tentang [Stripe Tax](https://docs.stripe.com/tax.md) dan [cara menambahkannya ke integrasi Payments Anda](https://docs.stripe.com/tax/custom.md). ### Gunakan Stripe Tax API untuk menghitung pajak Gunakan [Stripe Tax API](https://docs.stripe.com/api/tax/calculations/create.md) untuk menghitung pajak atas transaksi. Berikan `currency`, `customer_details`, dan `line_items` pesanan di isi permintaan. Gunakan atribut `tax_amount_exclusive` dari Perhitungan Pajak yang dihasilkan untuk menambahkan pajak eksklusif ke total pesanan. ### Catat Transaksi Pajak setelah Pembayaran berhasil Menautkan perhitungan pajak ke PaymentIntent menggunakan `kait[input][pajak][perhitungan]`. Halaman ini mencatat pajak yang dikumpulkan di akun Stripe Anda yang nantinya dapat Anda ekspor untuk tujuan akuntansi, dan memicu [tindakan Stripe](https://docs.stripe.com/tax/payment-intent.md#automatic-actions) lainnya. ### Izinkan metode pembayaran tertunda Beberapa metode pembayaran tidak dapat menjamin bahwa Anda akan menerima dana dari pelanggan di akhir proses checkout karena perlu waktu untuk menyelesaikannya (misalnya, sebagian besar debit bank, seperti SEPA atau ACH) atau mengharuskan tindakan pelanggan untuk menyelesaikannya (misalnya, OXXO, Konbini, Boleto). Gunakan tanda ini untuk mengaktifkan metode pembayaran yang tertunda. Jika Anda mengaktifkan fitur ini, pastikan integrasi server Anda mendengarkan [webhook](https://docs.stripe.com/payments/payment-methods.md#payment-notification) untuk notifikasi mengenai berhasil atau tidaknya pembayaran. ### Tambahkan dukungan Apple Pay Untuk mengaktifkan Apple Pay, berikan [Identifikasi Merchant Apple Pay](https://support.stripe.com/questions/enable-apple-pay-on-your-stripe-account) dan [kode negara](https://dashboard.stripe.com/settings/account) akun Stripe Anda. ### Tambahkan dukungan Google Pay Untuk menggunakan Google Pay, aktifkan Google Pay API terlebih dahulu di AndroidManifest.xml Anda. Aktifkan Google Pay dengan meneruskan objek [PaymentSheet.GooglePayConfiguration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-google-pay-configuration/index.html) bersama lingkungan Google Pay (produksi atau percobaan) dan [kode negara bisnis Anda](https://dashboard.stripe.com/settings/account) ketika menginisialisasi [PaymentSheet. Konfigurasi](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-configuration/index.html). ### Sesuaikan warna tombol utama Pertimbangkan untuk menggunakan warna custom untuk tombol utama yang lebih cocok dengan identitas visual brand atau aplikasi Anda. ### Aktifkan pemindaian kartu Pemindaian kartu dapat membantu meningkatkan rasio konversi Anda dengan menghilangkan hambatan entri kartu manual. Untuk mengaktifkan pemindaian kartu, atur `NSCameraUsageDescription` di `Info.plist` aplikasi Anda, dan berikan alasan untuk mengakses kamera (misalnya, “Untuk memindai kartu”). > Pemindaian kartu hanya didukung di perangkat yang menjalankan iOS 13 atau lebih tinggi. ### Aktifkan pemindaian kartu Pemindaian kartu dapat membantu meningkatkan rasio konversi Anda dengan menghilangkan hambatan entri kartu manual. Untuk mengaktifkan pemindaian kartu, tambahkan `stripecardscan` ke blok `dependencies` file [app/build.gradle](https://developer.android.com/studio/build/dependencies) Anda: #### Groovy ```groovy implementation 'com.stripe:stripecardscan:23.3.0' ``` ### Simpan detail pembayaran setelah pembayaran Sering digunakan oleh SaaS atau bisnis e-commerce yang memiliki pelanggan rutin. ### Impor sumber daya Stripe tambahan Impor Stripe paket `customer` dan `paymentmethod`. Gunakan paket ini untuk menyimpan informasi tentang pelanggan Anda. ### Impor sumber daya Stripe tambahan Impor model Stripe PaymentMethod dan Pelanggan. Gunakan model-model ini untuk menyimpan informasi tentang Pelanggan Anda. ### Buat pelanggan Stripe menyimpan kartu pada objek *Pelanggan* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments). Buat Pelanggan baru sebelum membuat PaymentIntent. Anda dapat juga menyimpan nama, email, alamat pengiriman, dan detail lain pada Pelanggan. ### Buat pelanggan Stripe menyimpan kartu pada objek [Akun](https://docs.stripe.com/api/v2/core/accounts/object.md) yang mewakili [pelanggan](https://docs.stripe.com/connect/account-capabilities.md?accounts-namespace=v2#customer). Buat Akun baru sebelum membuat PaymentIntent. Anda juga dapat menyimpan nama, email, alamat pengiriman, dan detail lainnya pada Akun. ### Tambahkan pelanggan ke PaymentIntent Teruskan identifikasi Pelanggan ke PaymentIntent dan atur `setup_future_usage` ke `off_session`. `setup_future_usage` memberi tahu Stripe cara Anda berencana menggunakan metode pembayaran—wilayah tertentu, seperti Eropa dan India, memiliki persyaratan seputar penggunaan kembali detail pembayaran. [Pelajari lebih lanjut](https://docs.stripe.com/payments/payment-intents.md#future-usage) tentang cara paling efektif untuk menerapkan `setup_future_usage`. Anda juga dapat melihat [daftar metode pembayaran yang didukung](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability). Setelah PaymentIntent berhasil, Stripe secara otomatis [melampirkan](https://docs.stripe.com/api/payment_methods/attach.md) detail pembayaran (dalam objek *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs)) kepada Pelanggan Anda. ### Tambahkan pelanggan ke PaymentIntent Teruskan ID Akun ke PaymentIntent dan atur `setup_future_usage` ke `off_session`. `setup_future_usage` memberi tahu Stripe cara Anda berencana menggunakan metode pembayaran—wilayah tertentu, seperti Eropa dan India, memiliki persyaratan seputar penggunaan kembali detail pembayaran. [Pelajari selengkapnya](https://docs.stripe.com/payments/payment-intents.md#future-usage) tentang cara paling efektif untuk menerapkan `setup_future_usage`. Anda juga dapat melihat [daftar metode pembayaran yang didukung](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability). Setelah PaymentIntent berhasil, Stripe secara otomatis [melampirkan](https://docs.stripe.com/api/payment_methods/attach.md) detail pembayaran (dalam objek *PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs)) ke Akun yang dikonfigurasi pelanggan. ### Charge PaymentMethod tersimpan Saat Anda siap men-charge PaymentMethod kembali, buat PaymentIntent baru dengan Identifikasi Pelanggan, identifikasi PaymentMethod yang ingin Anda charge, serta atur tanda `off_session` dan `confirm` ke true. ### Kumpulkan alamat menggunakan Address Element Kumpulkan alamat pengiriman atau penagihan lokal dan internasional dari pelanggan Anda. ### Kumpulkan alamat menggunakan Address Element Kumpulkan alamat pengiriman atau penagihan lokal dan internasional dari pelanggan Anda. Jika menggunakan Address Element, Anda dapat menggunakan [Google Places SDK](https://developers.google.com/maps/documentation/places/android-sdk/overview) secara opsional untuk mengambil saran pengisian alamat otomatis. Untuk mengaktifkan saran pengisian otomatis, tambahkan `places` ke blok dependensi file [app/build.gradle](https://developer.android.com/studio/build/dependencies) Anda: #### Groovy ```groovy implementation 'com.google.android.libraries.places:places:2.6.0' ``` ## Langkah berikutnya #### Web #### [Kumpulkan detail alamat tagihan](https://docs.stripe.com/elements/address-element.md) Secara default, Payment Element hanya mengumpulkan detail alamat tagihan yang diperlukan. Untuk mengumpulkan alamat tagihan lengkap pelanggan (misalnya, untuk menghitung pajak barang dan layanan digital) atau alamat pengiriman, gunakan Address Element. #### iOS #### Android #### [Payout](https://docs.stripe.com/payouts.md) Pelajari cara memindahkan dana dari akun Stripe ke rekening bank Anda. #### [Pengembalian dana](https://docs.stripe.com/refunds.md) Tangani permintaan pengembalian dana dengan menggunakan API Stripe atau Dashboard. #### [Pemenuhan](https://docs.stripe.com/webhooks/quickstart.md) Buat tujuan kejadian untuk mengirim kejadian ke endpoint webhook Anda guna memenuhi pesanan setelah pembayaran berhasil, dan untuk menangani kejadian penting lainnya.