Payment information from JavaScript to Django views - javascript

I integrating a payment processor for my django app and now if payment was successful, I have a call back function written in JavaScript inside of the HTML and that gives me the transaction reference id. I want to send that reference id to my Django views for final verification.
I have tried almost all related solutions here on Stack Overflow none seems to solve my exact problem. The only thing I can do is to console.log() the reference id.
Here is my code
inside html
<script>
function payWithPaystack(){
var handler = PaystackPop.setup({
key: 'pk_test_somekey',
email: 'customer#email.com',
plan: "PLN_testcode",
metadata: {
custom_fields: [
{
display_name: "Mobile Number",
variable_name: "mobile_number",
value: "+2348012345678"
}
]
},
// if transaction was successful
callback: function(response){
var ref_ = response.reference
console.log(ref_)
},
onClose: function(){
alert('window closed');
}
});
handler.openIframe();
}
</script>
django views.py
def payment(request):
# here a variable will be capture the ref_
return render(request, template, context={})

You can write ajax call inside your callback function.
function PaymentCompleted(){
$.ajax({
type:"POST",
url :"/payment-completed/",
data:"reference_id=reference_id_here",
datatype:"json",
error:function(data){alert('Error:'+data);}
success:function(data){alert('OK!'+data.message+','+data.code);}
});
}
And at Django views:
from django.utils import simplejson
def paymnet_completed(request):
print "ajax request called"
print request.GET['reference_id']
return_dict = {'message': 'Payment Successful','code':200}
json = simplejson.dumps(return_dict)
return HttpResponse(json, mimetype="application/x-javascript")
I Hope this might have helped.

Related

Having issues understanding flow - HTML form data handling by vue and axios

I am new to Vue and Axios and trying to use it in Salesforce Marketing Cloud - Cloud pages. Basically there are 3 parts,
HTML + vue page : this is a form page, where the user is asked to input the automation name and click on send button
App.js : this is build using axios and Vue.
Form-hander.js (backend) : SSJS code that runs the automation.
I referred this document to build this setup -https://ampscript.xyz/how-tos/how-to-start-status-of-automation-from-marketingcloud-form/. I understand the Form-hander.js (ssjs) code and this can be skipped.
What I am not able to understand is the flow of App.js, could anyone please explain me what is happening here.
I understand that on click of send button, the function in App.js - validateForm is called. Here after I don’t understand the flow of the code.
From App.js is the form-handler code called ? OR the post method used in the HTML page is directly called the form-handler page and staring the automation?
Here is the code of app.js. Can some explain to me in simple terms the flow of this code, would be really helpful.
new Vue({
el: '#app',
data: {
status: 100,
form: {
name: 'My Test Automation',
context: 'perform'
},
endpoint: '',
message: ''
},
watch: {
status: function () {
if(this.status == 201 || this.status == 102) {
this.form.context = 'check';
} else {
this.form.context = 'perform';
}
}
},
mounted: function() {
this.endpoint = this.$refs.form.getAttribute('action');
},
methods: {
sendFormData: function() {
this.status = 101;
var $this = this;
axios({
method: 'POST',
url: $this.endpoint,
data: $this.form,
validateStatus: function() { return true }
}).then(function(result) {
$this.status = result.data.Status;
$this.message = result.data.Message;
$this.checkStatus();
}).catch(function(error) {
console.error(error);
});
},
checkStatus: function() {
var $this = this;
var intervalID = setInterval(function() {
axios({
method: 'POST',
url: $this.endpoint,
data: $this.form,
validateStatus: function() { return true }
}).then(function(result) {
$this.status = result.data.Status;
$this.message = result.data.Message;
if($this.status == 200 || $this.status == 500) {
clearInterval(intervalID);
}
}).catch(function(error) {
console.error(error);
});
}, 10000);
},
validateForm: function() {
if (this.$refs.form.checkValidity() !== false) {
this.sendFormData();
}
this.$refs.form.classList.add('was-validated');
}
}
})
Let me explain you the flow of the code you posted :
Once component mounted, The first method which is getting called is mounted(). In this method you are fetching the endopint binded to the action attribute in your form html element and binding that in a data variable via this.endpoint.
Now, you are calling validateForm() method on click of submit button to validate the input fields. If validation pass, you are calling sendFormData() method to make an POST API call.
After getting the response, you added a watcher on status to update the form.context value based on the status code you received from an API response.
At the end, you are calling a checkStatus() method on success of axios call and in this checkStatus() method you are again making an POST API call after every 10 seconds and following step 3.
When the components is mounted, you run the form binded action on (submit?)
The action is probably binded to the sendFormData function(in methods)
Inside sendFormData, there is the setup of the axios request, followed be a then callback which handles the response from the request
The checkStatus function is called inside the "then" block
Sends the same data back to the server every 10 seconds if the previous response
doesn't have status code other than 200 or 500.
ValidateForm is may binded to some onInput or onChange event on the template
** The watcher is always looking for the status code and updates a form context

