Chat
Ask me anything
Ithy Logo

Transitioning to Stripe Pricing Tables in Python: A Step-by-Step Guide

Implementing Promo Codes and Free Trials Without Disrupting Your Existing Integration

stripe pricing table integration
PRO
OpenAI o1

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.

Key Takeaways

  • Create and configure Stripe Pricing Tables directly in the Dashboard to manage products, prices, promo codes, and free trials.
  • Embed the Pricing Table into your application, replacing direct calls to stripe.checkout.Session.create in your backend.
  • Update your backend to handle Stripe webhooks appropriately, ensuring seamless integration without breaking existing functionality.

Understanding the Transition

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:

  • Enhanced Features: Pricing Tables natively support promo codes and free trials.
  • Simplified Management: Products and pricing can be managed directly from the Stripe Dashboard.
  • User Experience: Pricing Tables provide a clean, embeddable UI for your customers to select products.

The key is to shift the checkout initiation from your backend to the frontend, leveraging Stripe's embeddable components.

Step 1: Create a Pricing Table in Stripe Dashboard

Setting Up Products and Prices

Begin by ensuring that all your products and their respective prices are correctly set up in your Stripe Dashboard:

  1. Navigate to the Products section in your Stripe Dashboard.
  2. Create new products or verify existing ones.
  3. For each product, ensure you have prices configured (e.g., monthly subscription, annual subscription).

Creating the Pricing Table

With your products and prices in place, proceed to create a Pricing Table:

  1. Go to the Pricing Tables section.
  2. Click on Create Pricing Table.
  3. Add the products and prices you wish to include.
  4. Configure the display settings, such as:
    • Appearance: Customize colors and styles to match your branding.
    • Pricing Details: Include trial periods and highlight features.
    • Promo Codes: Enable the option to accept promo codes at checkout.
  5. Once configured, save and publish your Pricing Table.

After publishing, you'll receive an embeddable code snippet and a unique Pricing Table ID.

Step 2: Embed the Pricing Table into Your Application

Front-End Integration

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.

Removing Backend Checkout Session Creation

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.

Step 3: Update Your Backend to Handle Webhooks

While the frontend now initiates the checkout process, your backend must still handle Stripe webhook events to respond to payment and subscription updates appropriately.

Configuring Webhooks

Ensure your Stripe webhook endpoint is set up to receive relevant events:

  1. In your Stripe Dashboard, navigate to Developers > Webhooks.
  2. Add or update your endpoint URL (e.g., https://yourdomain.com/webhook).
  3. Select events to listen to, such as:
    • checkout.session.completed
    • customer.subscription.created
    • invoice.paid
    • invoice.payment_failed
  4. Save the webhook endpoint and note the signing secret.

Implementing Webhook Handling in Python

In 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

Step 4: Enable Promo Codes and Free Trials

One of the main benefits of using Pricing Tables is the ease of enabling promo codes and free trials.

Configuring Promo Codes

  1. Create Coupons:

    • In your Stripe Dashboard, navigate to Products > Coupons.
    • Click on New to create a coupon.
    • Set the discount parameters (amount off, percentage off, duration).
  2. Create Promo Codes:

    • After creating a coupon, create a promo code linked to it.
    • Navigate to Products > Promo codes.
    • Click on New to create a promo code.
    • Associate it with the coupon you just created and set any restrictions.
  3. Enable Promo Codes in the Pricing Table:

    • Go back to your Pricing Table settings.
    • Under Settings, enable the option to Accept promo codes at checkout.
    • Save the changes.

Setting Up Free Trials

To offer free trials for your subscriptions:

  1. When creating or editing a price in the Stripe Dashboard:
    • Select the product and price you wish to edit.
    • Under the pricing options, enable Trial period and specify the duration (e.g., 14 days).
    • Save the changes.
  2. Ensure the price with the trial period is included in your Pricing Table.

Customers selecting this price from the Pricing Table will automatically receive the free trial.

Step 5: Test the Integration Thoroughly

Before deploying the changes to production, it's crucial to test the entire flow:

  1. Use Stripe's Test Mode:

    • Ensure your Stripe keys are set to test keys (sk_test_... and pk_test_...).
    • Perform transactions using Stripe's test card numbers.
  2. Test Promo Codes:

    • Create test promo codes and apply them at checkout.
    • Verify that discounts are applied correctly.
  3. Test Free Trials:

    • Select a price with a free trial from the Pricing Table.
    • Ensure the trial period is reflected in the customer's subscription.
  4. Check Webhook Events:

    • Verify that your webhook endpoint is receiving and handling events appropriately.
    • Check logs or output to ensure functions like handle_checkout_session are executed.
  5. Validate Success and Cancel URLs:

    • Ensure that after checkout, customers are redirected to the correct success or cancel pages.
    • These can be configured in the Pricing Table settings under Advanced options.

Step 6: Deploy to Production

After thorough testing:

  1. Switch your Stripe keys to live mode.
  2. Update any configuration pointing to test resources (e.g., promo codes, webhook endpoints).
  3. Monitor the integration closely after deployment to catch any unforeseen issues.

Recap and Conclusion

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.

References

  • Stripe Documentation: Embeddable Pricing Table
  • Stripe Documentation: Subscription Trials
  • Stripe Documentation: Discounts and Promo Codes
  • Stripe Documentation: Webhooks
  • Stripe API Reference: Promotion Codes

Last updated January 24, 2025
Ask Ithy AI
Download Article
Delete Article