### Install svelte-stripe and Dependencies
Source: https://github.com/joshnuss/svelte-stripe/blob/main/src/routes/+page.md
Install the necessary Stripe and svelte-stripe packages as development dependencies.
```bash
pnpm install -D stripe @stripe/stripe-js svelte-stripe
```
--------------------------------
### EmbeddedCheckout Component Setup
Source: https://context7.com/joshnuss/svelte-stripe/llms.txt
Set up the EmbeddedCheckout component for a complete Stripe-hosted checkout experience. Requires server-side session creation and client-side Stripe initialization.
```svelte
{#if stripe && data.clientSecret}
{/if}
```
--------------------------------
### Address Component for Billing and Shipping
Source: https://context7.com/joshnuss/svelte-stripe/llms.txt
Collect address information using the Address component, which includes built-in autocomplete and validation. This example shows both billing and shipping address collection.
```svelte
{#if stripe && clientSecret}
{/if}
```
--------------------------------
### Run Development Server
Source: https://github.com/joshnuss/svelte-stripe/blob/main/README.md
Use this command to run the development server and visit the local instance of the application.
```bash
pnpm dev
```
--------------------------------
### Initialize Stripe and Elements in Svelte
Source: https://github.com/joshnuss/svelte-stripe/blob/main/src/routes/+page.md
Load Stripe using your public key and wrap your Stripe components with the Elements provider. Ensure the public key is loaded from environment variables.
```svelte
```
--------------------------------
### Initialize Stripe Elements Context
Source: https://context7.com/joshnuss/svelte-stripe/llms.txt
The Elements wrapper component initializes Stripe and provides context to child Stripe components. It requires fetching a client secret from your server.
```svelte
{#if stripe && clientSecret}
{/if}
```
--------------------------------
### Forward Webhooks to Localhost with Stripe CLI
Source: https://github.com/joshnuss/svelte-stripe/blob/main/src/routes/+page.md
Use Stripe CLI to forward incoming webhooks to your local development server. This is useful for testing webhook functionality during development.
```bash
stripe listen --forward-to localhost:5173/stripe/webhooks
```
--------------------------------
### Create Payment Intent Server-Side
Source: https://github.com/joshnuss/svelte-stripe/blob/main/src/routes/+page.md
Create a server endpoint to generate a payment intent with specified amount, currency, and payment method types. This must be done server-side to prevent tampering.
```javascript
import Stripe from 'stripe'
import { SECRET_STRIPE_KEY } from '$env/static/private'
// initialize Stripe
const stripe = new Stripe(SECRET_STRIPE_KEY)
// handle POST /create-payment-intent
export async function POST() {
// create the payment intent
const paymentIntent = await stripe.paymentIntents.create({
amount: 2000,
// note, for some EU-only payment methods it must be EUR
currency: 'usd',
// specify what payment methods are allowed
// can be card, sepa_debit, ideal, etc...
payment_method_types: ['card']
})
// return the clientSecret to the client
return {
body: {
clientSecret: paymentIntent.client_secret
}
}
}
```
--------------------------------
### Create Server-Side Payment Intent
Source: https://context7.com/joshnuss/svelte-stripe/llms.txt
Use this endpoint to securely create payment intents on the server. It specifies the amount, currency, and enables automatic payment methods.
```typescript
// src/routes/api/payment-intent/+server.ts
import { json } from '@sveltejs/kit'
import Stripe from 'stripe'
import { SECRET_STRIPE_KEY } from '$env/static/private'
const stripe = new Stripe(SECRET_STRIPE_KEY)
export async function POST() {
const paymentIntent = await stripe.paymentIntents.create({
amount: 2000, // Amount in cents ($20.00)
currency: 'usd',
automatic_payment_methods: {
enabled: true
}
})
return json({
clientSecret: paymentIntent.client_secret
})
}
```
--------------------------------
### Handle Stripe Webhooks in SvelteKit
Source: https://github.com/joshnuss/svelte-stripe/blob/main/src/routes/+page.md
Implement a POST endpoint in SvelteKit to receive and verify Stripe webhook events. Ensure the webhook signature is validated before processing event data. This is crucial for security to confirm the data originates from Stripe.
```javascript
// in src/routes/stripe/webhooks/+server.js
import Stripe from 'stripe'
import { error, json } from '@sveltejs/kit'
import { env } from '$env/dynamic/private'
// init api client
const stripe = new Stripe(env.SECRET_STRIPE_KEY)
// endpoint to handle incoming webhooks
export async function POST({ request }) {
// extract body
const body = await request.text()
// get the signature from the header
const signature = request.headers.get('stripe-signature')
// var to hold event data
let event
// verify it
try {
event = stripe.webhooks.constructEvent(body, signature, env.STRIPE_WEBHOOK_SECRET)
} catch (err) {
// signature is invalid!
console.warn('⚠️ Webhook signature verification failed.', err.message)
// return, because it's a bad request
throw error(400, 'Invalid request')
}
// signature has been verified, so we can process events
// full list of events: https://stripe.com/docs/api/events/list
if (event.type == 'charge.succeeded') {
// get data object
const charge = event.data.object
// TODO: fulfill the order here
console.log(`✅ Charge succeeded ${charge.id}`)
}
// return a 200 with an empty JSON response
return json()
}
```
--------------------------------
### Use Payment Element for All-in-One Payments
Source: https://github.com/joshnuss/svelte-stripe/blob/main/src/routes/+page.md
Integrate the PaymentElement component into your form for a unified payment experience supporting cards, SEPA, GooglePay, and ApplePay. Ensure automatic payment methods are enabled on the server.
```svelte
```
--------------------------------
### Integrate Link Authentication Element
Source: https://github.com/joshnuss/svelte-stripe/blob/main/src/routes/+page.md
Add the LinkAuthenticationElement to your form to enable customers to use their Link account for faster checkouts, retrieving saved payment and address details.
```svelte
```
--------------------------------
### Enable Automatic Payment Methods
Source: https://github.com/joshnuss/svelte-stripe/blob/main/src/routes/+page.md
Configure the payment intent on the server to enable automatic payment methods, allowing Stripe to determine the best available payment options for the customer.
```javascript
const paymentIntent = await stripe.paymentIntents.create({
amount: 2000,
currency: 'eur',
automatic_payment_methods: {
enabled: true
}
})
```
--------------------------------
### Svelte Express Checkout Button
Source: https://github.com/joshnuss/svelte-stripe/blob/main/src/routes/+page.md
Integrate GooglePay or ApplePay using the ExpressCheckout component. Handle onclick to add line items and onconfirm to complete the payment.
```svelte
```
```javascript
async function click(event) {
const options = {
emailRequired: true,
phoneNumberRequired: true,
lineItems: [
{
name: 'Rad T-Shirt',
amount: 1099
}
]
}
event.resolve(options)
}
```
```javascript
async function confirm(event) {
let result = await elements.submit()
if (result.error) {
// validation failed, notify user
error = result.error
return
}
// create payment intent server side
const clientSecret = await createPaymentIntent()
const return_url = new URL('/examples/thanks', window.location.origin).toString()
// confirm payment with stripe
result = await stripe.confirmPayment({
elements,
clientSecret,
confirmParams: {
return_url
}
})
if (result.error) {
// payment failed, notify user
error = result.error
} else {
// payment succeeded, redirect to "thank you" page
goto('/thanks')
}
}
```
--------------------------------
### Svelte LinkAuthenticationElement Component
Source: https://context7.com/joshnuss/svelte-stripe/llms.txt
Integrate the LinkAuthenticationElement to enable Stripe Link for customers, allowing them to reuse payment methods. It requires Stripe initialization and a client secret from a payment intent.
```svelte
{#if stripe && clientSecret}
{/if}
```
--------------------------------
### Iban Component for SEPA Payments
Source: https://context7.com/joshnuss/svelte-stripe/llms.txt
Collect SEPA direct debit payment details using the Iban component. Requires initializing Stripe on the client and confirming the payment on the server.
```svelte
{#if stripe}
{/if}
```
--------------------------------
### Svelte Credit Card Form
Source: https://github.com/joshnuss/svelte-stripe/blob/main/src/routes/+page.md
Use CardNumber, CardExpiry, and CardCvc components to build a credit card input form. Pass the cardElement to stripe.confirmCardPayment() on form submission.
```svelte
```
```javascript
const result = await stripe
.confirmCardPayment(clientSecret, {
payment_method: {
card: cardElement,
billing_details: {
...
}
}
})
```
--------------------------------
### Handle Stripe Webhooks
Source: https://context7.com/joshnuss/svelte-stripe/llms.txt
Implement this webhook handler to receive and process payment-related events from Stripe. It verifies the signature and handles specific event types like 'charge.succeeded'.
```typescript
// src/routes/stripe/webhooks/+server.ts
import Stripe from 'stripe'
import { SECRET_STRIPE_KEY, STRIPE_WEBHOOK_SECRET } from '$env/static/private'
import { error } from '@sveltejs/kit'
const stripe = new Stripe(SECRET_STRIPE_KEY)
export async function POST({ request }) {
const body = await request.text()
const signature = request.headers.get('stripe-signature')
if (!signature) return error(401)
let event
try {
event = stripe.webhooks.constructEvent(body, signature, STRIPE_WEBHOOK_SECRET)
} catch (err) {
console.warn('Webhook signature verification failed.')
return new Response(undefined, { status: 400 })
}
// Handle specific events
switch (event.type) {
case 'charge.succeeded':
const charge = event.data.object
console.log(`Charge succeeded: ${charge.id}`)
// Fulfill order here
break
case 'payment_intent.succeeded':
const paymentIntent = event.data.object
console.log(`PaymentIntent succeeded: ${paymentIntent.id}`)
break
case 'payment_intent.payment_failed':
const failedIntent = event.data.object
console.log(`Payment failed: ${failedIntent.last_payment_error?.message}`)
break
}
return new Response(undefined)
}
```
--------------------------------
### Svelte iDEAL Payment Form
Source: https://github.com/joshnuss/svelte-stripe/blob/main/src/routes/+page.md
Accept iDEAL payments using the Ideal component. Collect customer details and the idealElement, then call stripe.confirmIdealPayment() with a return_url.
```svelte
```
```javascript
const result = await stripe.confirmIdealPayment(clientSecret, {
payment_method: {
ideal: idealElement,
billing_details: {
name,
email
}
},
return_url: `${window.location.origin}/return`
})
```
--------------------------------
### Custom Card Form with Individual Inputs
Source: https://context7.com/joshnuss/svelte-stripe/llms.txt
Use CardNumber, CardExpiry, and CardCvc components for granular control over card data collection in custom form layouts. Ensure Stripe is loaded before rendering the form.
```svelte
{#if stripe}
{/if}
```
--------------------------------
### Svelte SEPA Debit Form
Source: https://github.com/joshnuss/svelte-stripe/blob/main/src/routes/+page.md
Use the Iban component for SEPA direct debit payments. Collect IBAN and customer details, then use stripe.confirmSepaDebitPayment() to process.
```svelte
```
```javascript
const result = await stripe.confirmSepaDebitPayment(clientSecret, {
payment_method: {
sepa_debit: ibanElement,
billing_details: {
name,
email
}
}
})
```
--------------------------------
### Express Checkout for One-Click Payments
Source: https://context7.com/joshnuss/svelte-stripe/llms.txt
Integrate ExpressCheckout for seamless one-click payments via Apple Pay, Google Pay, and Link without user redirection. Configure payment methods and order, and handle click and confirm events.
```svelte
{#if stripe}
{/if}
```
--------------------------------
### Stripe PaymentElement with Form Integration
Source: https://context7.com/joshnuss/svelte-stripe/llms.txt
Integrates the PaymentElement with a form, including LinkAuthenticationElement, Address, and a submit button. Handles payment confirmation and error display.
```svelte
{#if stripe && clientSecret}
{/if}
```
--------------------------------
### Confirm Payment with Stripe Elements
Source: https://github.com/joshnuss/svelte-stripe/blob/main/src/routes/+page.md
After form submission, use `stripe.confirmPayment()` to process the payment. Specify `redirect: 'if_required'` or a `return_url` for handling redirects.
```javascript
const result = await stripe.confirmPayment({
elements,
// specify redirect: 'if_required' or a `return_url`
redirect: 'if_required'
})
```
--------------------------------
### Customize Stripe Elements Appearance
Source: https://github.com/joshnuss/svelte-stripe/blob/main/src/routes/+page.md
Style Stripe Elements by setting the `appearance` attribute on the `` container. This allows for customization of themes, labels, and specific visual rules.
```svelte
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.