framework7 component page not working with real database query

In framework7 (latest version) there are some sample pages for e.g. page-loader-component.html. This page having -
<p>Hello {{name}}</p>
and at bottom, there is script
return {
data: function(){
return{
name: "Peter"
}
}
}
Now when the page is accessed, it displays - Hello Peter
Question is I want to fetch name from real database from my server. So I made this changes -
app.request.post(
'http://domain-name/page.php',
{userid: 2},
function(response){
var response = JSON.parse(response);
console.log(response); //console log shows {name: "Peter"}
return response
}
);
return {
data: function(){
return response //console log shows response is not defined
}
}
Now when try to access the page, it throws errors (in console) - ReferenceError: response is not defined. In console my request query is OK, it show - {name: "Peter"}
I did return response as well as tried replacing the position of function as well as tried many other possible fix suggested on stackoverflow.
I think one function is running before other one make finish database queries. I am not expert (just average). So please someone suggest.
I have also tried to access the page through routes.js as example given in request-and-load.html but still reference error.
return response is inside the data: section. The request is not, and they cannot reach each other.
Put the gathering of data inside the data function. You also want to save the response outside of the request function. To make sure the response variable is reachable. I'd also personally move the request itself to be defined in a separate location for usage outside of this one instances.
File: custom.js
requests = {
GetName: function () {
app.request.post(
'http://domain-name/page.php',
{ userid: 2 },
function (response) {
var response = JSON.parse(response);
console.log(response); //console log shows {name: "Peter"}
return response
}
);
},
GetNameDynamic: function (id) {
app.request.post(
'http://domain-name/page.php',
{ userid: id},
function (response) {
var response = JSON.parse(response);
console.log(response);
return response
}
);
}
}
Then inside the data: section call that function and save as a variable. Pass that in the data return.
data: function () {
// Must return an object
var result = requests.GetName();
return {
name: result.name,
}
},
There are other ways/locations to accomplish this. One being the async in the route as the other user mentioned.
In the routes array, just change the path and componentUrl to the correct ones.
{
path: '/post-entity-group/:type/:group/:public/',
async: function (routeTo, routeFrom, resolve, reject) {
var result = requests.GetName();
resolve(
{
componentUrl: './pages/post-entity.html',
},
{
context: {
name: result.name,
}
}
)
}
},
I think you have to pass by async routeto load page context (c.f. F7 doc)
You will be able to load datas via resolve callback
Maybe an example can help : async data for page

How to access the trello API from within a powerup?

