Почему кнопки PayPal Smart не распознают массив моих товаров? - PullRequest
0 голосов
/ 01 апреля 2020

Я встроил умные кнопки PayPal в свою JavaScript корзину. Я пытаюсь разрешить PayPal сообщать пользователю о товарах, которые они имели в корзине при оформлении заказа. Например; enter image description here

Я знаю, что для этого мне нужно использовать следующий код:

<script>
        paypal.Buttons({
            createOrder: function(data, actions) {
                // This function sets up the details of the transaction, including the amount and line item details.
                return actions.order.create({
                    "purchase_units": [{
                        "description": "Stuff",
                        "amount": {
                            "value": "20.00",
                            "currency_code": "USD",
                            "breakdown": {
                                "item_total": {
                                    "currency_code": "USD",
                                    "value": "20.00"
                                },
                            }
                        },
                        "items": [
                            {
                                "unit_amount": {
                                    "currency_code": "USD",
                                    "value": "10.00"
                                },
                                "quantity": "1",
                                "name": "Item 1",
                            },
                            {
                                "unit_amount": {
                                    "currency_code": "USD",
                                    "value": "10.00"
                                },
                                "quantity": "1",
                                "name": "Item 2",
                            },
                        ],
                    }
                    ]
                });
            },
            onApprove: function(data, actions) {
                // This function captures the funds from the transaction.
                return actions.order.capture().then(function(details) {
                    // This function shows a transaction success message to your buyer.
                    window.location.href = "orderConfirmed.php"
                    clearCart()
                });
            }
        }).render('#paypal-button-container');
        //This function displays Smart Payment Buttons on your web page.
    </script>

В этом примере в раскрывающейся вкладке есть 2 элемента : Пункт 1 и пункт 2, но они нужны для представления того, что пользователь имеет в своей корзине. Я получил ответ на нее, который сказал, что мне нужно создать массив amn, который будет содержать название, цену и количество товара в корзине.

Я придумал этот код, я пытаюсь сделать для каждого товара в корзине, я хочу вернуть название товара, цену товара и количество товара. Я пришел с кодом ниже:

function arrayOfItems() {

        cart.forEach((cartItem, index) => {
            let currency = cartItem.price;
            let quantity = cartItem.quantity;
            let itemName = cartItem.name;

            let items = [{"unit_amount": {"currency_code": "USD","value": currency},"quantity": quantity,"name": itemName,}];

            return items;

        });

    }

Но когда я запускаю новый скрипт PayPal примерно так:

<script src="cart.js"></script>

    <script>
        paypal.Buttons({
            createOrder: function(data, actions) {
                // This function sets up the details of the transaction, including the amount and line item details.
                return actions.order.create({
                    purchase_units: [{
                        amount: {
                            value: countCartTotal()
                        },
                        items: [
                            {
                                arrayOfItems()
                            },
                        ],
                    }
                    ]
                });
            },
            onApprove: function(data, actions) {
                // This function captures the funds from the transaction.
                return actions.order.capture().then(function(details) {
                    // This function shows a transaction success message to your buyer.
                    window.location.href = "orderConfirmed.php"
                    clearCart()
                });
            }
        }).render('#paypal-button-container');
        //This function displays Smart Payment Buttons on your web page.
    </script>

Кнопки PayPal перестают работать! Любая помощь?


После внесения изменений код теперь выглядит следующим образом:

<script>
        paypal.Buttons({
            createOrder: function(data, actions) {
                // This function sets up the details of the transaction, including the amount and line item details.
                return actions.order.create({
                    "purchase_units": [{
                        "amount": {
                            "value": countCartTotal(),
                            "currency_code": "USD",
                        "breakdown": {
                            "item_total": {
                                "currency_code": "USD",
                                "value": countCartTotal()
                            },
                        },
                        "items": arrayOfItems()
                    }
                    ]
                });
            },
            onApprove: function(data, actions) {
                // This function captures the funds from the transaction.
                return actions.order.capture().then(function(details) {
                    // This function shows a transaction success message to your buyer.
                    window.location.href = "orderConfirmed.php"
                    clearCart()
                });
            }
        }).render('#paypal-button-container');
        //This function displays Smart Payment Buttons on your web page.
    </script>

И не выдает никаких ошибок в моей IDE, однако, когда я запускаю код, JavaScript Консоль выдаёт мне эту ошибку:

enter image description here

Есть идеи? Спасибо

1 Ответ

1 голос
/ 01 апреля 2020

Вы, похоже, не включаете необходимую разбивку. Это может показаться излишним, но требуется разделить секцию.

                        "breakdown": {
                            "item_total": {
                                "value": countCartTotal()
                            },
                        }

Кроме того, похоже, что вы генерируете массив элементов, поэтому вам нужно использовать его так:

                    amount: {
                        value: countCartTotal()
                    },
                    items: arrayOfItems(),

Все поля currency_code также необходимы и не обязательны при передаче информации о позиции, поэтому вам необходимо добавить их обратно.

Это три проблемы, которые вам нужно исправить.

Если вам все еще нужна помощь, опубликуйте во время выполнения пример того, что все оценивает, то есть вывод функций, чтобы мы могли сказать вам, что не так

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...