
If you're currently utilizing stripe.checkout.Session.create with price line items to generate checkout session URLs in your Python application, you might be wondering how to transition to using Stripe's Pricing Tables. This shift enables you to leverage powerful features like promo codes and free trials without breaking your existing setup. This comprehensive guide will walk you through each step of the process, ensuring a smooth transition.
stripe.checkout.Session.create in your backend.Switching from directly creating checkout sessions in your backend to using Stripe's Pricing Tables might seem daunting at first. However, this change brings significant benefits:
The key is to shift the checkout initiation from your backend to the frontend, leveraging Stripe's embeddable components.
Begin by ensuring that all your products and their respective prices are correctly set up in your Stripe Dashboard:
With your products and prices in place, proceed to create a Pricing Table:
After publishing, you'll receive an embeddable code snippet and a unique Pricing Table ID.
To display the Pricing Table on your website or application, embed it using the provided code snippet:
<!-- Include the Stripe.js library -->
<script async src="https://js.stripe.com/v3/pricing-table.js"></script>
<!-- Embed the Pricing Table -->
<stripe-pricing-table
pricing-table-id="prctbl_12345ABCDE"
publishable-key="pk_live_your_publishable_key"
client-reference-id="your_unique_client_reference"
customer-email="customer@example.com"
>
</stripe-pricing-table>
Replace the following placeholders with your actual values:
prctbl_12345ABCDE: Your unique Pricing Table ID.pk_live_your_publishable_key: Your Stripe publishable API key.your_unique_client_reference: An optional identifier for the customer.customer@example.com: Pre-fill the customer's email if known.Since the Pricing Table handles the checkout process, you no longer need to create checkout sessions in your backend. Remove or comment out any code that calls stripe.checkout.Session.create. For example:
# Previous backend code to create a checkout session
session = stripe.checkout.Session.create(
line_items=[{
'price': 'price_12345ABCDE', # Your price ID
'quantity': 1,
}],
mode='subscription',
success_url='https://yourdomain.com/success?session_id={CHECKOUT_SESSION_ID}',
cancel_url='https://yourdomain.com/cancel',
)
# Return the session URL to the frontend
return jsonify({'url': session.url})
After embedding the Pricing Table, this code is no longer necessary.
While the frontend now initiates the checkout process, your backend must still handle Stripe webhook events to respond to payment and subscription updates appropriately.
Ensure your Stripe webhook endpoint is set up to receive relevant events:
https://yourdomain.com/webhook).checkout.session.completedcustomer.subscription.createdinvoice.paidinvoice.payment_failedIn your backend application, implement webhook handling to process events. Here's an example using Flask:
from flask import Flask, request, jsonify
import stripe
app = Flask(__name__)
stripe.api_key = 'sk_live_your_secret_key'
endpoint_secret = 'whsec_your_webhook_signing_secret'
@app.route('/webhook', methods=['POST'])
def webhook():
payload = request.get_data()
sig_header = request.headers.get('Stripe-Signature')
try:
# Verify the event by constructing it with the signing secret
event = stripe.Webhook.construct_event(
payload, sig_header, endpoint_secret
)
except (ValueError, stripe.error.SignatureVerificationError) as e:
# Invalid payload or signature
return jsonify({'error': str(e)}), 400
# Handle the event
if event['type'] == 'checkout.session.completed':
session = event['data']['object']
# Fulfill the purchase or provision the service
handle_checkout_session(session)
elif event['type'] == 'invoice.paid':
invoice = event['data']['object']
# Handle successful payment
handle_successful_payment(invoice)
elif event['type'] == 'invoice.payment_failed':
invoice = event['data']['object']
# Handle failed payment
handle_failed_payment(invoice)
# Add more event types as needed
else:
print(f'Unhandled event type {event["type"]}')
return jsonify({'status': 'success'}), 200
def handle_checkout_session(session):
print(f'Checkout session completed: {session.id}')
# Implement your fulfillment logic here
def handle_successful_payment(invoice):
print(f'Invoice paid: {invoice.id}')
# Update subscription status or access
def handle_failed_payment(invoice):
print(f'Invoice payment failed: {invoice.id}')
# Notify the customer or take action
One of the main benefits of using Pricing Tables is the ease of enabling promo codes and free trials.
Create Coupons:
Create Promo Codes:
Enable Promo Codes in the Pricing Table:
To offer free trials for your subscriptions:
Customers selecting this price from the Pricing Table will automatically receive the free trial.
Before deploying the changes to production, it's crucial to test the entire flow:
Use Stripe's Test Mode:
sk_test_... and pk_test_...).Test Promo Codes:
Test Free Trials:
Check Webhook Events:
handle_checkout_session are executed.Validate Success and Cancel URLs:
After thorough testing:
Transitioning to Stripe Pricing Tables allows you to enhance your payment processing with features like promo codes and free trials, all while simplifying product management. By embedding the Pricing Table into your application and updating your backend to handle webhooks appropriately, you can achieve this without breaking your existing integration.
Remember to test extensively in a safe environment before going live. With the steps outlined in this guide, you should be well-equipped to make the transition smoothly.