How can I make queries against the trello API from within a powerup? This seems like such an obvious question but it doesn't seem to be covered that I can find.
My simple powerup looks like this so far:
var boardButtonCallback = function(t){
return t.popup({
title: 'Tools',
items: [
{
text: 'Hide Duplicates',
callback: function(t){
var cardQueryCb = function(result){
console.log(result);
}
var cardQ = 'https://trello.com/1/boards/[board_id]/cards/all';
fetch(cardQ).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
});
return t.cards('id', 'name')
.then(cardQueryCb);
}
}
]
});
};
TrelloPowerUp.initialize({
'board-buttons': function(t, options){
return [{
text: 'Duplicates',
callback: boardButtonCallback
}];
}
});
The response object after the call to fetch says the call is unauthorized.
I would have thought that calling this code from within the context of the power up would be considered authorized. While I'm logged into trello, I'm able to put that address into my browser and get a valid response - how come the javascript call doesn't also result in a valid response?
More importantly, how can I get a successful response from that URL?
Since your power-up is run through an iframe, it's not actually coming from the Trello page itself so you need to specify your API key and token in the GET URL.
Example:
https://api.trello.com/1/boards/560bf4298b3dda300c18d09c?fields=name,url&key={YOUR-API-KEY}&token={AN-OAUTH-TOKEN}
The info for getting your API key and token can be found here: https://trello.readme.io/v1.0/reference#api-key-tokens

Triggering Javascript Code from PHP Laravel Controller

I'm using OAuth for login in my Laravel Controller. Its working fine but the thing is when the user is registered for the first time, I wanna trigger the HTML 5 geolocation API to fetch the user's current location and do some mixpanel stuff. Earlier I was using AJAX in the JS for the login so there was no such problem but now that I've implemented a complete server side solution, I'm stuck with this one problem.
The Laravel Controller code looks something like this :
function callback(){
\\ fetch the access token and graph data
if($res = \Auth::mjAuthenticate('facebook', $fbData)){
$user = \Auth::scope()->getUser();
return \Redirect::to('events');
}
if (\Auth::mjRegister('facebook', $fbData)) {
$user = \Auth::scope()->getUser();
return \Redirect::to('events');
}
return $this->handleFailure('Some Problem Occured');
}
The Earlier JS Code was :
ajax
.post('auth/login', {
data: {
oauth_provider: 'facebook',
oauth_token: accessToken
},
cache: false
})
.done(function(data) {
mixpanel.track('User Logged In', {
id: data.resource.id,
provider: 'Facebook',
email: data.resource.email,
first_name: data.resource.first_name,
last_name: data.resource.last_name
});
if (data.msg == 'Resource registered') {
if(navigator.geolocation){
// Prompt for Allow Deny Geolocation popup.
}
}
});

What is the best way to add server variables (PHP) in to the Backbone.model using require.js?

I'm not sure what is the elegant way to pass server variables in to my Model.
For example, i have an id of user that has to be implemented on my Model. But seems like Backbone with require are not able to do that.
My two options are:
Get a json file with Ajax.
Add the variable on my index.php as a global.
Someone know if exists a other way. Native on the clases?
Trying to make work the example of backbonetutorials. I am not able to throw a callback when the method fetch().
$(document).ready(function() {
var Timer = Backbone.Model.extend({
urlRoot : 'timeserver/',
defaults: {
name: '',
email: ''
}
});
var timer = new Timer({id:1});
timer.fetch({
success: function(data) {
alert('success')
},
fail: function(model, response) {
alert('fail');
},
sync: function(data) {
alert('sync')
}
});
});
The ajax request it has been threw. But does not work at all. Because any alert its dispatched.
var UserModel = Backbone.Model.extend({
urlRoot: '/user',
defaults: {
name: '',
email: ''
}
});
// Here we have set the `id` of the model
var user = new Usermodel({id: 1});
// The fetch below will perform GET /user/1
// The server should return the id, name and email from the database
user.fetch({
success: function (user) {
console.log(user);
}
})
The server will reply with a json object then you can leave the rendering part for your backbone. Based on a template for the user.
You may also want to check these out: http://backbonetutorials.com/

Categories

Resources