-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathviews.py
66 lines (48 loc) · 2.21 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
from django.shortcuts import render
import stripe
from django.conf import settings
from django.views.decorators.http import require_http_methods
from django.http import HttpResponse
stripe.api_key = settings.STRIPE_SECRET
@require_http_methods(['GET'])
def main(request):
return render(request, "index.html")
@require_http_methods(['POST'])
def charges(request):
# if stripe base url not found in settings, use the default url
if settings.STRIPE_BASE_URL:
stripe.api_base = settings.STRIPE_BASE_URL
try:
stripe.Charge.create(
amount=remove_decimal_places(extract_amount(request)),
currency='EUR',
description='Charge for testing.pays@example.com',
source=request.POST['stripeToken'],
)
except stripe.error.CardError as error:
return generate_http_response(extract_error_code(error), error.http_status)
except stripe.error.RateLimitError as error:
return generate_http_response(extract_error_code(error), error.http_status)
except stripe.error.InvalidRequestError as error:
if not extract_error_code(error):
return generate_http_response(extract_error_param(error), error.http_status)
return generate_http_response(extract_error_code(error), error.http_status)
except stripe.error.AuthenticationError as error:
return generate_http_response(extract_error_code(error), error.http_status)
except stripe.error.APIConnectionError as error:
return generate_http_response(extract_error_code(error), error.http_status)
except stripe.error.StripeError as error:
return generate_http_response(extract_error_code(error), error.http_status)
except Exception as error:
return generate_http_response(error, 418)
return render(request, 'index.html')
def extract_amount(request):
return request.POST['amount']
def extract_error_param(e):
return e.json_body['error']['param']
def generate_http_response(error_code, http_status):
return HttpResponse(error_code, content_type="application/json", status=http_status)
def extract_error_code(e):
return e.json_body['error']['code']
def remove_decimal_places(amount):
return int(float(amount) * 100)