<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            html,
            body,
            iframe{
                margin: 0;
                border: 0;
                padding: 0;
                display: block;
                height: 100%;
                width: 100%;
                background: white;
                color: black;
                overflow: hidden;
            }
        </style>
    </head>

    <body>
        <!-- Include the PayPal JavaScript SDK; replace "test" with your own sandbox Business account app client ID -->
        <!-- Set up a container element for the button -->
        <div id="paypal-button-container"></div>
        <script>
            let isDOMContentLoaded = false;
            let isOnMessage = false;
            document.addEventListener("DOMContentLoaded", function () {
                isDOMContentLoaded = true;
            })
            function loadAsyncScript(src, callback = function () {}) { // 同步加载js
                const head = document.getElementsByTagName('head')[0];
                const script = document.createElement('script');
                script.setAttribute('type', 'text/javascript');
                script.setAttribute('src', src);
                script.setAttribute('async', true);
                script.setAttribute('defer', true);
                head.appendChild(script);
        
                if (script.readyState) { // ie
                    script.onreadystatechange = function () {
                        var state = this.readyState;
                        if (state === 'loaded' || state === 'complete') {
                            callback();
                        }
                    }
                } else {
                    script.onload = function () {
                        callback();
                    }
                }
            }

            function getQueryString(name) {
                let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
                let r = window.location.search.substr(1).match(reg);
                if (r != null) {
                    return decodeURIComponent(r[2]);
                };
                return null;
            }
            let paypalClientId = getQueryString('paypalClientId');
            let src = `https://www.paypal.com/sdk/js?client-id=${paypalClientId}&currency=USD`;
            loadAsyncScript(src, () => {
                if(isDOMContentLoaded) {
                    loadPaypal();
                } else {
                    document.addEventListener("DOMContentLoaded", function () {
                        isDOMContentLoaded = true;
                        if(!isOnMessage) {
                            loadPaypal()
                        }
                    })
                    setTimeout(() => {
                        if(!isOnMessage) {
                            loadPaypal()
                        }
                    }, 600)
                }
            })

            function loadPaypal() {
                let amount = getQueryString('amount');
                isOnMessage = true;
                window.parent.postMessage({ actionType: "iframeLoaded" }, "*");
                // window.addEventListener("message", function (event) {
                //     if (event.data && event.data.actionType) {
                //         switch (event.data.actionType) {
                //             case "setAmount":
                //                 amount = event.data.amount;
                                initPaypal(amount);
                //                 break;
                //             }
                //     }
                // });
            }

            function initPaypal(amount) {
                let dom = document.getElementById('paypal-button-container');
                if(dom.children && dom.children.length) {
                    empty(dom)
                }
                paypal
                    .Buttons({
                        style: {
                            layout: 'horizontal',
                            color:  'blue',
                            shape:  'pill',
                            tagline: false,
                            height: 48
                        },
                        // Sets up the transaction when a payment button is clicked
                        createOrder: function (data, actions) {
                            return actions.order.create({
                                purchase_units: [
                                    {
                                        amount: {
                                            value: amount, // Can reference variables or functions. Example: `value: document.getElementById('...').value`
                                        },
                                    },
                                ],
                            });
                        },

                        // Finalize the transaction after payer approval
                        onApprove: function (data, actions) {
                            return actions.order
                                .capture()
                                .then(function (orderData) {
                                    // Successful capture! For dev/demo purposes:
                                    console.log(
                                        "Capture result",
                                        orderData,
                                        JSON.stringify(orderData, null, 2)
                                    );
                                    var transaction =
                                        orderData.purchase_units[0].payments
                                            .captures[0];
                                    window.parent.postMessage(
                                        {
                                            actionType: "payCallBack",
                                            orderData: orderData,
                                            transaction: transaction,
                                        },
                                        "*"
                                    );
                                    // 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');
                                });
                        },
                    })
                    .render("#paypal-button-container");
            }
            function empty (e) {
                while (e.firstChild) {
                    e.removeChild (e.firstChild);
                }
            }
        </script>
    </body>
</html>