Использование API-интерфейса PayPal REST в .net - PullRequest
0 голосов
/ 29 мая 2019

Я пытаюсь реализовать PayPal REST API с моим приложением .net.Для этого я использую учетные записи в песочнице.Ссылаясь на приведенные ниже демонстрационные документы / документы, вы получите код, который сначала создаст заказ, а затем произведет оплату за тот же заказ.

Однако моя проблема в том, что я не могу получить идентификатор заказа.Хотя я получаю res.json() снизу код.Мне нужно получить идентификатор заказа, установить его для некоторой переменной и использовать его в последующих запросах.Этот нижеприведенный код я получил по демонстрационной ссылке и внес некоторые изменения в соответствии с моим требованием.

Также в блоке OnApprove я не получаю data.id.

 <div id="paypal-button-container">    </div>

<script>
        // Render the PayPal button into #paypal-button-container
        paypal.Buttons({

            // Set up the transaction
            createOrder: function (data, actions) {
                return fetch('https://api.sandbox.paypal.com/v2/checkout/orders', {
                    method: 'post',
                    headers: {
                        'content-type': 'application/json',
                        'Authorization': 'Bearer <My Access Token>'
                    },
                    body: JSON.stringify({
                        "intent": "CAPTURE",
                        "purchase_units": [
                            {
                                "amount": {
                                    "currency_code": "USD",
                                    "value": "100.00"
                                }
                            }
                        ]
                    })
                }).then(function (res) {
                    return res.json();
                }).then(function (data) {
                    return data.id;
                });
            },

            // Finalize the transaction
            onApprove: function (data, actions) {

                return fetch('https://api.sandbox.paypal.com/v2/checkout/orders/' + data.id + '/capture/', {
                    method: 'post',
                    headers: {
                        'content-type': 'application/json',
                        'Authorization': 'Bearer <My Access Token>'
                    },
                }).then(function (res) {
                    return res.json();
                }).then(function (details) {
                    console.log(details);
                    // Show a success message to the buyer
                    alert('Transaction completed');
                });
            }

        }).render('#paypal-button-container');

    </script>

Кроме того, могу ли я запускать свои собственные API из кнопок PayPal?

Любая помощь по этому вопросу приветствуется!

1 Ответ

2 голосов
/ 03 июня 2019

Ваш код кажется идеальным (почти).Вам просто нужно иметь в виду объем переменных здесь.Поскольку переменная data ограничена блоком then, вам нужно будет создать новую переменную для хранения значения data.id и использовать ее в блоке onApprove.Я добавил новую переменную под названием 'orderID' в коде ниже, и это, кажется, работает.

<script>
    var orderID; //Declared a variable
    // Render the PayPal button into #paypal-button-container
    paypal.Buttons({

        // Set up the transaction
        createOrder: function (data, actions) {
            return fetch('https://api.sandbox.paypal.com/v2/checkout/orders', {
                method: 'post',
                headers: {
                    'content-type': 'application/json',
                    'Authorization': 'Bearer <My Access Token>'
                },
                body: JSON.stringify({
                    "intent": "CAPTURE",
                    "purchase_units": [
                        {
                            "amount": {
                                "currency_code": "USD",
                                "value": "100.00"
                            }
                        }
                    ]
                })
            }).then(function (res) {
                return res.json();
            }).then(function (data) {
                orderID = data.id; //storing the id in our variable
                return data.id;
            });
        },

        // Finalize the transaction
        onApprove: function (data, actions) {
            //using the id stored in our variable
            return fetch('https://api.sandbox.paypal.com/v2/checkout/orders/' + orderID + '/capture/', {
                method: 'post',
                headers: {
                    'content-type': 'application/json',
                    'Authorization': 'Bearer <My Access Token>'
                },
            }).then(function (res) {
                return res.json();
            }).then(function (details) {
                console.log(details);
                // Show a success message to the buyer
                alert('Transaction completed');
            });
        }

    }).render('#paypal-button-container');

</script>

Реализация, которую вы делаете, идеально подходит для случаев, когда задействован компонент на стороне сервера,и вызов API для серверов PayPal осуществляется через сервер.Если ваша реализация не требует серверной стороны, я настоятельно рекомендую следовать реализации Smart Payment Buttons - https://developer.paypal.com/docs/checkout/integrate/#

...