我必须在 React SPA 应用程序中实现“与 Paypal 连接”功能。
使用Paypal提供的代码实现登录
paypal.use( ["login"], function(login) {
login.render ({
"appid": MYAPPID,
"authend": "sandbox",
"scopes": <SCOPES>,
"containerid": "paypalButton",
"locale": "en-us",
"returnurl": <RETURN_URL>
});
});
这会打开一个新的弹出窗口,这完全超出了我的控制范围。弹出窗口打开 Paypal 登录表单,在成功登录后,该表单将重定向到 <RETURN_URL>
。 .
所有这一切都发生在弹出窗口中。由于这是一个 SPA,我不想刷新页面。
我需要一种方法来关闭重定向的弹出窗口,同时还保留从 Paypal 传回给它的 URL 参数,并将该信息(URL 参数)传输到主应用程序窗口。
这可能吗?如果可能的话怎么办?据我所知,Paypal 文档已经过时了。
最佳答案
有很多方法可以共享这些数据。我假设您的 {RETURN_URL}
和 SPA 是同源的。这是我想出的两种在您的 SPA 和弹出窗口之间进行通信的方法。 p>
1) 使用 Broadcast Channel API如果您需要的浏览器和版本支持 API (caniuse) .没有 Safari,并且边缘有限! Polyfill 也存在。
下面是一些示例代码,您可以用来尝试不同的方法。两页(一个是您的 SPA,另一个是您提供的 RETURN_URL,供 PayPal 在完成时发送给您)。
您的 SPA index.html
:
<html>
<head>
<title>My SPA</title>
</head>
<body>
<script>
const bc = new BroadcastChannel("my_spa_listener");
window.open("./newpage.html?some=true&query=hi¶ms=cat", "_new");
bc.onmessage = function(ev) {
console.log("Got a message from the pop-up: ", ev.data);
};
</script>
</body>
</html>
弹出newpage.html
:
<html>
<head>
<title>PayPal redirected me here</title>
</head>
<body>
<script>
setTimeout(function() {
const bc = new BroadcastChannel("my_spa_listener");
bc.postMessage(window.location.search);
bc.close();
window.close();
}, 2500);
</script>
</body>
</html>
2) 好老localStorage .你can use it几乎任何地方!
index.html
:
const targetKey = "popup-queryparams";
window.addEventListener("storage", function(ev) {
if (ev.key === targetKey) {
console.log("Got the data: ", ev.newValue);
// clear key in case it conatins sensitive info
localStorage.removeItem(targetKey);
}
});
window.open("./newpage.html?some=true&query=hi¶ms=cat", "_new");
然后在弹出窗口中,在关闭窗口之前,只需执行以下操作:
localStorage.setItem("popup-queryparams", window.location.search);
关于javascript - 在弹出窗口中成功登录 Paypal 后,将重定向 url 参数传回主窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57298890/