After completing the payment, Paypal Express checkout causes the page to refresh

I have integrated an Express checkout button into my webpage and configured the server-side process with client code:

<script src="https://www.paypalobjects.com/api/checkout.js"></script>
<script>
    var CREATE_PAYMENT_URL = "<create_payment_url>";
    var EXECUTE_PAYMENT_URL = "<execute_payment_url>";

    paypal.Button.render({
        env: "sandbox",
        payment: function (resolve, reject) {
            return paypal.request.post(CREATE_PAYMENT_URL)
                .then(function (data) {
                    resolve(data.id);
                })
                .catch(function (err) {
                    reject(err);
                });
        },
        onAuthorize: function (data) {
            return paypal.request.post(EXECUTE_PAYMENT_URL, { paymentID: data.paymentID, payerID: data.payerID })
                .then(function (data) {
                    document.querySelector('#paypal-button').innerText = 'Payment Complete!';
                    console.log("Success", data);
                })
                .catch(function (err) {
                    console.log("Error", err);
                });
        }
    }, "#paypal-button");
</script>

Although I am using the server-side .NET SDK to facilitate payment creation and processing with generic handlers, I am facing an issue where the entire page reloads after the payment is executed.

My goal is to manage the results/errors through execution listeners using the callbacks defined with the .then() and .catch() methods in paypal.request.post(EXECUTE_PAYMENT_URL, ...).

In PayPal's interactive demo available at https://developer.paypal.com/demo/checkout/#/pattern/server, the listener functions as expected.

Any suggestions on how I can address this issue would be greatly appreciated.

Answer №1

In my create payment handler (CREATE_PAYMENT_URL), I encountered an issue with the default redirect_urls. These URLs are not necessary for my use case as responses are handled by JavaScript listeners. Despite this, redirect_urls are a required parameter for the Payment object. Interestingly, it appears that the actual URLs provided don't need to be accurate, only the server port needs to respond.

The server-side code I am working with is as follows:

Dictionary<string, string> config = ConfigManager.Instance.GetProperties();
string accessToken = new OAuthTokenCredential(config).GetAccessToken();
APIContext apiContext = new APIContext(accessToken);
Payer payer = new Payer()
{
    payment_method = "paypal"
};
RedirectUrls redirUrls = new RedirectUrls()
{
    cancel_url = "http://localhost:<correct_port>/some_cancel.ashx",
    return_url = "http://localhost:<correct_port>/some_return.ashx"
};
ItemList itemList = new ItemList()
{
    items = new List<Item>() {
    // Some items
}
};
Amount amount = new Amount()
{
    currency = "EUR",
    total = "##.##",
};
List<Transaction> transList = new List<Transaction>()
{
    new Transaction() {
        amount=amount,
        description="Desc...",
        invoice_number="#####",
        item_list=itemList
    }
};
Payment payment = new Payment()
{
    intent = "sale",
    payer = payer,
    transactions = transList,
    redirect_urls = redirUrls
};
Payment createdPayment = payment.Create(apiContext);
context.Response.Write(/*<Serialized response>*/);

Additionally, I have a question regarding the sandbox buyer Paypal account. When logging in, I noticed that I am unable to change the payment method, with only the Paypal balance available. However, when I tested the demo at https://developer.paypal.com/demo/checkout/#/pattern/server, I was able to change the payment method to a Credit card linked to the same Paypal account. Both tests were conducted using the same sandbox account.

Thank you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vuex is exclusively eliminating the initial element

Currently, I have set up the code to remove the activeNote from the array called notes by using the DELETE_NOTE mutation. However, it seems that it only removes the first element of the array. The content of mutations.js is as follows: export const mutat ...

Scroll a div using JavaScript/jQuery

I'm currently facing some challenges in resolving this issue. My goal is to pan a DIV using jQuery. The process is quite straightforward - on mouseDown, I capture X & Y coordinates and then subtract them from the newly obtained X & Y values during mou ...

Achieving compatibility with pseudo elements :before/:after in Internet Explorer 7

I've been attempting to make these functionalities compatible with IE 7, but I'm encountering difficulties. I've downloaded and included the jQuery plugin for it in the header as shown below: <!--[if lte IE 7]> <script type="text/j ...

Ways to eliminate the white overlay that occurs on the page after clicking the scroll top button

Hi there! I've been busy with updating my site at , and noticed a small glitch. Every time I hit the Back to Top button at the bottom of the page, the screen goes white. Any ideas on how to fix this issue? Thanks in advance! ...

