Lewati ke konten
Buat akun atau Masuk
Logo Dokumen Stripe
/
Tanya AI
Buat akunMasuk
Mulai
Pembayaran
Pendapatan
Platform dan situs belanja online
Manajemen uang
Sumber daya pengembang
API & SDKBantuan
Gambaran UmumTerima pembayaranUpgrade integrasi Anda
Pembayaran online
Gambaran umumTemukan contoh penggunaan Anda
Gunakan Payment Links
Gunakan halaman checkout bawaan
Buat integrasi kustom dengan Elements
Bangun integrasi dalam aplikasi
Gunakan Managed Payments
Pembayaran rutin
Pembayaran di tempat
Terminal
Metode Pembayaran
Tambahkan metode pembayaran
Kelola metode pembayaran
Checkout lebih cepat dengan Link
Operasi pembayaran
Analitik
Saldo dan waktu pelunasan
Kepatuhan dan keamanan
Mata uang
Penolakan
Sengketa
Pencegahan penipuan
Perlindungan penipuan Radar
Payout
ResiPengembalian dana dan pembatalan
Integrasi lanjutan
Alur pembayaran custom
    Gambaran umum
    Pembayaran untuk pelanggan yang ada
    Buat alur checkout dua langkah
    Kumpulkan detail pembayaran sebelum membuat Intent
    Finalisasikan pembayaran di server
    Ambil pesanan pos dan telepon (MOTO)
    Kartu AS dan Kanada
    Teruskan detail kartu ke endpoint API pihak ketiga
    Mata anggaran pembayaran
    Metadata industri
Akuisisi fleksibel
Pembayaran di Luar Sesi
Orkestrasi multi-pemroses
Di luar pembayaran
Dirikan perusahaan Anda
Kripto
Perdagangan agen
Pembayaran mesin
Financial Connections
Climate
Verifikasikan identitas
Amerika Serikat
Bahasa Indonesia
BerandaPembayaranCustom payment flows

Collect payment details before creating an Intent

Build an integration where you can render the Payment Element prior to creating a PaymentIntent or SetupIntent.

Bandingkan referensi Pelanggan v1 dan Akun v2

Jika platform Connect Anda menggunakan Akun yang dikonfigurasi pelanggan, gunakan panduan kami untuk mengganti referensi Customer dan kejadian dalam kode Anda dengan referensi Accounts v2 API yang setara.

The Payment Element allows you to accept multiple payment methods using a single integration. In this integration, learn how to build a custom payment flow where you render the Payment Element, create the PaymentIntent, and confirm the payment from the buyer’s browser. If you prefer to confirm the payment from the server instead, see Finalize payments on the server.

Siapkan Stripe
Sisi server

Pertama, buat akun Stripe atau masuk.

Gunakan pustaka resmi kami untuk mengakses API Stripe dari aplikasi Anda:

Command Line
Ruby
Python
PHP
Java
Node.js
Go
.NET
No results
# Available as a gem sudo gem install stripe
Gemfile
Ruby
Python
PHP
Java
Node.js
Go
.NET
No results
# If you use bundler, you can add this line to your Gemfile gem 'stripe'

Enable payment methods

Peringatan

This integration path doesn’t support BLIK or pre-authorized debits that use the Automated Clearing Settlement System (ACSS). You also can’t use customer_balance with dynamic payment methods when the deferred intent is created client-side. The client-side deferred-intent flow can’t include a Customer, and customer_balance requires a Customer on the PaymentIntent, so it’s excluded to avoid errors. To use customer_balance, create the PaymentIntent server-side with a Customer and return its client_secret to the client.

Lihat pengaturan metode pembayaran dan aktifkan metode pembayaran yang ingin Anda dukung. Anda membutuhkan setidaknya satu metode pembayaran yang diaktifkan untuk membuat PaymentIntent.

Secara default, Stripe mengaktifkan kartu dan metode pembayaran umum lainnya yang dapat membantu menjangkau lebih banyak pelanggan, tetapi sebaiknya aktifkan metode pembayaran tambahan yang relevan untuk bisnis dan pelanggan Anda. Lihat Dukungan metode pembayaran untuk dukungan produk dan metode pembayaran, dan halaman skema biaya kami untuk mengetahui biayanya.

Kumpulkan rincian pembayaran
Sisi klien

Use the Payment Element to securely send payment information collected in an iFrame to Stripe over an HTTPS connection.

Conflicting iFrames

Avoid placing the Payment Element within another iframe because it conflicts with payment methods that require redirecting to another page for payment confirmation.

Your checkout page URL must start with https:// rather than http:// for your integration to work. You can test your integration without using HTTPS, but remember to enable it when you’re ready to accept live payments.

Siapkan Stripe.js

Payment Element tersedia secara otomatis sebagai fitur Stripe.js. Sertakan skrip Stripe.js di halaman checkout Anda dengan menambahkannya ke head file HTML Anda. Selalu muat Stripe.js langsung dari js.stripe.com agar tetap sesuai dengan PCI. Jangan sertakan skrip dalam bundel atau simpan sendiri salinannya.

checkout.html
<head> <title>Checkout</title> <script src="https://js.stripe.com/clover/stripe.js"></script> </head>

Buat instance Stripe dengan JavaScript berikut di halaman checkout Anda:

checkout.js
// Set your publishable key: remember to change this to your live publishable key in production // See your keys here: https://dashboard.stripe.com/apikeys const stripe = Stripe(
'pk_test_TYooMQauvdEDq54NiTphI7jx'
);

Tambahkan Payment Element ke halaman pembayaran Anda

Payment Element membutuhkan tempat tinggal di halaman checkout Anda. Buat simpul DOM kosong (kontainer) dengan ID unik di formulir pembayaran Anda:

checkout.html
<form id="payment-form"> <div id="payment-element"> <!-- Elements will create form elements here --> </div> <button id="submit">Submit</button> <div id="error-message"> <!-- Display error message to your customers here --> </div> </form>

After your form loads, create an Elements instance with the mode, amount, and currency. These values determine which payment methods the Element presents to your customer.

Kemudian, buat instance Payment Element dan pasang ke simpul DOM penampung.

