简体   繁体   English

如何根据环境呈现贝宝智能按钮?

[英]How to render Paypal Smart Button based on environment?

I'm able to add the paypal button in my site with live client id and it works all good, however for development purposes I use my sandbox client id when testing locally and this means always changing the client id in the src:我可以在我的网站中添加带有实时客户端 ID 的 paypal 按钮,并且一切正常,但是出于开发目的,我在本地测试时使用沙箱客户端 ID,这意味着始终更改 src 中的客户端 ID:

<script src="https://www.paypal.com/sdk/js?client-id=AYw0JC4IjiptK8Dyv--SPi98ze5My9hgTOmD_ckO8u197I56tpOtinZAu7p2flNCPGk5ZezoYSNS-U4Z&currency=GBP&disable-funding=credit,card">
    </script>

I created a js file which loads different script files depending on the environment the site is being run on -我创建了一个 js 文件,它根据站点运行的环境加载不同的脚本文件 -

const LOCAL_DOMAINS = ["localhost", "127.0.0.1", ""];

var paypalTestScript = 'https://www.paypal.com/sdk/js?client-id=AXQBIcWjoGGdwc1GXUtX9fx7o_U3lUIcmShJCa7FcJYX8MVOXa20yy1M7FgLdHPmEsWmU30ChP1X9xJJ&vault=true&currency=GBP&disable-funding=credit,card';
var paypalLiveScript = 'https://www.paypal.com/sdk/js?client-id=AYw0JC4IjiptK8Dyv--SPi98ze5My9hgTOmD_ckO8u197I56tpOtinZAu7p2flNCPGk5ZezoYSNS-U4Z&vault=true&currency=GBP&disable-funding=credit,card';

var paypalScriptToUse = "";
if (LOCAL_DOMAINS.includes(window.location.hostname)) {
    paypalScriptToUse = paypalTestScript;
} else {
    paypalScriptToUse = paypalLiveScript;
}

var script = document.createElement('script');
script.setAttribute('src', paypalScriptToUse);
document.head.appendChild(script);

Yet the paypal smart button is being very inconsistent in rendering as it works 1 out of 7/8 times.然而,paypal 智能按钮在呈现方面非常不一致,因为它的工作率为 7/8 次中的 1 次。 Is there a stable way of loading the scripts dynamically?是否有一种稳定的方式来动态加载脚本?

Your code appears as though it'll work, I think you've created the right sort of hack for this sort of dynamic environment loading based on URL, although I've never seen this done before.您的代码看起来好像可以工作,我认为您已经为这种基于 URL 的动态环境加载创建了正确的 hack,尽管我以前从未见过这样做过。 Typically people switch between environments at a much slower rate, perhpas a few times a day at most, so commenting out and uncommenting two lines at the top of the page, ie:通常人们以慢得多的速度在环境之间切换,最多一天几次,因此在页面顶部注释和取消注释两行,即:

    <script>for sandbox...(currently uncommented)</script>
<!--
    <script>for live...(currently commented out)</script>
-->

..has been sufficient for all the development use cases I've observed up til now. ..对于我迄今为止观察到的所有开发用例来说已经足够了。


Your issue of "it works 1 out of 7/8 times" can't be looked into without more data, like a full runnable snippet we can test and reproduce the same with如果没有更多数据,就无法研究“它可以运行 7/8 次中的 1 次”的问题,就像我们可以测试和重现的完整可运行代码段一样

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM