PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 4, 2022

[FIXED] how to write the fetch in that case - django app payment

 July 04, 2022     django, javascript, paypal, python     No comments   

Issue

hello I am working on a django app 'my app is about paying for someone service' client will access to the page and click on their selected person and then they will fill a form and click on get the service and then people who work in the plateform will go to another page and they can find a list of forms of people who want to get their service .... but I want the form not to be posted until the payment is done so my database will not be fall. so this is my views.py I have actually 2 functions :

#here where client can select people they are willing to take service from 
@login_required(login_url='login')
def pSelected(request,slug):
    profile = get_object_or_404(Profile,slug=slug)

    form = MessageForm()
    if request.method == 'POST':
        form = MessageForm(request.POST,request.user)
        form.sender = request.user.username
        form.receiver = request.POST.get('receiver', '')
        if form.is_valid():
            form.sender = request.user.username
            form.receiver = request.POST.get('receiver', '')
            messages.success(request, f'succed')
            form.save()
            print(form.sender,form.receiver)
    else:
        form = MessageForm()
    return render(request,'base/p-selected.html',context)
#here for workers in the platefrorm 
@login_required(login_url='login')
def giveService(request):
    requests = Message.objects.all().order_by('-id')

    context={'requests':requests}
    return render(request, 'base/giveService.html',context)

now in my p-selected.html

<form>
<!--I have here for example a form method post *inside of my form I have input get and payment with paypal -->

<input type="submit" value="GET" class="btn get" style="outline: none; margin:auto;"/>

<div id="paypal-button-container"></div>

</form>
<!-- Include the PayPal JavaScript SDK -->
    <script src="https://www.paypal.com/sdk/js?client-id=I-Already-Put-Here-The-Id&currency=USD"></script>

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

            // Call your server to set up the transaction
            createOrder: function(data, actions) {
                return fetch('/demo/checkout/api/paypal/order/create/', {
                    method: 'post'
                }).then(function(res) {
                    return res.json();
                }).then(function(orderData) {
                    return orderData.id;
                });
            },

            // Call your server to finalize the transaction
            onApprove: function(data, actions) {
                return fetch('/demo/checkout/api/paypal/order/' + data.orderID + '/capture/', {
                    method: 'post'
                }).then(function(res) {
                    return res.json();
                }).then(function(orderData) {
                    // Three cases to handle:
                    //   (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
                    //   (2) Other non-recoverable errors -> Show a failure message
                    //   (3) Successful transaction -> Show confirmation or thank you

                    // This example reads a v2/checkout/orders capture response, propagated from the server
                    // You could use a different API or structure for your 'orderData'
                    var errorDetail = Array.isArray(orderData.details) && orderData.details[0];

                    if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
                        return actions.restart(); // Recoverable state, per:
                        // https://developer.paypal.com/docs/checkout/integration-features/funding-failure/
                    }

                    if (errorDetail) {
                        var msg = 'Sorry, your transaction could not be processed.';
                        if (errorDetail.description) msg += '\n\n' + errorDetail.description;
                        if (orderData.debug_id) msg += ' (' + orderData.debug_id + ')';
                        return alert(msg); // Show a failure message (try to avoid alerts in production environments)
                    }

                    // Successful capture! For demo purposes:
                    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');

                    // Replace the above to show a success message within this page, e.g.
                    // const element = document.getElementById('paypal-button-container');
                    // element.innerHTML = '';
                    // element.innerHTML = '<h3>Thank you for your payment!</h3>';
                    // Or go to another URL:  actions.redirect('thank_you.html');
                });
            }

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

I want the workers in plateform to not receive the form until the payment is done by clients how I can do it in that case I already tried but I really couldn't succed many times maybe because I am not that good in js ..I hope you guys can help me in that I won't forget your help thank you so much.


Solution

The PayPal button code in your example is for a server-side integration. To use it, the first thing you need to do is make two actual django routes on your server (one for create, one for capture) that call the PayPal API and return JSON data of the result.

Next you need to change the fetch('/demo/checkout/api/paypal/order/' in the JS sample to actually point to the local paths of those working routes you made.

(Alternatively, instead of doing thisroute and API work you can switch over to a client-side JS integration ... not recommended, client-side payments are for much simpler use cases than yours that don't need to trigger any server side code on success, like saving a record of the transaction or saving form data as in your case)

Once you have a working PayPal button to simply process the payment (either server or client side), next you need to make use of your form data from the onApprove function. The simplest thing to do would be to trigger form submission with JS, however this is bad since you could receive completed payments without getting that information received and processed correctly.

The best solution is to serialize the form data into a JSON object (using JS), and include it in the body of the fetch request to the capture order route. That way your capture route can validate all the form data before capturing, do the capture, and on success immediately add the transaction record and submitted form data to your django backend, right before returning that JSON response to the calling JS fetch.



Answered By - Preston PHX
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing