How to create order in admin after payment is completed

I'm making a website where you buy stuff and pay through PayPal. I am done with the PayPal part now I am trying to get a situation where after the payment is complete in checkout the item purchased goes to orders in the admin.

This is the order model.py:

class Order (models.Model):
  product = models.ForeignKey(Coinpack, max_length=200, null=True, blank=True, on_delete = models.SET_NULL)   
  created =  models.DateTimeField(auto_now_add=True) 

this is the PayPal code part in checkout.html:

<script src="https://www.paypal.com/sdk/js?client-id=idexample&currency=USD"></script>

    <script>

function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const 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;
}
const csrftoken = getCookie('csrftoken');

        var total = '{{checkout.price}}'
        var productId = '{{checkout.id}}'


        function completeOrder(){
            var url = "{% url 'complete' %}"

            fecth(url, {
                method: 'POST',
                headers:{
                    'content-type':'aplication/json',
                    'X-CSRFToken': csrftoken,
                },
                body: JSON.stringify({'productId':productId})
            })
        }

        // Render the PayPal button into #paypal-button-container
        paypal.Buttons({

            // Set up the transaction
            createOrder: function(data, actions) {
                return actions.order.create({
                    purchase_units: [{
                        amount: {
                            value: total
                        }
                    }]
                });
            },

            // Finalize the transaction
            onApprove: function(data, actions) {
                return actions.order.capture().then(function(orderData) {
                    // Successful capture! For demo purposes:
                    completeOrder()
                    console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
                    var transaction = orderData.purchase_units[0].payments.captures[0];
                    alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details');

                  
                });
            }


        }).render('#paypal-button-container');
    </script>
</body>
</html>

    
    

and here is the views.py

def paymentComplete(request):
    body = json.loads(request.body)
    print('BODY:', body)
    product = checkout.objects.get(id=body['productId'])
    Order.objects.create(
        product=product
        )
       

    return JsonResponse('Payment completed!', safe=False)   

So i was following a tutorial but the tutorial and mine where different so i kinda got confused and i don't know what to do, pls help.

I also have the payment complete in the urls.py:

 path('complete/', views.paymentComplete, name="complete"),

Thank you.

Do not use actions.order.create() / actions.order.capture() to create and capture an order on the client side if you are then going to be doing server-side operations with the completed payment. Those JS functions are for simple use cases, not what you are trying to do.

Instead, use PayPal's v2/checkout/orders API and make two routes (url paths) on your server, one for 'Create Order' and one for 'Capture Order'. You could use the (recently deprecated) Checkout-PHP-SDK for the routes' API calls to PayPal, or your own HTTPS implementation of first getting an access token and then doing the call. Both of these routes should return/output only JSON data (no HTML or text). Inside the 2nd route, when the capture API is successful you should verify the amount was correct and store its resulting payment details in your database (particularly purchase_units[0].payments.captures[0].id, which is the PayPal transaction ID) and perform any necessary business logic (such as reserving product or sending an email) immediately before forwarding return JSON to the frontend caller. In the event of an error forward the JSON details of it as well, since the frontend must handle such cases.

Pair those 2 routes with this frontend approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server . (If you need to send any additional data from the client to the server, such as an items array or selected options, add a body parameter to the fetch with a value that is a JSON string or object)

Back to Top