简体   繁体   中英

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:

<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 -

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. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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