# This example sets up an endpoint using the Sinatra framework.# To learn more about Sinatra, watch this video: https://youtu.be/8aA9Enb8NVc.require'json'require'sinatra'require'stripe'# Set your secret key. Remember to switch to your live secret key in production.# See your keys here: https://dashboard.stripe.com/apikeysStripe.api_key =
'sk_test_4eC39HqLyjWDarjtT1zdp7dc'
post '/create-checkout-session'do
session =Stripe::Checkout::Session.create({
line_items:[{
price_data:{
currency:'usd',
product_data:{
name:'T-shirt',},
unit_amount:2000,},
quantity:1,}],
mode:'payment',
ui_mode:'embedded',
return_url:'https://example.com/checkout/return?session_id={CHECKOUT_SESSION_ID}'}){clientSecret: session.client_secret}.to_json
end
Checkout is available as part of Stripe.js. Include the Stripe.js script on your page by adding it to the head of your HTML file. Next, create an empty DOM node (container) to use for mounting.
index.html
<head><scriptsrc="https://js.stripe.com/v3/"></script></head><body><divid="checkout"><!-- Checkout will insert the payment form here --></div></body>
Initialize Stripe.js with your publishable API key.
Create an asynchronous fetchClientSecret function that makes a request to your server to create the Checkout Session and retrieve the client secret. Pass this function into options when you create the Checkout instance:
index.js
// Initialize Stripe.jsconst stripe =Stripe(
'pk_test_TYooMQauvdEDq54NiTphI7jx'
);initialize();// Fetch Checkout Session and retrieve the client secretasyncfunctioninitialize(){constfetchClientSecret=async()=>{const response =awaitfetch("/create-checkout-session",{
method:"POST",});const{ clientSecret }=await response.json();return clientSecret;};// Initialize Checkoutconst checkout =await stripe.initEmbeddedCheckout({
fetchClientSecret,});// Mount Checkout
checkout.mount('#checkout');}
Checkout renders in an iframe that securely sends payment information to Stripe over an HTTPS connection.
常见错误
Avoid placing Checkout within another iframe because some payment methods require redirecting to another page for payment confirmation.
get '/session-status'do
session =Stripe::Checkout::Session.retrieve(params[:session_id]){status: session.status, customer_email: session.customer_details.email}.to_json
end
client.js
const session =awaitfetch(`/session_status?session_id=${session_id}`)if(session.status=='open'){// Remount embedded Checkout}elseif(session.status=='complete'){// Show success page// Optionally use session.payment_status or session.customer_email// to customize the success page}
Welcome to the Stripe Shell!
Stripe Shell is a browser-based shell with the Stripe CLI pre-installed. Log in to your
Stripe account and press Control + Backtick (`) on your keyboard to start managing your Stripe
resources in test mode.
- View supported Stripe commands:
- Find webhook events:
- Listen for webhook events:
- Call Stripe APIs: stripe [api resource] [operation] (e.g., )