0

Background:

Working in a Django application, I have a template that performs an action (makes a payement) using an external API. The API call is done in Javascript.

On Success, the API returns a response object. This works well on tests.

function makePayment(applicationAmount) {
    let paymentEngine = RmPaymentEngine.init({
        key: 'abcd'
        firstName: '{{ user.f_name }}',
        onSuccess: function(response) {
            console.log('callback Successful Response', response);
            // TODO: Add a function to post the payment records to the database
            // response from the API contains a dictionary like (read json) object
            // how can I get that response object in Python and use those response
            // object values to update a django model database records
        },
        onError: function(response) {
            console.log('callback Error Response', response);
            // TODO: Add a function to throw an error message
        },
        onClose: function() {
            console.log("closed");
        }
    });
}

Question:

How can I get that onSuccess response object variables in Python and use those response object values to update a django model database records?

Looked at this link: How do I return the response from an asynchronous call? but can't seem to implement my need.

I'd be happy to be directed to a simple resource that explains the procedure, not something very involved that takes hours to understand.

ArthurEzenwanne
  • 176
  • 2
  • 10
  • 1
    You cannot pass a Javascript object to Python, it's two differents languages, one running in the user's browser and the other on your server. Your best bet to process something when payment is successful is to call an internal API (in Python) into your `OnSuccess` function (Javascript) and pass expected arguments from `reponse` (Javascript) to your Python API via POST or GET arguments. – Arount Jan 29 '20 at 12:35
  • 1
    Inside OnSuccess fucntion, send the response using ajax to the backend to handle the things you want to do with python – Lag11 Jan 29 '20 at 13:05
  • Thanks @Arount. Do you have directions on how I could implement this or an example? – ArthurEzenwanne Jan 29 '20 at 17:26

1 Answers1

0

Using ideas from @Lag11 and @Arount and a wonderful tutorial here, I created 2 function based views, one to just serve the 'page' the other to handle the 'page post to DB'.

Summary, I did this in the template:

function makePayment(applicationAmount) {
    let paymentEngine = RmPaymentEngine.init({
        key: 'abcd'
        firstName: '{{ user.f_name }}',
        onSuccess: function(response) {
            console.log('callback Successful Response', response);

            // start new additions

            data = {
                "payer_email": "{{ user.email }}",
                "payer_phone": "{{ user.phone }}",
                "payment_amount_total": response.amount,
            }

            $.ajax({
                type: 'POST',
                url: "{% url 'post_purchase_form' %}",
                data: data,
                onSuccess: function (response) {
                    console.log('callback db post Successful', response);  
                },
                error: function (response) {
                    // alert the error if any error occured
                    alert(response);
                }
            })
            // end new additions
        },
        onError: function(response) {
            console.log('callback Error Response', response);
            // TODO: Add a function to throw an error message
        },
        onClose: function() {
            console.log("closed");
        }
    });
}

And this in the views.py:

def application_form_view(request):
    user = request.user
    form = ApplicationForm(instance=user)

    return render(request, 'application_form.html', {'form': form, 'user': user})

def post_application_form_view(request):
    # request should be ajax and method should be POST.
    if request.is_ajax and request.method == "POST":
        # get the form data
        form = ApplicationForm(request.POST, request.FILES)
        # save the data and after fetch the object in instance
        if form.is_valid():
            instance = form.save()
            # serialize in new FormPurchase object in json
            ser_instance = serializers.serialize('json', [ instance, ])
            # send to client side.
            return JsonResponse({"instance": ser_instance}, status=200)
        else:
            # some form errors occured.
            return JsonResponse({"error": form.errors}, status=400)

    # some error occured
    return JsonResponse({"error": "unknown errors"}, status=400)
ArthurEzenwanne
  • 176
  • 2
  • 10