#Flask stripe

1 messages · Page 1 of 1 (latest)

storm cloak
#
@payment_bp.route('/create-stripe-product')
def create_product():
    data = request.json
    stripe.api_key = os.getenv('STRIPE_SECRET_KEY')

    try:
        product = stripe.Product.create(
            name=data['name'],
            description=data['description', '']
        )
        
        price = stripe.Price.create(
            unit_amount=data['price'] * 100,
            currency='usd',
            product=product.id
        )
        
        return jsonify({
            'product_id': product.id,
            'price_id': price.id
        })
    except Exception as e:
        return jsonify(error=str(e))
#
@payment_bp.route('/checkout', methods=['GET', "POST"])
def checkout():
    form = CheckoutForm()
    user_id = current_user.id
    cart_items = CartModel.query.filter_by(user_id=user_id).all()
    products = []
    total_price = 0
    stripe.api_key = os.getenv('STRIPE_SECRET_KEY')
    stripe_public_key = os.getenv('STRIPE_PUBLISHABLE_KEY')
    domain_url = 'http://127.0.0.1:5000/'

    for item in cart_items:
        product = ProductModel.query.get(item.product_id)
        product.amount = item.amount
        total_price += product.amount * product.price
        products.append(product)

    if form.validate_on_submit():
        try:
            checkout_session = stripe.checkout.Session.create(
                success_url=domain_url + 'success?session_id={checkout_session.id}',
                cancel_url=domain_url + 'cancelled',
                payment_method_types=['card'],
                mode='payment',
                line_items=[{
                    'price_data': {
                        'currency': 'usd',
                        'product_data': {
                            'name': item.product.name,
                            'description': item.product.description,
                        },
                        'unit_amount': item.product.price,
                    },
                    'quantity': item.amount
                } for item in cart_items ]
            )
            return jsonify({'sessionId': checkout_session['id']})
        except Exception as e:
            return jsonify(error=str(e)), 403
    return render_template('base.html', form=form, total_price=total_price, cart=products, stripe_public_key=stripe_public_key) @payment_bp.route('/success')
def success():
    return "Payment was succesfull."

@payment_bp.route('/cancelled')
def cancelled():
    return "Payment was cancelled."


tall inlet
#

Hi - this is he development channel for internal Litestar related things

#

This would be more appropriate for help or off topic (since it’s related to flask)?