In my E-commerce project, when a user adds items to the cart and executes a payment via PayPal, a PayPal window is opened and after submitting payment the windows are closed but the website page remains to the payment page where there is still items in the cart because the page is not refreshed.
So my question is how do I set the ajax javascript to redirect the website page to go to another link called: "order_completed.html" that I have set with Executed order details, instead of show a success message to the buyer from script.
To just elaborate a little more to be more clear
I have tried adding
// similar behavior as an HTTP redirect
window.location.replace("/");
and that is what happened it returned me to the home page without refreshing but still this is not what I am trying to do, what I am trying to do I to render the following as in the view:
return render(request, "order_completed.html", {'order': order})
so that I can add the Order reference no. for the successful purchase.
I am not sure how to achieve this.
Here is the views.html:
def payment_complete(request):
body = json.loads(request.body)
order = Order.objects.get(
user=request.user, ordered=False, id=body['orderID'])
payment = Payment(
user=request.user,
stripe_charge_id=body['payID'],
amount=order.grand_total()
)
payment.save()
# assign the payment to order
order.payment = payment
order.ordered = True
order.ref_code = create_ref_code()
order.save()
messages.success(request, "Your Order was Successful ! ")
return render(request, "order_completed.html", {'order': order})
class PaymentView(View):
def get(self, *args, **kwargs):
# order
order = Order.objects.get(user=self.request.user, ordered=False)
if order.billing_address:
context = {
'order': order,
'DISPLAY_COUPON_FORM': False
}
return render(self.request, "payment.html", context)
else:
messages.warning(
self.request, "You have not added a billing address")
return redirect("core:checkout")
# `source` is obtained with Stripe.js; see https://stripe.com/docs/payments/accept-a-payment-charges#web-create
# -token
def post(self, *args, **kwargs):
order = Order.objects.get(user=self.request.user, ordered=False)
token = self.request.POST.get('stripeToken')
amount = int(order.grand_total() * 100)
try:
charge = stripe.Charge.create(
amount=amount, # cents
currency="usd",
source=token,
)
# create payment
payment = Payment()
payment.stripe_charge_id = charge['id']
payment.user = self.request.user
payment.amount = order.grand_total()
payment.save()
# assign the payment to the order
order_items = order.items.all()
order_items.update(ordered=True)
for item in order_items:
item.save()
order.ordered = True
order.payment = payment
order.ref_code = create_ref_code()
order.save()
messages.success(self.request, "Your Order was Successful ! ")
return render(self.request, "order_completed.html", {'order': order})
here is the PayPal script:
<!--Paypal Script-->
<script>
// Render the PayPal button into #paypal-button-container
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== "") {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === name + "=") {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie("csrftoken");
var orderID = "{{order.id}}";
var amount = "{{order.grand_total|floatformat:2}}";
var url = "{% url 'core:payment_complete' %}";
paypal.Buttons({
style: {
color: "blue",
shape: "pill",
label: "pay",
height: 40,
},
// Set up the transaction
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: amount,
}
}]
});
},
// Finalize the transaction
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
console.log(details);
sendData();
function sendData() {
fetch(url, {
method: "POST",
headers: {
"Content-type": "application/json",
"X-CSRFToken": csrftoken,
},
body: JSON.stringify({ orderID: orderID, payID: details.id }),
});
}
// Show a success message to the buyer
alert('Transaction completed by ' + details.payer.name.given_name + '!');
});
}
}).render('#paypal-button-container');
</script>
<!--Paypal Script-->