The AJAX load event listener triggers prior to receiving a response from the server

When working on a script to upload images via AJAX, the process is as follows: a user selects an image using a form file input field. The form contains an onsubmit function that prevents the page from reloading after submission. Within this function, data ...

I am currently experiencing some challenges with using jquery ajax post in conjunction with PHP

I am facing an issue with jQuery AJAX post and PHP. My attempt is to send data using .serialize() along with additional data. However, in PHP, I can only receive the data from .serialize() but not the additional data. In my jQuery Ajax code, f ...

Keep moving forward in Sailsjs even after sending back a response with res.json();

It will keep running even if the condition is met and the code inside return res.json() gets executed. _.each(rooms, function(room){ if(room.users.length == users.length) { return res.json(room); // <-- returns but execution continues } ...

Unveil the Expressjs middleware within the API Client

I am currently developing a Nodejs API Client with the following simple form: //client.js function Client (appId, token) { if (!(this instanceof Client)) { return new Client(appId, token); } this._appId = appId; this._token = tok ...

Vue-chartjs line chart not displaying data fetched from API

I successfully created bar charts using vue2 and vue-chart.js with data from an API call. However, I am facing issues with displaying line charts. Despite loading the data, the line chart is not showing up, and no errors are being displayed. I have reviewe ...

Generate a randomly structured 2D array called "Array" using JavaScript

Can anyone help me with extracting a random array from a 2D named array? I've tried several solutions but none of them seem to work. var sites = []; sites['apple'] = [ 'green' , 'red' , 'blue' ]; sites['o ...

Angular: Identifier for Dropdown with Multiple Selection

I have recently set up a multi select dropdown with checkboxes by following the instructions provided in this post: https://github.com/NileshPatel17/ng-multiselect-dropdown This is how I implemented it: <div (mouseleave)="showDropDown = false" [class. ...

Issues with clearRect() function in HTML5 canvas

Recently, I developed a function with the goal of redrawing a square line block that covers the entire page whenever the window size is adjusted. For reference, you can view my code at http://jsfiddle.net/9hVnZ/ However, I encountered an issue: bgCtx.cl ...

Develop a dynamic thunk and additional reducer to efficiently handle multiple API calls and retrieve data

Using Redux and Redux-Toolkit, I aim to streamline my code by implementing a single asynchronous Thunk and extra reducer for multiple requests. Below is the setup for both the company and client slices: import { createSlice, createAsyncThunk } from &apos ...

Is there a way to modify the FixedTableHeader jQuery plugin to include a fixed first column in addition to the fixed header?

I've been experimenting with a jQuery plugin I found at to create a stylish table with fixed headers, sorting options, and other interesting features. While the plugin is great, I also considered using jqGrid for its impressive capabilities. However, ...

How do I make the YouTube Grid Gallery player show up in a pop-up window?

I have been experimenting with the following code: <head> <script type="text/javascript" src="http://swfobject.googlecode.com/svn/trunk/swfobject/swfobject.js"></script> <script type="text/javascript"> function loadVideo(playerUrl, ...

Sending data from PHP to JavaScript using AJAX

I'm encountering an issue trying to pass data from a PHP file to a JavaScript file using echo. My PHP file contains the following code snippet: <?php ...establishing connection and retrieving list from database... for($i=0;$i<sizeOf($li ...

jQuery error: an unexpected token was encountered

I am encountering an issue with an "unexpected token =" error on the line toggleNav = function(evt){ in the code snippet below. Despite going through various similar posts, I am unable to pinpoint why this error is occurring. Any assistance in guiding me ...

Update the SQL database by transferring star ratings from a JSP file

Utilizing JSP to showcase information obtained from user queries, I have implemented a system where contextual data and the query itself are saved in a MySQL database using JDBC each time a new query is input. To enhance user interaction, I wanted to incor ...

Utilize Vue to access and read a file stored in the current directory

I am attempting to retrieve data from a text file that is located in the same directory as my .vue file. Unfortunately, I am encountering an issue where the content of the text file is not being displayed in both Chrome and Firefox. Instead, I am seeing th ...

The React application is functioning properly; however, during compilation, it continually displays an error stating that the module cannot be found

Compilation Failed. Error: Module not found, unable to resolve the specified path. webpack compiled with 1 error I was hoping for a successful compilation, but unfortunately encountered an error. It's perplexing as the application is functioning co ...