Reputation: 113
I am writing an online store based on the Django 3 By Example 3rd Edition book. I encountered a problem with the book's codes in the payment section, I searched the internet and updated some of the codes, but I still have a problem! After filling out the debit card form, when I click on the "pay now!" button, I am not redirected to the Don page!
process.html
{% extends "shop/base.html" %} {% block title %} Pay by credit card {% endblock %} {% block sidenavigation %} {% endblock %} {% block content %}Pay by credit card
<form method="post" autocomplete="off"> {% if braintree_error %} <div class="alert alert-danger fade in"> <button class="close" data-dismiss="alert">×</button> {{ braintree_error|safe }} </div> {% endif %} <div class="braintree-notifications"></div> <div id="braintree-dropin"></div> <input style="background-color: #0783ca" id="submit-button" class="btn btn-success btn-lg btn-block" type="button" value="Pay now!"/> </form> <script> var braintree_client_token = "{{ client_token}}"; var button = document.querySelector('#submit-button'); braintree.dropin.create({ authorization: "{{client_token}}", container: '#braintree-dropin', card: { cardholderName: { required: false } } }, function (createErr, instance) { button.addEventListener('click', function () { instance.requestPaymentMethod(function (err, payload) { $.ajax({ type: 'POST', url: '{% url "payment:process" %}', data: { 'paymentMethodNonce': payload.nonce, 'csrfmiddlewaretoken': '{{ csrf_token }}' } }).done(function (result) { //do accordingly }); }); }); }); </script>
{% endblock %}
process view:
def payment_process(request):
"""The view that processes the payment"""
order_id = request.session.get('order_id')
order = get_object_or_404(Order, id=order_id)
total_cost = order.get_total_cost()
print(f'ORDER=== {order.first_name}')
if request.method == 'POST':
print('---------Post------------')
# retrieve nonce
# retrieve nonce
nonce = request.POST.get('paymentMethodNonce', None)
# # create User
customer_kwargs = {
# "customer_id": order.braintree_id
"first_name": order.first_name,
"last_name": order.last_name,
"email": order.email
}
customer_create = gateway.customer.create(customer_kwargs)
customer_id = customer_create.customer.id
# create and submit transaction
result = gateway.transaction.sale({
'amount': f'{total_cost:.2f}',
'payment_method_nonce': nonce,
'options': {
'submit_for_settlement': True
}
})
print(f'Result----{result}')
if result.is_success:
# mark the order as paid
print(f'------Success----')
order.paid = True
# store the unique transaction id
order.braintree_id = result.transaction.id
order.save()
return redirect('payment:done')
else:
return redirect('payment:canceled')
else:
print('---------Get----------')
# generate token
client_token = gateway.client_token.generate()
return render(
request,
'payment/process.html',
{
'order': order,
'client_token': client_token
}
)
Upvotes: 0
Views: 193