PacktPublishing / Django-4-by-example

Django 4 by example (4th Edition) published by Packt
https://djangobyexample.com/
MIT License
818 stars 461 forks source link

In chaper 9: The stripe API had changing #4

Closed concocon2003 closed 2 years ago

concocon2003 commented 2 years ago

The API of Stripe had changing: So in the payment_process function , i change to: def payment_process(request):

......

    # add order items to the Stripe checkout session
    for item in order.items.all():
        session_data['line_items'].append({
            'price_data': {
                'unit_amount_decimal': int(item.price * Decimal('100')),
                'currency': 'usd',
                'product_data': {
                    'name': item.product.name,
                },
            },

            'quantity': item.quantity,
        })
    # after change this, i can create Stripe checkout session
    session = stripe.checkout.Session.create(**session_data) 
    # But 
    # link checkout session with order >> my current problem is "session.payment_intent" is None  
    order.stripe_id = session.payment_intent
    order.save()
    #  Please solve this problem.
concocon2003 commented 2 years ago

I have solve this

def payment_process(request): order_id = request.session.get('order_id', None) order = get_object_or_404(Order, id=order_id) if request.method == 'POST': success_url = request.build_absolute_uri( reverse('payment:completed') ) cancel_url = request.build_absolute_uri( reverse('payment:canceled') )

Stripe checkout session data

    session_data = {
        'mode': 'payment',
        'success_url': success_url,
        'cancel_url': cancel_url,
        'line_items': []
    }
    # add order items to the Stripe checkout session
    for item in order.items.all():
        session_data['line_items'].append({
            'price_data': {
                'unit_amount_decimal': int(item.price * Decimal('100')),
                'currency': 'usd',
                'product_data': {
                    'name': item.product.name,
                },
            },
            'quantity': item.quantity,
        })
    # create Stripe checkout session
    response = stripe.checkout.Session.create(**session_data)
    # store cs_id
    request.session["cs_id"] = response.id
    # redirect to Stripe payment form
    return redirect(response.url, code=303)
else:
    return render(request, 'payment/process.html', locals())

def payment_completed(request): order_id = request.session.get('order_id', None) order = get_object_or_404(Order, id=order_id)

retrieve object from cs_id for get payment_intent

cs = stripe.checkout.Session.retrieve(request.session["cs_id"])
# link checkout session with order
order.stripe_id = cs.payment_intent
order.save()
return render(request, 'payment/completed.html')