Skip to content

Commit

Permalink
Add checkout form data caching in payment intent and remove unused st…
Browse files Browse the repository at this point in the history
…ripe javascript on checkout success template
  • Loading branch information
Awoyalejohn committed Aug 5, 2022
1 parent 8ec5bfc commit e01f898
Show file tree
Hide file tree
Showing 6 changed files with 127 additions and 28 deletions.
1 change: 0 additions & 1 deletion cart/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ def post(self, request, slug):
#Adds the amount of that item to its value in the dictionary
request.session['cart'] = cart

print(request.session['cart'])
return redirect(redirect_url)


Expand Down
107 changes: 90 additions & 17 deletions checkout/static/checkout/js/stripe_elements.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,30 +47,103 @@ card.addEventListener('change', (event) => {
const form = document.querySelector('#payment-form');

form.addEventListener('submit', (event) => {
// Prevents form from submitting
event.preventDefault();
//disables card element
card.disabled = true;
document.querySelector('#submit-button').disabled = true;

stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: card,
// Checks the checkbox if its checked
let saveInfo = document.querySelector('#id-save-info')
if (typeof (saveInfo) != 'undefined' && saveInfo != null) {
saveInfo = saveInfo.checked;
} else {
saveInfo = false;
}
console.log(saveInfo);

// Gets CSRF Token from using {% csrf_token %} in the form
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;

// Url that the data will be posted to
const url = '/checkout/cache_checkout_data/';

//headers
headerInfo = {
'Content-Type': 'application/json',
'X-CSRFToken': csrftoken,
};

// Data to post
const postData = {
"client_secret": clientSecret,
"save_info": saveInfo
};

// Django docs implementation of posting data with CSRF token
const request = new Request(
url,
{
method: 'POST',
headers: headerInfo,
body: JSON.stringify(postData),
mode: 'same-origin' // Do not send CSRF token to another domain.
}
}).then(function (result) {
if (result.error) {
let errorDiv = document.querySelector('#card-errors');
let html = `
);

fetch(request)
.then(function (data) {
console.log('Success:', data);
stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: card,
billing_details: {
name: form.full_name.value.trim(),
phone: form.phone_number.value.trim(),
email: form.email.value.trim(),
address: {
line1: form.street_address1.value.trim(),
line2: form.street_address2.value.trim(),
city: form.town_or_city.value.trim(),
country: form.country.value.trim(),
state: form.county.value.trim(),
}
}
},
shipping: {
name: form.full_name.value.trim(),
phone: form.phone_number.value.trim(),
address: {
line1: form.street_address1.value.trim(),
line2: form.street_address2.value.trim(),
city: form.town_or_city.value.trim(),
country: form.country.value.trim(),
postal_code: form.postcode.value.trim(),
state: form.county.value.trim(),
}
},
}).then(function (result) {
if (result.error) {
let errorDiv = document.querySelector('#card-errors');
let html = `
<span class="icon" role="alert">
<i class="fas fa-times"></i>
</span>
<span>${result.error.message}</span
`;
errorDiv.innerHTML = html;
card.disabled = false;
document.querySelector('#submit-button').disabled = false;
} else {
if (result.paymentIntent.status === 'succeeded') {
form.submit();
}
}
})
});
errorDiv.innerHTML = html;
card.disabled = false;
document.querySelector('#submit-button').disabled = false;
} else {
if (result.paymentIntent.status === 'succeeded') {
form.submit();
}
}
})
})
.catch(function (error) {
// Reloads the page
console.log('Error:', error);
location.reload();
});
});
7 changes: 0 additions & 7 deletions checkout/templates/checkout/checkout_success.html
Original file line number Diff line number Diff line change
Expand Up @@ -203,10 +203,3 @@ <h2 class="section-heading">Thank You</h2>

</main>
{% endblock %}

{% block postloadjs %}
{{ block.super }}
{{ stripe_public_key|json_script:"id_stripe_public_key" }}
{{ client_secret|json_script:"id_client_secret" }}
<script src="{% static 'checkout/js/stripe_elements.js' %}"></script>
{% endblock %}
5 changes: 3 additions & 2 deletions checkout/urls.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from django.urls import path
from checkout.views import Checkout, CheckoutSuccess
from checkout.views import Checkout, CheckoutSuccess, cache_checkout_data
from .webhooks import webhook

urlpatterns = [
path('', Checkout.as_view(), name='checkout'),
path('checkout_success/<order_number>', CheckoutSuccess.as_view(), name='checkout_success'),
path('wh/>', webhook, name='webhook'),
path('cache_checkout_data/', cache_checkout_data, name='cache_checkout_data'),
path('wh/', webhook, name='webhook'),
]
33 changes: 32 additions & 1 deletion checkout/views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django.shortcuts import get_object_or_404, render, redirect, reverse
from django.shortcuts import get_object_or_404, render, redirect, reverse, HttpResponse
from django.views.decorators.http import require_POST
from django.contrib import messages
from django.conf import settings
from django.views.generic import View
Expand All @@ -8,6 +9,36 @@
from cart.contexts import cart_contents

import stripe
from django.http import JsonResponse
import json







@require_POST
def cache_checkout_data(request):
try:
req_json = json.loads(request.body)
pid = req_json['client_secret'].split('_secret')[0]
print(pid)
stripe.api_key = settings.STRIPE_SECRET_KEY
stripe.PaymentIntent.modify(pid, metadata={
'cart': json.dumps(request.session.get('cart', {})),
'save_info': req_json['save_info'],
'username': request.user,
})
return HttpResponse(status=200)
except Exception as e:
messages.error(request, 'Sorry, your payment cannot be \
processed right now. Please try again later.')
print(e)
print(e)
return HttpResponse(content=e, status=400)



# Create your views here.
class Checkout(View):
Expand Down
2 changes: 2 additions & 0 deletions checkout/webhook_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ def handle_payment_intent_succeeded(self, event):
"""
Handle the payment_intent.succeeded webhook from Stripe
"""
intent = event.data.object
print(intent)
return HttpResponse(
content=f'Webhook received: {event["type"]}',
status=200)
Expand Down

0 comments on commit e01f898

Please sign in to comment.