Ajax post data to external URL don't receive callback javascript jquery - javascript

$(document).ready(function()
{
$("img").click(function()
{
$.post("https://.co.za/payweb3/initiate.trans",
{
PAYGATE_ID: "1029612100016",
REFERENCE: "Basket_ACDDDDA1-816E-48D7-A9DB-64ECAC97C76",
AMOUNT: "33900",
CURRENCY: "ZAR",
RETURN_URL: "https://www./checkout.asp",
TRANSACTION_DATE: "2019-10-21 9:17:9",
LOCALE: "en-za",
COUNTRY: "ZAF",
EMAIL: "dave#.co.za",
NOTIFY_URL: "https://www./thanks.asp",
CHECKSUM: "6251a4edec03bfcc86ad88112b10637d"
},
//Callback
function(data) {
alert( "Data Loaded: " + data );
//document.form1.submit();
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
I perform an ajax post to the external URL but don't receive the HTTP post reply. I have never had to do this before so I am a bit lost.
I adapted function from W3schools but bit in the dark...
This is the expected postback data from URL, I don't receive it. Please help.
PAYGATE_ID=1029612100016&PAY_REQUEST_ID=C7701B85-F479-DBB1-73BE-B1D57F17EAE0&REFERENCE=Basket_ACDDDDA1-816E-48D7-A9DB-64ECAC97C76&CHECKSUM=40c4daefb5e7d1eef6fa6a085789b89c
The callback doesn't work, not sure what I'm doing here?

$(document).ready(function()
{
$("img").click(function()
{
$.post("https://my.paymentgateway.com/some/endpoint",
{
PAYGATE_ID: "123456",
REFERENCE: "BASKET_REF_123",
AMOUNT: "33900",
CURRENCY: "ZAR",
RETURN_URL: "https://www.my.shop.com/checkout.asp",
TRANSACTION_DATE: "2019-10-21 9:17:9",
LOCALE: "en-za",
COUNTRY: "ZAF",
EMAIL: "dave#my.show.com",
NOTIFY_URL: "https://www.my.shop.com/thanks.asp",
CHECKSUM: "6251a4edec03bfcc86ad88112b10637d"
}).done((data)=> {
// Success handling
}).fail((xhr, status, error) => {
// Error handling
});
});
});
Try to use the done() and fail() handlers.

There are a couple of errors in your snippet:
You have no img in your HTML, so it cannot be clicked. I changed it to a button in my snippet.
You seem to have CORS problems - that means the server thinks you are not allowed to request the resource you try to get. I put http://cors-anywhere.herokuapp.com/ before your URL. Keep in mind that it's only a test solution, not for production. You either have to get the provider to set the correct headers (so accept your request), or you need to create a solution that goes around this problem. (So if you remove the URL part I put there, the snippet won't work.)
Something is not right with your request data, as it returns a ERROR=DATA_CHK message - this is not conventional, so I don't know what it means or implies.
$(document).ready(function() {
$('.button').on('click', function(e) {
e.preventDefault();
$.post("https://cors-anywhere.herokuapp.com/https://.co.za/initiate.trans", {
PAYGATE_ID: "123456",
REFERENCE: "Basket_ACDDDDA1-816E-48D7-A9DB-64ECAC97C76",
AMOUNT: "33900",
CURRENCY: "ZAR",
RETURN_URL: "https://www./checkout.asp",
TRANSACTION_DATE: "2019-10-21 9:17:9",
LOCALE: "en-za",
COUNTRY: "ZAF",
EMAIL: "dave#.co.za",
NOTIFY_URL: "https://www./thanks.asp",
CHECKSUM: "6251a4edec03bfcc86ad88112b10637d"
},
function(data) {
console.log('data:', data)
})
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button class="button">CLICK HERE</button>
More on CORS:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
https://www.codecademy.com/articles/what-is-cors

Related

Credimax hosted checkout payment always return "Unsuccessful Payment" in response?

I am using the Credimax hosted checkout payment gateway. After getting the session id from the server, I'm trying to do a test transaction using Credimax testing cards, but it always show the "Unsuccessful Payment" response from the server with 200 code.
The below link shows the official documentation.
https://credimax.gateway.mastercard.com/api/documentation/integrationGuidelines/hostedCheckout/integrationModelHostedCheckout.html?locale=en_US#x_obtainThePaymentResult
You can also check this documentation too,
https://credimax.gateway.mastercard.com/api/documentation/integrationGuidelines/index.html
This is what I have done so far.
<script type="text/javascript">
function errorCallback(error) {
console.log(JSON.stringify(error));
}
function cancelCallback() {
console.log('Payment cancelled');
}
$( document ).ready(function() {
console.log( "ready!" );
});
Checkout.configure({
merchant: 'E18009950',
session: {
id: 'SESSION0002013654327E6XXXX8'
},
interaction: {
operation : "PURCHASE",
merchant: {
name: 'XYZZZ',
address: {
line1: '200 Sample St',
line2: '1234 Example Town'
}
},
},
order: {
// amount : "12.0",
// currency : "BHD",
description: "Ordered Goods",
id: "2325487321"
}
});
</script>
This script loads the payment page successfully but throws this error at the beginning of the page;
Let me know if anyone has faced this issue and found any solution.

PayPal Smart Buttons Error: "Expected order id to be passed"

i have a problem : I'm trying to figure out what it is since last friday, I can't find any good docs and no clues on the internet, I share some screenshots if anyone could help it would be awesome, by the way my problem is that when clicking on the paypal smart buttons that I integrated, i get in the console "expected an order id to be passed" unfortunately I can't find what is that order id thing
paypal.Buttons({
style: {
shape: 'rect',
color: 'gold',
layout: 'vertical',
label: 'pay',
},
// Sets up the transaction when a payment button is clicked
createOrder: function (data, actions) {
var cartArray = shoppingCart.listCart();
// Call your backend to create the Checkout Session
$.ajax({
data: {
id: cookie
},
type: "POST",
url: "create.php",
success: function (response) {
response = JSON.parse(response)
surname = []
surname = response.name.split(/(\s+)/).filter(e => e.trim().length > 0)
const Cart5 = [];
function Cart(description, name, unit_amount, quantity) {
this.description = description;
this.name = name;
this.unit_amount = {
value: unit_amount,
currency_code: 'EUR'
};
this.quantity = quantity;
this.category = 'PHYSICAL_GOODS';
}
cartArray.forEach(element => {
var item = new Cart(element.id, element.name, element.price, element.count);
Cart5.push(item);
})
JSON.stringify(Cart5);
orderid = makeid(12);
const paymentData = {
//authorization: 'AdhHUVsamn71V-Xs5JZVpzL4v6ElEKiYywV6PwF7rRwCwRQ-AZHMcLELmvQuWlS1pL19iiCbbZUIupTt',
intent: "CAPTURE",
env: "production",
application_context: {
brand_name: "Skunker",
locale: "fr-FR",
landing_page: "BILLING",
shipping_preference: "SET_PROVIDED_ADDRESS",
},
purchase_units: [{
reference_id: orderid,
custom_id: orderid,
description: 'Achat chez Skunker.Store',
invoice_id: orderid,
payer: {
email_address: response.email,
},
amount: {
currency_code: "EUR",
value: shoppingCart.totalCart() - (shoppingCart.totalCart() * sessionStorage.getItem('discount') / 100) + 6.15,
breakdown: {
item_total: {
currency_code: "EUR",
value: shoppingCart.totalCart()
},
tax_total: {
currency_code: "EUR",
value: 0.20
},
shipping: {
currency_code: "EUR",
value: 5.95
},
handling: {
currency_code: "EUR",
value: 0.00
},
insurance: {
currency_code: "EUR",
value: 0.0
},
shipping_discount: {
currency_code: "EUR",
value: 0.00
}
}
},
items: Cart5,
shipping: {
method: "La Poste - Colissimo",
address: {
name: {
given_name: surname[0],
surname: surname[1],
},
address_line_1: response.address,
admin_area_2: response.city,
postal_code: response.postalCode,
country_code: "FR"
},
phone_number: {
country_code: '33',
national_number: response.tel,
}
}
}]
}
return actions.order.create(paymentData);
}
})
},
// Finalize the transaction after payer approval
onApprove: function (data, actions) {
return actions.order.capture().then(function (orderData) {
// Full available details
console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
// 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>';
// Successful capture! For dev/demo purposes:
$.ajax({
data: JSON.stringify(paymentData),
type: "POST",
url: "https://skunker.store/scripts/paid.php",
success: function (response) {}
})
// When ready to go live, remove the alert and show a success message within this page. For example:
// var 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');
});
},
onError: function (err) {
console.log(err);
},
}).render('#payBtn');
And this is the error I get :
Error: Expected an order id to be passed
at https://www.sandbox.paypal.com/smart/buttons?style.label=pay&style.layout=vertical&style.color=gold&style.shape=rect&style.tagline=false&style.menuPlacement=below&components.0=buttons&locale.country=FR&locale.lang=fr&sdkMeta=eyJ1cmwiOiJodHRwczovL3d3dy5wYXlwYWwuY29tL3Nkay9qcz9jbGllbnQtaWQ9QVhTMWxLcXR2cjkzbDVkYlFPTE9nclJCYlNKMWt0cmNnYkpMZnJjRWEyckhING1ZYzVvWlQ1dmxpWUZDMnRobUFlcDVic1h4RmF1WEJ1cDMmY3VycmVuY3k9RVVSIiwiYXR0cnMiOnsiZGF0YS1zZGstaW50ZWdyYXRpb24tc291cmNlIjoiYnV0dG9uLWZhY3RvcnkiLCJkYXRhLXVpZCI6InVpZF9tdmh4dGh4aHhlYW13bHJzYXVna2dqeGRmcmpqenMifX0&clientID=AXS1lKqtvr93l5dbQOLOgrRBbSJ1ktrcgbJLfrcEa2rHH4mYc5oZT5vliYFC2thmAep5bsXxFauXBup3&sdkCorrelationID=f540177905bdc&storageID=uid_dbb0ba13c9_mtq6mzg6ndi&sessionID=uid_0e8f15ce50_mtq6ntq6nte&buttonSessionID=uid_1e5135ffcf_mtq6ntq6nte&env=sandbox&buttonSize=huge&fundingEligibility=eyJwYXlwYWwiOnsiZWxpZ2libGUiOnRydWUsInZhdWx0YWJsZSI6dHJ1ZX0sInBheWxhdGVyIjp7ImVsaWdpYmxlIjpmYWxzZSwibWVyY2hhbnRDb25maWdIYXNoIjoiZmQxNWMxYTBkNTFiYjBlMTRjODkxYTUzNDYwZTZiYWU1MDkyZmEzZCIsInByb2R1Y3RzIjp7InBheUluMyI6eyJlbGlnaWJsZSI6ZmFsc2UsInZhcmlhbnQiOm51bGx9LCJwYXlJbjQiOnsiZWxpZ2libGUiOmZhbHNlLCJ2YXJpYW50IjpudWxsfSwicGF5bGF0ZXIiOnsiZWxpZ2libGUiOmZhbHNlLCJ2YXJpYW50IjpudWxsfX19LCJjYXJkIjp7ImVsaWdpYmxlIjp0cnVlLCJicmFuZGVkIjp0cnVlLCJpbnN0YWxsbWVudHMiOmZhbHNlLCJ2ZW5kb3JzIjp7InZpc2EiOnsiZWxpZ2libGUiOnRydWUsInZhdWx0YWJsZSI6dHJ1ZX0sIm1hc3RlcmNhcmQiOnsiZWxpZ2libGUiOnRydWUsInZhdWx0YWJsZSI6dHJ1ZX0sImFtZXgiOnsiZWxpZ2libGUiOnRydWUsInZhdWx0YWJsZSI6dHJ1ZX0sImRpc2NvdmVyIjp7ImVsaWdpYmxlIjpmYWxz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ablePaylater=false&experiment.enableVenmoAppLabel=false&flow=purchase&currency=EUR&intent=capture&commit=true&vault=false&renderedButtons.0=paypal&renderedButtons.1=card&debug=false&applePaySupport=false&supportsPopups=true&supportedNativeBrowser=false&allowBillingPayments=true:1338:178001
I tried putting only the amount into the data and it still doesn't work, I also tried to add an order ID but it doesn't work
This is a bit of a mess, you're doing an ajax call to a "create.php" on your server, but for some reason not calling the PayPal API from there (with the Checkout-PHP-SDK or similar), but are instead using that response to then create an order from the client-side (which is what actions.order.create does)
This doesn't make any real sense. If you are using a server, you should have two routes: create.php and capture.php?id=XXXXXXXXXXXXXXX" (use a JSON body parameter to fetch rather than GET URL string, if desired) both of which communicate with the PayPal API themselves, to create and capture an order respectively. It does not make sense to combine your own server operations with JS SDK client-side methods.
So, you should switch over completely to this server pattern example: https://developer.paypal.com/demo/checkout/#/pattern/server , and in each of the respective routes that are called (create.php / capture.php or similar) you can either write your own HTTPS calls for the PayPal API, or use the Checkout-PHP-SDK to abstract them as desired, and return the JSON response to the fetch caller.
I do not recommend trying to get what you have to work, but the main reason it is not working is a failure to return a JavaScript Promise properly. You are invoking an asynchronous $.ajax and not returning anything after doing so, hence the error "Expected an order id to be passed" since you actually returned nothing (even though you think you did); in reality you just spun off an asynchronous $.ajax to do its own thing and that function's result is never fed back (nor would it be if you returned its result, since it uses a callback rather than promises).
The simplest way to get a promise when calling your own server routes is to use fetch instead of $.ajax, then you can just return the result of the fetch. It is theoretically possible to turn a $.ajax callback into a promise and return that, but I would not spend any time on this if I were you; the built-in browser fetch creates a promise for you and is preferred in modern JS.

Razor Pay checkout form not appearing and giving error as not a function

I am implementing razorPay payment in angular7 project.I am trying to open checkout form by creating a single instance of Razorpay and accessing its function open(). But instead it is throwing error "is not a function". I couldn't find any proper documentation regarding this.
However, If I try to simple create payment using razorpay, it opens up the window but there is no option for user to choose any method and hence it throws error again because directly creating payment will not add up any card(if method is 'card'). So it is necessary to open checkout form.
Here is my function I am using, firstly i create order on server to generate id and then proceed to payment.
buyPlan() {
let postdata = {
amount: 1000,
currency: "INR",
receipt: "1",
notes: {},
payment_capture: true
}
this.common.createOrder(postdata).subscribe(
(result: any) => {
console.log(result)
var razorpay = new this.winRef.nativeWindow.Razorpay({
key: 'dashboard_key_id',
image: 'assets/images/logo-1.png',
});
var data = {
amount: 1000,
currency: "INR",
email: 'abc#example.com',
contact: '9874563210',
notes: {
address: 'Sector 65 Delhi',
},
method: 'card',
order_id: result.data.id,
handler: function (response) {
alert(response.razorpay_payment_id);
}
};
razorpay.open();
}, (err: HttpErrorResponse) => {
}
);
}
For Custom Integration
Remove:
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
from index.html file
and put:
<script type="text/javascript" src="https://checkout.razorpay.com/v1/razorpay.js"></script>
inside <head></head> tag

Stripe - Not charging card

I've setup a stripe custom checkout using javascript. Every parameter goes through, I receive a status 200 in the log when we make a payment. Everything looks like it goes through. However the amount remains as "0" in the Parsed Request Query Parameters and not charging the card.
I've gone over documentation for hours and can't get my head around the issue.
<script src="https://checkout.stripe.com/checkout.js"></script>
<script>
var pinId = "<%= #id %>";
var from = "<%= #from %>";
var content = "Supersize+me";
var handler = StripeCheckout.configure({
key: 'Published-Key',
image: '/assets/campusboard-logo.png',
token: function(token, args) {
$.getJSON( "purchased/"+pinId )
.done(function( data ) {
window.location = "http://"+window.location.host+"/pins/"+pinId+"?utm_source=Purchased&utm_medium="+from+"&utm_campaign=Featured%20Pins&utm_content="+content;
})
.fail(function( jqxhr, textStatus, error ) {
alert("We've encountered a problem with the transaction. Please try again.");
});
}
});
document.getElementById('ssm').addEventListener('click', function(e) {
// Open Checkout with further options
handler.open({
name: 'CampusBoard',
description: 'Featured Pin (£29.00)',
amount: "100",
currency: 'GBP',
panelLabel: 'Supersize my Pin'
});
e.preventDefault();
});
document.getElementById('mmh').addEventListener('click', function(e) {
// Open Checkout with further options
handler.open({
name: 'CampusBoard',
description: 'Featured Pin (£59.00)',
amount: 5900,
currency: 'GBP',
panelLabel: 'Make my Pin Huge'
});
content = "Make+me+huge";
e.preventDefault();
});
</script>
Can someone see where I'm going wrong?
Stripe Checkout is just a well-done pre-made payment form. You actually have to create a Charge object on your server using your Stripe secret API key. Follow these tutorials for your specific language.
You are passing the amount as a string whereas I think stripe is expecting it as a number. So:
handler.open({
...
amount: 100,
...
});

Load data into a Backbone collection from JSON file?

I'm trying to load some data into a Backbone Collection from a local JSON file, using this very basic code:
window.Student = Backbone.Model.extend({
});
window.Students = Backbone.Collection.extend({
model: Student,
});
window.AllStudents = new Students();
AllStudents.fetch({ url: "/init.json"});
console.log('AllStudents', AllStudents);
In the console statement, AllStudents is empty. But init.json is definitely being loaded. It looks like this:
[
{ text: "Amy", grade: 5 },
{ text: "Angeline", grade: 26 },
{ text: "Anna", grade: 55 }
]
What am I doing wrong?
UPDATE: I've also tried adding a reset listener above the .fetch() call, but that's not firing either:
AllStudents.bind("reset", function() {
alert('hello world');
});
AllStudents.fetch({ url: "/init.json"});
No alert appears.
UPDATE 2: Trying this script (reproduced here in full):
$(function(){
window.Student = Backbone.Model.extend({
});
window.Students = Backbone.Collection.extend({
model: Student,
});
window.AllStudents = new Students();
AllStudents.url = "/init.json";
AllStudents.bind('reset', function() {
console.log('hello world');
});
AllStudents.fetch();
AllStudents.fetch({ url: "/init.json", success: function() {
console.log(AllStudents);
}});
AllStudents.fetch({ url: "/init.json" }).complete(function() {
console.log(AllStudents);
});
});
Only one console statement even appears, in the third fetch() call, and it's an empty object.
I'm now absolutely baffled. What am I doing wrong?
The JSON file is being served as application/json, so it's nothing to do with that.
The attribute names and non-numeric attribute values in your JSON file must be double quoted (" ") . Single quotes or no-quotes produces errors and response object is not created that could be used to create the models and populate the collection.
So. If you change the json file content to :
[
{ "text": "Amy", grade: 5 },
{ "text": "Angeline", grade: 26 },
{ "text": "Anna", grade: 55 }
]
you should see the non-empty collection object.
You can change your code to see both success and failure as below:
AllStudents.fetch({
url: "/init.json",
success: function() {
console.log("JSON file load was successful", AllStudents);
},
error: function(){
console.log('There was some error in loading and processing the JSON file');
}
});
For more details, probably it will be a good idea to look in to the way ajax response objects are created.
I/O operations in javascript are almost always asynchronous, and so it is with Backbone as well. That means that just because AllStudents.fetch has returned, it hasn't fetched the data yet. So when you hit your console.log statement, the resources has not yet been fetched. You should pass a callback to fetch:
AllStudents.fetch({ url: "/init.json", success: function() {
console.log(AllStudents);
}});
Or optionally, use the new promise feature in jQuery (fetch will return a promise):
AllStudents.fetch({ url: "/init.json" }).complete(function() {
console.log(AllStudents);
});
fetch() returns a 'success' notification as already stated, but that just means that the server request was successful. fetch() brought back some JSON, but it still needs to stuff it into the collection.
The collection fires a 'reset' event when it's contents have been updated. That is when the collection is ready to use...
AllStudents.bind('reset', function () { alert('AllStudents bind event fired.'); });
It looks like you had this in your first update. The only thing I did differently was to put fetch() in front of the event binding.
I think you need to add {add:true} to the options of fetch,
if you assigned the fetch to a variable, you would get the result as well,
but then its not inside the collection you wanted

Categories

Resources