ajax conflict when trying to integrate paypal
I’m trying to integrate paypal payment, but I have a problem since I’m using ajax to send the shopping cart data to the create order. It show me this alert: Failed to load https://linktothepaypallogin Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost’ is therefore not allowed access. Create order php:
function validate_order()< $.ajax(< url: "create_order.php", >); >
I’m sure the problem is ajax, because if I try with submit it works as intended.
1,911 1 1 gold badge 15 15 silver badges 31 31 bronze badges
asked Sep 5, 2018 at 0:00
1 2 2 bronze badges
looks like you’re trying to access «linktothepaypallogin» in an XMLHttpRequest on the browser, and due to the type of request, the browser performs a CORS preflight, which is failing . none of the code you’ve shown would result in that error
Sep 5, 2018 at 0:27
yes that’s the problem I don’t know how can I make the browser properly redirect me to the paypal link instead of showing me that error.
Sep 5, 2018 at 2:45
don’t use XHR for cross origin requests that are not allowed by the other domain — the code in the question has nothing to do with your error — so, it’s hard to actually help at all
Sep 5, 2018 at 2:55
well I was thinking it was something with ajax, cause if i use a input submit to the same create.php it works as if should.
Sep 5, 2018 at 3:02
The Ajax you show in the question is same origin, so is not going to result in a cross origin error. Oh wait. I see now. You’re redirecting the request to a different host. Sorry for the confusion.
paypal request in ajax method
I’m making paypal request using Ajax calling but I’m getting error with status ZERO.The header format is JSON and data format is JSON. In header i send user ID,Password,Signature, app ID, IP address, request and response format, content type. In data i send return ur, receiver, cancel url , action type.
var dataObject = <>; dataObject = ,"currencyCode":"USD","receiverList":<"receiver":[<"email":"[email protected]","amount":"10.00">,[email protected]","amount":"10.00">]>,"cancelUrl":"http://www.igoogle.com","actionType":"PAY">; var dataHeader = <>; dataHeader = ; $.ajax( < type:'POST', url:'https://svcs.sandbox.paypal.com/AdaptivePayments/Pay',//paypal url headers: JSON.stringify(dataHeader, null, 8), data: JSON.stringify(dataObject, null, 6), dataType:'json', success:onSuccess, error:function(xhr,ajaxOptions)< alert(xhr.status + " :: " + xhr.statusText); >>);
selladurai
asked May 10, 2011 at 13:54
selladurai selladurai
6,551 14 14 gold badges 56 56 silver badges 88 88 bronze badges
1 Answer 1
Have you tried viewing the http discussion between your browser and the server using something like Firebug? That should give you a better idea of what’s going wrong.
answered May 10, 2011 at 13:58
6,105 2 2 gold badges 36 36 silver badges 62 62 bronze badges
I tried with REST client in Firefox but i can’t get the result through coding. Here I make ajax POST request for this URL svcs.sandbox.paypal.com/AdaptivePayments/Pay
Saved searches
Use saved searches to filter your results more quickly
Cancel Create saved search
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
paypal button leads to error after using jquery ajax in onCancel function #997
kkagill opened this issue Jan 28, 2019 · 8 comments
paypal button leads to error after using jquery ajax in onCancel function #997
kkagill opened this issue Jan 28, 2019 · 8 comments
Comments
kkagill commented Jan 28, 2019 •
Description
When a user decided to cancel transaction by clicking x on the paypal modal, I am updating DB by using jquery ajax in onCancel function like below:
`
onCancel: function (data, actions)
$.ajax( < type: 'GET', url: '@Url.Action("OrderCancelled", "ShopUserManagerAPI")', contentType: 'application/json; charset=utf-8', dataType: 'json', success: function (res) < alert("Payment is cancelled") >>); >,
After updating db, alert message is successfully shown. Problem is, when I click on the paypal button again I get this error:
Instead of redirecting them to a cancel page, I show them an alert message because the user should be able to click on the paypal button to try again on the same page.
What’s wrong with this when I use jquery ajax to manually perform something?
Affected browsers
- [v] Chrome
- Safari
- Firefox
- Edge
- IE
- Chrome Mobile/Tablet
- Safari Mobile/Tablet
- Web View / Safari ViewController
- Other
The text was updated successfully, but these errors were encountered:
kkagill commented Jan 29, 2019 •
Hi @mcntsh, here’s what I got:
env: 'sandbox', // Or 'production' // Set up the payment: // 1. Add a payment callback payment: function (data, actions) < // 2. Make a request to server return actions.request.post('/api/User/create-payment/') .then(function (res) < return res.id; >); >, // Execute the payment: // 1. Add an onAuthorize callback onAuthorize: function (data, actions) < // 2. Make a request to server return actions.request.post('/api/User/execute-payment/', < paymentID: data.paymentID, payerID: data.payerID >) .then(function (res) < if (res.status === "Success") < window.location.href = '@Url.Action("OrderSuccess", "User")'; >>); >, onCancel: function (data, actions) < $.ajax(< type: 'GET', url: '@Url.Action("OrderCancelled", "User")', // Call OrderCancelled() to update order has been cancelled contentType: 'application/json; charset=utf-8', dataType: 'json', success: function (res) < alert("Payment is cancelled") >>); >, // If an error prevents buyer checkout, define an error page using the onError callback: onError: function (err) < // Show an error page here, when an error occurs >>, '#paypal-button');
So when the user closed the paypal modal in the middle of the process, then it will trigger onCancel function which will call the server’s OrderCancelled method via jquery ajax to update that this transaction has been cancelled.
If it’s updated, it will return 200 response and show an alert message.
Now, since it’s just returning 200 response and you mentioned I need a valid token, do I need to pass token string from onCancel()’s callback parameter data to my OrderCancelled method and return the token in 200 response?
Contributor
mcntsh commented Feb 1, 2019
Hey @kkagill, apologies for the late response!
This all looks good – the onCancel callback doesn’t require any token response, just payment . I’m wondering if something in your OrderCancelled API is causing failure in /api/User/create-payment . Can you confirm that res.id is a valid token?
kkagill commented Feb 1, 2019 •
@mcntsh no OrderCancelled is not returning any token because that ajax is not passing any data to OrderCancelled api. That’s why I asked you if I need to pass onCancel ‘s callback data (paymentID, paymentToken) to OrderCancelled and return token again in the 200 response,
Contributor
mcntsh commented Feb 1, 2019
You do not need to return anything in the onCancel callback, only the payment callback which is where this error is occurring. The payment callback is what gets called when a buyer clicks the button. Could you please confirm that when you reproduce this error, this promise in the payment callback
return return actions.request.post('/api/User/create-payment/')
resolves, and that this variable
return res.id;
is a valid token.
kkagill commented Feb 2, 2019
It is returning a valid token when it is requesting to /api/user/create-payment at the first try. Then when a paypal popup asks me to login and I close it intentionally, it triggers onCancel , showing the alert message then what I do is send GET request to OrderCancelled to update DB which returns 200 response.
Then on the same page, I close the alert message and I clicked on the paypal button again. As a result, it redirects me back to return_url instead of showing a paypal popup.
So if you are asking about the second attempt on the same page, yes it is not returning a valid token.
If I removed the ajax part in onCancel and just show an alert message, then it works fine on my second attempt to login to PayPal via popup on the same page.
Not sure why ajax part is triggering me to redirect back to return_url when it only returns 200 response.
Contributor
mcntsh commented Feb 2, 2019
So if you are asking about the second attempt on the same page, yes it is not returning a valid token.
Therein lies the problem. I’d check your network logs for your second request to /api/user/create-payment and see what’s going on there. I suspect its a server failure resulting from the OrderCancelled request you made before it.
Приложение Venmo, детище PayPal, начнет работать с 4 криптовалютами, включая Bitcoin и Ethereum
Платежный сервис Venmo, который принадлежит PayPal, объявил о введении операций с криптовалютами.
Как это работает
Теперь пользователи Venmo смогут покупать, хранить и продавать четыре типа криптовалюты: Bitcoin, Ethereum, Litecoin и Bitcoin Cash. Минимальная сумма сделки составляет $1.
Чтобы провести операцию, пользователь может использовать средства со своего баланса в Venmo, привязанного банковского счета или дебетовой карты. Все транзакции управляются непосредственно в приложении Venmo.
Нововведение стало возможным благодаря партнерству PayPal с Paxos Trust Company, регулируемым поставщиком криптовалютных продуктов и услуг.
Напомним, в конце марта PayPal дал пользователям возможность использовать криптовалюту для оплаты покупок. При этом криптовалюта будет конвертироваться в фиатные валюты в момент покупки. К сожалению, пока это действует только в США, как и операции в Venmo — сервис доступен только для американских пользователей.
« Запуск этой функции подтверждает стремление PayPal информировать своих клиентов о потенциале цифровых валют по мере их роста и способствует пониманию и использованию криптовалют в массовом масштабе » , — подытожили в Venmo.
Для тех, кто хочет знать больше:
- 10 самых продаваемых гаджетов на AliExpress
- 10 самых продаваемых TWS-наушников с Aliexpress
- Выбираем лучший робот-пылесос
- 10 лучших закрытых беспроводных наушников с Aliexpress до 20 долларов
- 10 самых продаваемых ТВ-приставок на Android с Aliexpress