checkout.js
const options = { mode: 'payment', amount: 1099, currency: 'usd', // Fully customizable with appearance API. appearance: {/*...*/}, }; // Set up Stripe.js and Elements to use in checkout form const elements = stripe.elements(options); // Create and mount the Payment Element const paymentElementOptions = { layout: 'accordion'}; const paymentElement = elements.create('payment', paymentElementOptions); paymentElement.mount('#payment-element');

Payment Element merender formulir dinamis yang memungkinkan pelanggan Anda memilih metode pembayaran. Formulir secara otomatis mengumpulkan semua detail pembayaran yang diperlukan untuk metode pembayaran yang dipilih oleh pelanggan.

You can customize the Payment Element to match the design of your site by passing the appearance object into options when creating the Elements provider.

Kumpulkan alamat

Secara default, Payment Element hanya mengumpulkan detail alamat penagihan yang diperlukan. Beberapa perilaku, seperti menghitung pajak atau memasukkan detail pengiriman, memerlukan alamat lengkap pelanggan Anda. Anda dapat melakukannya:

  • Gunakan Address Element untuk memanfaatkan fitur pelengkapan otomatis dan pelokalan untuk mengumpulkan alamat lengkap pelanggan Anda. Hal ini membantu memastikan penghitungan pajak yang paling akurat.
  • Kumpulkan detail alamat menggunakan formulir khusus Anda sendiri.

OpsionalMenyesuaikan tata letak
Sisi klien

Anda dapat menyesuaikan tata letak Payment Element (akordeon atau tab) agar sesuai dengan antarmuka checkout Anda. Untuk informasi selengkapnya tentang setiap properti, lihat elements.create.

Anda dapat mulai menggunakan fitur tata letak dengan meneruskan type tata letak dan properti opsional lainnya saat membuat Payment Element:

const paymentElement = elements.create('payment', { layout: { type: 'accordion', defaultCollapsed: false, radios: true, spacedAccordionItems: false } });

Gambar berikut adalah Payment Element yang sama yang ditampilkan menggunakan konfigurasi tata letak yang berbeda:

Tiga pengalaman formulir checkout

Tata letak Payment Element

OpsionalMenyesuaikan penampilan
Sisi klien

Setelah menambahkan Payment Element ke halaman, Anda dapat menyesuaikan tampilannya agar sesuai dengan desain. Untuk mempelajari selengkapnya cara menyesuaikan Payment Element, lihat Elements Appearance API.

Sesuaikan Payment Element

Sesuaikan Payment Element

OpsionalMenyimpan dan mengambil metode pembayaran pelanggan

Anda dapat mengonfigurasi Payment Element untuk menyimpan metode pembayaran pelanggan untuk digunakan di masa mendatang. Bagian ini menunjukkan cara mengintegrasikan fitur metode pembayaran tersimpan, yang memungkinkan Payment Element untuk:

  • Meminta persetujuan pembeli untuk menyimpan metode pembayaran
  • Menyimpan metode pembayaran saat pembeli memberikan persetujuan
  • Menampilkan metode pembayaran yang tersimpan kepada pembeli untuk pembelian di masa mendatang
  • Secara otomatis memperbarui kartu yang hilang atau kedaluwarsa saat pembeli menggantinya
Kotak centang Payment Element dan metode pembayaran tersimpan

Simpan metode pembayaran.

Payment Element dengan Metode pembayaran tersimpan dipilih

Gunakan kembali metode pembayaran yang disimpan sebelumnya.

Mengaktifkan penyimpanan metode pembayaran di Payment Element

Buat CustomerSession di server Anda dengan memberikan Customer ID serta mengaktifkan komponen payment_element untuk sesi Anda. Konfigurasikan fitur metode pembayaran tersimpan yang ingin Anda aktifkan. Misalnya, mengaktifkan payment_method_save menampilkan kotak centang yang memungkinkan pelanggan menyimpan detail pembayaran untuk digunakan di masa mendatang.

Anda dapat menentukan setup_future_usage pada PaymentIntent atau Sesi Checkout untuk mengesampingkan perilaku default penyimpanan metode pembayaran. Hal ini memastikan bahwa Anda secara otomatis menyimpan metode pembayaran untuk digunakan di masa mendatang, sekalipun pelanggan tidak secara eksplisit memilih untuk menyimpannya.

Peringatan

Mengizinkan pembeli menghapus metode pembayaran yang tersimpan dengan mengaktifkan payment_method_remove berdampak pada langganan yang tergantung pada metode pembayaran tersebut. Menghapus metode pembayaran akan melepaskan PaymentMethod dari Pelanggan tersebut.

server.rb
Ruby
Python
PHP
Node.js
Java
Go
.NET
No results
# Set your secret key. Remember to switch to your live secret key in production. # See your keys here: https://dashboard.stripe.com/apikeys Stripe.api_key =
'sk_test_BQokikJOvBiI2HlWgH4olfQ2'
post '/create-customer-session' do customer_session = Stripe::CustomerSession.create({ customer:
{{CUSTOMER_ID}}
, components: { payment_element: { enabled: true, features: { payment_method_redisplay: 'enabled', payment_method_save: 'enabled', payment_method_save_usage: 'off_session', payment_method_remove: 'enabled', }, }, }, }) { customer_session_client_secret: customer_session.client_secret }.to_json end

Instance Elements Anda menggunakan client secret untuk mengakses metode pembayaran yang disimpan pelanggan tersebut. Tangani kesalahan dengan benar saat Anda membuat CustomerSession. Jika terjadi kesalahan, Anda tidak perlu memberikan client secret CustomerSession ke instance Elements, karena bersifat opsional.

Buatlah instance Elements menggunakan Client Secret CustomerSession. Kemudian, gunakan instance Elements untuk membuat Payment Element.

checkout.js
// Create the CustomerSession and obtain its clientSecret const res = await fetch("/create-customer-session", { method: "POST" }); const { customer_session_client_secret: customerSessionClientSecret } = await res.json(); const elementsOptions = { mode: 'payment', amount: 1099, currency: 'usd', customerSessionClientSecret, // Fully customizable with appearance API. appearance: {/*...*/}, }; // Set up Stripe.js and Elements to use in checkout form, passing the client secret // and CustomerSession's client secret obtained in a previous step const elements = stripe.elements(elementsOptions); // Create and mount the Payment Element const paymentElementOptions = { layout: 'accordion'}; const paymentElement = elements.create('payment', paymentElementOptions); paymentElement.mount('#payment-element');

Saat mengonfirmasi PaymentIntent, Stripe.js secara otomatis mengontrol pengaturan setup_future_usage pada PaymentIntent dan allow_redisplay pada PaymentMethod, tergantung pada jika pelanggan mencentang kotak untuk menyimpan detail pembayaran.

Terapkan pengumpulan kembali CVC

Secara opsional, tentukan require_cvc_recollection ketika membuat PaymentIntent dan ketika membuat Elements untuk memberlakukan pengumpulan kembali CVC saat pelanggan membayar dengan kartu.

Mendeteksi pemilihan metode pembayaran yang disimpan

Untuk mengontrol konten dinamis saat metode pembayaran tersimpan dipilih, dengarkan peristiwa change elemen pembayaran, yang diisi dengan metode pembayaran yang dipilih.

checkout.js
paymentElement.on('change', function(event) { if (event.value.payment_method) { // Control dynamic content if a saved payment method is selected } })

OpsionalPerbarui detail pembayaran secara dinamis
Sisi klien

Saat pelanggan melakukan tindakan yang mengubah detail pembayaran (misalnya, menerapkan kode diskon), perbarui instance Element untuk mencerminkan nilai baru. Beberapa metode pembayaran, seperti Apple Pay dan Google Pay, menampilkan jumlah di UI, jadi pastikan jumlahnya selalu akurat dan terbaru.

checkout.js
async function handleDiscountCode(code) { // On the server, validate that the discount code is valid and return the new amount const {newAmount} = await fetch("/apply-discount", { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({code}), }); elements.update({amount: newAmount}); }

OpsionalAdditional Elements options
Sisi client

The Elements object accepts additional options that influence payment collection. Based on the options provided, the Payment Element displays available payment methods from those you’ve enabled. Learn more about payment method support.

PropertiTipeKeteranganHarus diisi
mode
  • payment
  • setup
  • subscription
Menunjukkan apakah Payment Element digunakan dengan PaymentIntent, SetupIntent, atau Subscription.Ya
currencystringMata uang dari jumlah yang akan ditagihkan kepada pelanggan.Ya
amountnumberThe amount to charge the customer, shown in Apple Pay, Google Pay, or BNPL UIs.Untuk mode payment dan subscription
setupFutureUsage
  • off_session
  • on_session
Indicates that you intend to make future payments with the payment details collected by the Payment Element. Tidak
captureMethod
  • automatic
  • automatic_async
  • manual
Mengontrol kapan harus mengambil dana dari rekening pelanggan.Tidak
onBehalfOfstringConnect only. The Stripe account ID, which is the business of record. See use cases to determine if this option is relevant for your integration.Tidak
paymentMethodTypesstring[]A list of payment method types to render. You can omit this attribute to manage your payment methods in the Stripe Dashboard.Tidak
paymentMethodConfigurationstringThe payment method configuration to use when managing your payment methods in the Stripe Dashboard. If not specified, your default configuration is used.Tidak
paymentMethodCreationmanualAllows PaymentMethods to be created from the Elements instance using stripe.createPaymentMethod.Tidak
paymentMethodOptions{us_bank_account: {verification_method: string}}Verification options for the us_bank_account payment method. Accepts the same verification methods as Payment Intents.Tidak
paymentMethodOptions{card: {installments: {enabled: boolean}}}Allows manually enabling the card installment plan selection UI if applicable when you aren’t managing your payment methods in the Stripe Dashboard. You must set mode='payment' and explicitly specify paymentMethodTypes. Otherwise an error is raised. Incompatible with paymentMethodCreation='manual'.Tidak

OpsionalBuat ConfirmationToken

If you want to build a multi-page checkout or collect payment method details before running additional validations, see Build a two-step checkout flow. With this flow, you create a ConfirmationToken on the client to collect payment details and then use it to create a PaymentIntent on the server.

Buat PaymentIntent
Sisi server

Jalankan logika bisnis custom segera sebelum konfirmasi pembayaran

Navigate to step 5 in the finalize payments guide to run your custom business logic immediately before payment confirmation. Otherwise, follow the steps below for a simpler integration, which uses stripe.confirmPayment on the client to both confirm the payment and handle any next actions.

When the customer submits your payment form, create a PaymentIntent on your server with an amount and currency enabled.

Return the client secret value to your client for Stripe.js to use to complete the payment process.

The following example includes commented code to illustrate the optional Tax Calculation.

main.rb
Ruby
Python
PHP
Node.js
Java
Buka
.NET
No results
require 'stripe' Stripe.api_key =
'sk_test_BQokikJOvBiI2HlWgH4olfQ2'
post '/create-intent' do # If you used a Tax Calculation, optionally recalculate taxes # confirmation_token = Stripe::ConfirmationToken.retrieve(params[:confirmation_token_id]) # summarized_payment_details = summarize_payment_details(confirmation_token) intent = Stripe::PaymentIntent.create({ # To allow saving and retrieving payment methods, provide the Customer ID. customer: customer.id, # If you used a Tax Calculation, use its `amount_total`. # amount: summarized_payment_details.amount_total, amount: 1099, currency: 'usd', # Specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. automatic_payment_methods: {enabled: true}, # If you used a Tax Calculation, link it to the PaymentIntent to make sure any transitions accurately reflect the tax. # hooks: { # inputs: { # tax: { # calculation: tax_calculation.id # } # } #} }, #{ # stripe_version: '2025-09-30.preview' } ) {client_secret: intent.client_secret}.to_json end

Setting `payment_method_options` for `us_bank_account` payments

Setting payment_method_options at this step won’t affect collected payment methods. Instead, configure payment methods in the Dashboard.

Serahkan pembayaran ke Stripe
Sisi client

Use stripe.confirmPayment to complete the payment using details from the Payment Element.

Provide a return_url to this function to indicate where Stripe should redirect the user after they complete the payment. Your user might be initially redirected to an intermediate site, like a bank authorization page, before being redirected to the return_url. Card payments immediately redirect to the return_url when a payment is successful.

If you don’t want to redirect for card payments after payment completion, you can set redirect to if_required. This only redirects customers that check out with redirect-based payment methods.

checkout.js
const form = document.getElementById('payment-form'); const submitBtn = document.getElementById('submit'); const handleError = (error) => { const messageContainer = document.querySelector('#error-message'); messageContainer.textContent = error.message; submitBtn.disabled = false; } form.addEventListener('submit', async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); // Prevent multiple form submissions if (submitBtn.disabled) { return; } // Disable form submission while loading submitBtn.disabled = true; // Trigger form validation and wallet collection const {error: submitError} = await elements.submit(); if (submitError) { handleError(submitError); return; } // Create the PaymentIntent and obtain clientSecret const res = await fetch("/create-intent", { method: "POST", }); const {client_secret: clientSecret} = await res.json(); // Confirm the PaymentIntent using the details collected by the Payment Element const {error} = await stripe.confirmPayment({ elements, clientSecret, confirmParams: { return_url: 'https://example.com/order/123/complete', }, }); if (error) { // This point is only reached if there's an immediate error when // confirming the payment. Show the error to your customer (for example, payment details incomplete) handleError(error); } else { // Your customer is redirected to your `return_url`. For some payment // methods like iDEAL, your customer is redirected to an intermediate // site first to authorize the payment, then redirected to the `return_url`. } });

OpsionalTangani kejadian pascapembayaran

Stripe mengirim kejadian payment_intent.succeeded ketika selesai pembayaran. Gunakan Dashboard, webhook custom, atau solusi mitra untuk menerima kejadian ini dan menjalankan tindakan, seperti mengirim email konfirmasi pesanan kepada pelanggan Anda, mencatat penjualan di database, atau memulai alur kerja pengiriman.

Mendengarkan kejadian ini daripada menunggu callback dari client. Di client, pelanggan dapat menutup jendela browser atau keluar dari aplikasi sebelum callback mengeksekusi, dan client jahat dapat memanipulasi respons. Penyiapan integrasi untuk mendengarkan kejadian asinkron juga membantu Anda menerima lebih banyak metode pembayaran di masa mendatang. Pelajari tentang perbedaan antara semua metode pembayaran yang didukung.

  • Tangani event secara manual di Dashboard

    Gunakan Dashboard untuk Melihat pembayaran uji coba Anda di Dashboard, mengirim tanda terima email, menangani pencairan dana, atau mencoba kembali pembayaran yang gagal.

  • Buat webhook kustom

    Build a custom webhook handler to listen for events and build custom asynchronous payment flows. Test and debug your webhook integration locally with the Stripe CLI.

  • Integrasikan aplikasi siap pakai

    Tangani event bisnis umum, seperti otomatisasi atau pemasaran dan penjualan, dengan mengintegrasikan aplikasi mitra.

Lihat juga

  • Design an integration
Apakah halaman ini membantu?
YaTidak
  • Butuh bantuan? Hubungi Tim CS.
  • Lihat log perubahan kami.
  • Ada pertanyaan? Hubungi Bagian Penjualan.
  • LLM? Baca llms.txt.
  • Dijalankan oleh Markdoc