In this part, we adjust the previous code to show the Preview page, optionally.
class PreviewRedirect(RedirectView):
def get_redirect_url(self, **kwargs):
self.request.session['payment_method'] = self.request.POST.get('payment_method')
return reverse('checkout:preview')
from django.urls import path
from .views import *
urlpatterns = [
path("preview_redirect/", PreviewRedirect.as_view(), name="preview_redirect"),
]
...
{% block payment_details %}
{% block payment_details_content %}
<form action="{% url 'preview_redirect' %}" method="post">
{% csrf_token %}
<fieldset>
<input type="radio" name="payment_method" value="oscar_paypal" required> Oscar PayPal <br>
<input type="radio" name="payment_method" value="stripe" required> Stripe <br>
<input type="radio" name="payment_method" value="paypal" required> Paypal <br>
<button type="submit">Continue</button>
</fieldset>
</form>
{% endblock payment_details_content %}
{% endblock payment_details %}
{% block place_order %}
<div class="form-group clearfix">
<div class="row">
<div class="col-sm-4 offset-sm-8">
<br>
{% if request.session.payment_method == "oscar_paypal" %}
<a href="https://github.com/django-oscar/django-oscar-paypal">
{% if anon_checkout_allowed or request.user.is_authenticated %}
<a href="{% url 'paypal-redirect' %}">
<img src="https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif" align="left" style="margin-right:7px;">
</a>
{% endif %}
{% elif request.session.payment_method == "stripe" %}
<a href="{% url 'gateway_redirect' %}">Stripe</a>
{% elif request.session.payment_method == "paypal" %}
<script src="https://www.paypal.com/sdk/js?client-id={Client ID}¤cy=EUR"></script>
<div id="paypal-button-container"></div>
<script>
const basketId = "{{ basket.id }}";
paypal.Buttons({
async createOrder() {
const res = await fetch("/create-order/", {
method: "POST",
headers: {
"X-CSRFToken": "{{ csrf_token }}"
}
});
const data = await res.json();
return data.orderID;
},
async onApprove(data) {
const res = await fetch("/capture-order/", {
method: "POST",
headers: {
"X-CSRFToken": "{{ csrf_token }}",
"Content-Type": "application/json"
},
body: JSON.stringify({
orderID: data.orderID,
basketId: basketId
})
});
const details = await res.json();
if (!res.ok) {
console.error(details);
alert("Error capturing the payment.");
return;
}
window.location.href = "/success/" + basketId + "/";
},
async onCancel(data) {
window.location.href = "/cancel/" + basketId + "/";
}
}).render("#paypal-button-container");
</script>
{% endif %}
</div>
</div>
</div>
{% endblock place_order %}
Tested with: Django 5.2 Django-Oscar 4