Django stripe expand data to webhook

i sending order data by post request to stripe and creating session and set my order data in line_items, problem is that i want this line_items data to expand to stripe webhook view and by this data creating order and payment history, i tryed first to set this data to

metadata={"data": items}

but i get error, because is limited count of keys, it’s means that my data is too big to put in metadata, after that i found in that i can put my data in expand like that

expand=[‘line_items’]

but nothing happend i don’t get this data in my webhook view, but i get this data on stripe website

so here is my code i hope someone helps me :p

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>from django.conf import settings
from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.views.decorators.csrf import csrf_exempt
import stripe
from rest_framework.decorators import api_view
from accounts.models import AppUser
stripe.api_key = settings.STRIPE_SECRET_KEY
class StripeCheckoutView(APIView):
def post(self, request):
try:
data = request.data['orderData']['orderItems']
items = []
for i in data.keys():
i = data[i]
desc = ', '.join([i.get('name') for i in i.get('extra').values()]) + i.get('extra_info')
name = ', '.join(
filter(None, [
i.get('name'),
i.get('pizzaDough', ''),
f"{str(i.get('size', ''))} size" if i.get('size') else '',
f"{str(i.get('grams', ''))} grams" if i.get('grams') else '',
])
)
items.append(
{
"price_data": {
"currency": "usd",
"unit_amount": int(i['price']),
"product_data": {
"name": name,
"description": f"+ {desc}" if len(desc) > 0 else " ",
"images": [i['img_modify'],],
},
},
"quantity": i['quantity'],
}
)
checkout_session = stripe.checkout.Session.create(
line_items=items,
mode='payment',
expand=['line_items'],
success_url=settings.SITE_URL + '/?success=true&session_id={CHECKOUT_SESSION_ID}',
cancel_url=settings.SITE_URL + '/?canceled=true',
automatic_tax={"enabled": True},
#discounts=[{"coupon": "promo_1PnWnuGKlfpQfnx9vj6v7cw9"}],
allow_promotion_codes=True,
shipping_options=[
{
"shipping_rate_data": {
"type": 'fixed_amount',
"fixed_amount": {
"amount": 500,
"currency": 'usd',
},
"display_name": 'Food Shipping',
"delivery_estimate": {
"maximum": {
"unit": 'hour',
"value": 1,
},
},
},
},
],
)
return Response({"url": checkout_session.url})
except:
return Response(
{'error': 'Something went wrong when creating stripe checkout session'},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
@csrf_exempt
@api_view(['POST'])
def stripe_webhook_view(request):
payload = request.body
sig_header = request.META['HTTP_STRIPE_SIGNATURE']
event = None
print(request.POST)
try:
event = stripe.Webhook.construct_event(
payload,
sig_header,
settings.STRIPE_SECRET_WEBHOOK
)
except ValueError as e:
return HttpResponse({"error": 'Error parsing payload', 'payload': payload},status=400)
except stripe.error.SignatureVerificationError as e:
return HttpResponse({"error":'Error verifying webhook signature', 'sign_header': sig_header},status=400)
if event['type'] == 'checkout.session.completed':
session = event['data']['object']
print(session, event['data'])
if event.type == 'payment_intent.succeeded':
payment_intent = event.data.object # contains a stripe.PaymentIntent
print(payment_intent)
elif event.type == 'payment_method.attached':
payment_method = event.data.object # contains a stripe.PaymentMethod
print(payment_method)
# ... handle other event types
else:
print('Unhandled event type {}'.format(event.type))
return HttpResponse(status=200)
</code>
<code>from django.conf import settings from django.http import HttpResponse from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from django.views.decorators.csrf import csrf_exempt import stripe from rest_framework.decorators import api_view from accounts.models import AppUser stripe.api_key = settings.STRIPE_SECRET_KEY class StripeCheckoutView(APIView): def post(self, request): try: data = request.data['orderData']['orderItems'] items = [] for i in data.keys(): i = data[i] desc = ', '.join([i.get('name') for i in i.get('extra').values()]) + i.get('extra_info') name = ', '.join( filter(None, [ i.get('name'), i.get('pizzaDough', ''), f"{str(i.get('size', ''))} size" if i.get('size') else '', f"{str(i.get('grams', ''))} grams" if i.get('grams') else '', ]) ) items.append( { "price_data": { "currency": "usd", "unit_amount": int(i['price']), "product_data": { "name": name, "description": f"+ {desc}" if len(desc) > 0 else " ", "images": [i['img_modify'],], }, }, "quantity": i['quantity'], } ) checkout_session = stripe.checkout.Session.create( line_items=items, mode='payment', expand=['line_items'], success_url=settings.SITE_URL + '/?success=true&session_id={CHECKOUT_SESSION_ID}', cancel_url=settings.SITE_URL + '/?canceled=true', automatic_tax={"enabled": True}, #discounts=[{"coupon": "promo_1PnWnuGKlfpQfnx9vj6v7cw9"}], allow_promotion_codes=True, shipping_options=[ { "shipping_rate_data": { "type": 'fixed_amount', "fixed_amount": { "amount": 500, "currency": 'usd', }, "display_name": 'Food Shipping', "delivery_estimate": { "maximum": { "unit": 'hour', "value": 1, }, }, }, }, ], ) return Response({"url": checkout_session.url}) except: return Response( {'error': 'Something went wrong when creating stripe checkout session'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR ) @csrf_exempt @api_view(['POST']) def stripe_webhook_view(request): payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None print(request.POST) try: event = stripe.Webhook.construct_event( payload, sig_header, settings.STRIPE_SECRET_WEBHOOK ) except ValueError as e: return HttpResponse({"error": 'Error parsing payload', 'payload': payload},status=400) except stripe.error.SignatureVerificationError as e: return HttpResponse({"error":'Error verifying webhook signature', 'sign_header': sig_header},status=400) if event['type'] == 'checkout.session.completed': session = event['data']['object'] print(session, event['data']) if event.type == 'payment_intent.succeeded': payment_intent = event.data.object # contains a stripe.PaymentIntent print(payment_intent) elif event.type == 'payment_method.attached': payment_method = event.data.object # contains a stripe.PaymentMethod print(payment_method) # ... handle other event types else: print('Unhandled event type {}'.format(event.type)) return HttpResponse(status=200) </code>
from django.conf import settings
from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.views.decorators.csrf import csrf_exempt
import stripe
from rest_framework.decorators import api_view
from accounts.models import AppUser

stripe.api_key = settings.STRIPE_SECRET_KEY


class StripeCheckoutView(APIView):
    def post(self, request):
        try:

            data = request.data['orderData']['orderItems']
            items = []
            for i in data.keys():
               i = data[i]
               desc = ', '.join([i.get('name') for i in i.get('extra').values()]) + i.get('extra_info')
               name = ', '.join(
                   filter(None, [
                        i.get('name'),
                        i.get('pizzaDough', ''),
                        f"{str(i.get('size', ''))} size" if i.get('size') else '',
                        f"{str(i.get('grams', ''))} grams" if i.get('grams') else '',
                   ])
               )
               items.append(
                    {   
                        "price_data": {
                            "currency": "usd",
                            "unit_amount": int(i['price']),
                            "product_data": {
                                "name": name,
                                "description": f"+ {desc}" if len(desc) > 0 else " ",
                                "images": [i['img_modify'],],
                            },
                        },
                        "quantity": i['quantity'],
                    }
                )


            checkout_session = stripe.checkout.Session.create(
                line_items=items,
                mode='payment',
                expand=['line_items'],
                success_url=settings.SITE_URL + '/?success=true&session_id={CHECKOUT_SESSION_ID}',
                cancel_url=settings.SITE_URL + '/?canceled=true',
                automatic_tax={"enabled": True},
                #discounts=[{"coupon": "promo_1PnWnuGKlfpQfnx9vj6v7cw9"}],
                allow_promotion_codes=True,
                shipping_options=[
                    {
                    "shipping_rate_data": {
                        "type": 'fixed_amount',
                        "fixed_amount": {
                            "amount": 500,
                            "currency": 'usd',
                        },
                        "display_name": 'Food Shipping',
                        "delivery_estimate": {
                        "maximum": {
                            "unit": 'hour',
                            "value": 1,
                        },
                        },
                    },
                    },
                ],
            )


            return Response({"url": checkout_session.url})
        except:
            return Response(
                {'error': 'Something went wrong when creating stripe checkout session'},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )


@csrf_exempt
@api_view(['POST'])
def stripe_webhook_view(request):
    payload = request.body
    sig_header = request.META['HTTP_STRIPE_SIGNATURE']
    event = None

    print(request.POST)

    try:
        event = stripe.Webhook.construct_event(
            payload,
            sig_header,
            settings.STRIPE_SECRET_WEBHOOK
        )
    except ValueError as e:
        return HttpResponse({"error": 'Error parsing payload', 'payload': payload},status=400)
    except stripe.error.SignatureVerificationError as e:
        return HttpResponse({"error":'Error verifying webhook signature', 'sign_header': sig_header},status=400)

    if event['type'] == 'checkout.session.completed':
        session = event['data']['object']
        print(session, event['data'])
    if event.type == 'payment_intent.succeeded':
        payment_intent = event.data.object # contains a stripe.PaymentIntent
        print(payment_intent)
    elif event.type == 'payment_method.attached':
        payment_method = event.data.object # contains a stripe.PaymentMethod
        print(payment_method)
    # ... handle other event types
    else:
        print('Unhandled event type {}'.format(event.type))


    return HttpResponse(status=200)

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật