-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathviews.py
143 lines (116 loc) · 4.48 KB
/
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import json
import stripe
from django.core.mail import send_mail
from django.conf import settings
from django.views.generic import TemplateView
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse, HttpResponse
from django.views import View
from .models import Product
stripe.api_key = settings.STRIPE_SECRET_KEY
class SuccessView(TemplateView):
template_name = "success.html"
class CancelView(TemplateView):
template_name = "cancel.html"
class ProductLandingPageView(TemplateView):
template_name = "landing.html"
def get_context_data(self, **kwargs):
product = Product.objects.get(name="Test Product")
context = super(ProductLandingPageView, self).get_context_data(**kwargs)
context.update({
"product": product,
"STRIPE_PUBLIC_KEY": settings.STRIPE_PUBLIC_KEY
})
return context
class CreateCheckoutSessionView(View):
def post(self, request, *args, **kwargs):
product_id = self.kwargs["pk"]
product = Product.objects.get(id=product_id)
YOUR_DOMAIN = "http://127.0.0.1:8000"
checkout_session = stripe.checkout.Session.create(
payment_method_types=['card'],
line_items=[
{
'price_data': {
'currency': 'usd',
'unit_amount': product.price,
'product_data': {
'name': product.name,
# 'images': ['https://i.imgur.com/EHyR2nP.png'],
},
},
'quantity': 1,
},
],
metadata={
"product_id": product.id
},
mode='payment',
success_url=YOUR_DOMAIN + '/success/',
cancel_url=YOUR_DOMAIN + '/cancel/',
)
return JsonResponse({
'id': checkout_session.id
})
@csrf_exempt
def stripe_webhook(request):
payload = request.body
sig_header = request.META['HTTP_STRIPE_SIGNATURE']
event = None
try:
event = stripe.Webhook.construct_event(
payload, sig_header, settings.STRIPE_WEBHOOK_SECRET
)
except ValueError as e:
# Invalid payload
return HttpResponse(status=400)
except stripe.error.SignatureVerificationError as e:
# Invalid signature
return HttpResponse(status=400)
# Handle the checkout.session.completed event
if event['type'] == 'checkout.session.completed':
session = event['data']['object']
customer_email = session["customer_details"]["email"]
product_id = session["metadata"]["product_id"]
product = Product.objects.get(id=product_id)
send_mail(
subject="Here is your product",
message=f"Thanks for your purchase. Here is the product you ordered. The URL is {product.url}",
recipient_list=[customer_email],
from_email="[email protected]"
)
# TODO - decide whether you want to send the file or the URL
elif event["type"] == "payment_intent.succeeded":
intent = event['data']['object']
stripe_customer_id = intent["customer"]
stripe_customer = stripe.Customer.retrieve(stripe_customer_id)
customer_email = stripe_customer['email']
product_id = intent["metadata"]["product_id"]
product = Product.objects.get(id=product_id)
send_mail(
subject="Here is your product",
message=f"Thanks for your purchase. Here is the product you ordered. The URL is {product.url}",
recipient_list=[customer_email],
from_email="[email protected]"
)
return HttpResponse(status=200)
class StripeIntentView(View):
def post(self, request, *args, **kwargs):
try:
req_json = json.loads(request.body)
customer = stripe.Customer.create(email=req_json['email'])
product_id = self.kwargs["pk"]
product = Product.objects.get(id=product_id)
intent = stripe.PaymentIntent.create(
amount=product.price,
currency='usd',
customer=customer['id'],
metadata={
"product_id": product.id
}
)
return JsonResponse({
'clientSecret': intent['client_secret']
})
except Exception as e:
return JsonResponse({ 'error': str(e) })