Exploring the PayPal Checkout JavaScript SDK's CreateOrder call and interpreting the response

I am currently exploring how to use the JavaScript SDK to display PayPal payment buttons on a website. I am new to working with JSON and REST API calls, so I am facing some challenges in implementing this.

The createOrder function is running smoothly and triggering the code on my backend server. The PayPal API calls on the backend seem to be functioning correctly (authorization, /v2/orders/create). However, the issue arises when I try to pass the response body from the /v2/orders/create call on the server side back to the client-side createOrders function. PayPal then throws the following error:

{err: 'Error: Expected an order id to be passed\n    at ht…credit,venmo&integration-date=2023-01-01:3:15633)', timestamp: '1686345825125', referer: 'www.sandbox.paypal.com', sdkCorrelationID: 'f896866242248', sessionID: 'uid_915a4c39df_mje6mtm6mtc', …}

Here is what the developer console shows as the server-side code response returned to the createOrder method:

{"d":"{\"id\":\"7MF03646UY937942N\",\"status\":\"PAYER_ACTION_REQUIRED\",\"payment_source\":{\"paypal\":{}},\"links\":[{\"href\":\"https://api.sandbox.paypal.com/v2/checkout/orders/7MF03646UY937942N\",\"rel\":\"self\",\"method\":\"GET\"},{\"href\":\"https://www.sandbox.paypal.com/checkoutnow?token=7MF03646UY937942N\",\"rel\":\"payer-action\",\"method\":\"GET\"}]}"}    

This is the code snippet for my createOrder function:

createOrder: function () {
                return fetch("ppcktest2/ppckCreateOrder", {
                    method: 'POST',
                    credentials: 'include',
                    headers: { 'Content-Type': 'application/json' },
                })
                .then((response) => response.json())
                .then((order) => order.id);
         }

I suspect that the issue lies in how I am formatting the JSON response being sent back to the createOrder function. Is there something wrong with the structure of the response? The Chrome developer console does not display my server response as a structured tree view, which makes me question whether the format is incorrect.

I have refrained from sharing my server-side code as it seems to be correct, unless there's an anomaly in how I return the JSON data, where I essentially send back the response body as received from PayPal.

Note: I do not utilize a PayPal SDK on the server side; instead, I directly make API calls.

I would like clarification on:

  1. What specific data does the JavaScript SDK createOrder function expect in return? Is it the entire JSON response from the server-side call to /v2/orders/create or just a portion?

  2. How should I format the response on the server side before sending it back - Should it be a JSON string similar to what I am currently returning... I'm unsure of other approaches.

I am relatively new to JSON and APIs, which I believe contributes to the challenge I am facing.

Answer №1

{"d":"{\"id\":\"7MF03646UY937942N\",\"status\":\"PAYER_ACTION_REQUIRED\",\"payment_source\":{\"paypal\":{}},\"links\":[{\"href\":\"https://api.sandbox.paypal.com/v2/checkout/orders/7MF03646UY937942N\",\"rel\":\"self\",\"method\":\"GET\"},{\"href\":\"https://www.sandbox.paypal.com/checkoutnow?token=7MF03646UY937942N\",\"rel\":\"payer-action\",\"method\":\"GET\"}]}"}

This mysterious log seems to be excessively encoded or processed, suggesting a need for simplification on the server end.

To further investigate, check the Network tab and examine the response data of the request. If there are excessive backslashes present (\), it may indicate overencoding that requires correction at the server level.

For comparison, visit https://developer.paypal.com/demo/checkout/#/pattern/server and analyze the Network tab logs after interacting with the buttons.

In addition, open both ppcktest2/ppckCreateOrder and

https://developer.paypal.com/demo/checkout/api/paypal/order/create/
in separate tabs to compare their output formats directly.

Note that the demo site may have additional response parameters specific to its setup, but the key one to focus on is id.

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

Unable to physically tap on the checkbox input, though able to perceive the value it holds

When running my protractor test, I encountered an issue with the following statement: await element(by.model('publishCtrl.isPublishedInAllRegions')).click(); The test failed and returned an error message stating "ElementNotVisibleError: element ...

Guide to downloading a file from a byte base64 in Vue.js

I am dealing with a byte base64 string let data = 'UEsDBBQABgAIAAAAIQBi7...' If I want to download the file from this byte base64 in vue js, what should I do? Any suggestions or solutions would be greatly appreciated :') ...

What is the most effective way to manage and respond to multiple events while also organizing the overall structure of

I am currently in the process of planning a complex web application using WebGL and Three.js. As I experiment with different tests, I have encountered a problem that is raising many questions for me. I am unsure of the correct approach to take and would gr ...

Updating the minimum date based on the user's previous selection using React JS and Material UI

In my material UI, I have two date pickers set up: From Date - <KeyboardDatePicker value={initialDateFrom} disableFuture={true} onChange={handleFromDateChange} > </KeyboardDatePicker> To Date - <KeyboardDatePicker value={initialDateTo} ...

Component in Angular2 encountering a null value

Unexpected situations may arise where "this" becomes null within a component. So far, I have encountered it in two scenarios: 1) When the promise is rejected: if (this.valForm.valid) { this.userService.login(value).then(result => { ...

Having issues with IE8 and SmoothGallery script errors

I'm currently utilizing the SmoothGallery plugin created by Jon Designs to enhance the website of one of my clients. However, there seems to be a minor issue in Internet Explorer 8 when attempting to navigate to the next image. Interestingly enough, a ...

Creating Web Components using JavaScript on the fly

I tried to create web components directly from JavaScript, but I encountered an issue where the public constructor could not be found. Here's a basic example to illustrate the situation: The HTML Template: <polymer-element name="wc-foo" construct ...

Content in TinyMCE styled with the default CSS of the application

Hello fellow developers; I'm struggling to find a suitable solution to apply the same styles from our main CSS file to the text entered in the TinyMCE editor. Just to clarify, I don't want to alter the overall theme or appearance of TinyMCE itse ...

Having trouble with gsap.reverse() not functioning properly when using onMouseLeave event in React

I've been incorporating simple gsap animations into my React application. I have successfully triggered an animation.play() function on onMouseEnter, but for some reason, the animation.reverse() function is not functioning as expected. Here's ho ...

Is there a way to send arguments to a pre-existing Vue JS application?

A Vue application we've developed connects to a Web Service to retrieve data. However, the URL of the web service varies depending on the installation location of the app. Initially, we considered using .env files for configuration, but realized that ...

Is it possible for $templateCache to preload images?

Is there a way to preload images in Angular without using a spinner after the controller is initialized? I've heard about caching templates with $templateCache. Can this be used to also preload images when the template contains <img> tags or sty ...

Contrasting bracket notation property access with Pick utility in TypeScript

I have a layout similar to this export type CameraProps = Omit<React.HTMLProps<HTMLVideoElement>, "ref"> & { audio?: boolean; audioConstraints?: MediaStreamConstraints["audio"]; mirrored?: boolean; screenshotFormat?: "i ...

Does the arrangement of props matter in JSX?

Assuming the o object has a key/value pair of: foo: 'bar', can I expect these results to hold true?: // foo will be 'bar' <MyComponent foo='should not override' {...o} /> // foo will be 'overridden' ...

"Send the selected radio button options chosen by the user, with the values specified in a JSON format

My current task involves inserting radio button values into a MySql database using Angular. The form consists of radio buttons with predefined values stored in a json file. Below is an example of how the json file is structured: //data.json [{ "surve ...

NextJS 12: The dilemma of styled components not rendering server side due to missing CSS

Exciting news with the latest NextJS 12 release - now styled-components is supported without the need for any extra plugins on NextJS! However, I'm running into issues getting it to work with server-side rendering. To activate it, I installed the sty ...

"Implementing a seamless transition effect on two slideshows using jQuery's fadeslideshow

I currently have a homepage featuring a fadeslideshow with 5 slides. The fadeslideshow plugin being used can be found at http://plugins.jquery.com/project/fadeslideshow. On the homepage, there is also a menu bar with various menu items. When a user clicks ...

Tips for delaying the rendering of a directive in AngularJS until the data from a tsv file has been fully loaded

I am trying to integrate d3.js with angularjs to create a line graph using data loaded from a tsv file. However, I am facing an issue where the graph is being rendered before the data is fully loaded. I want the graph to be rendered only after the data has ...

How to use jQuery to dynamically generate a JSON object within a loop

http://jsfiddle.net/hU89p/219/ This example demonstrates the creation of a JSON object based on selected checkboxes. When selecting one checkbox, the JSON would look like: var data={"name":"BlackBerry Bold 9650", "rating":"2/5", "Location":UK}; By sele ...

Can anyone tell me where to find the unminified version of Bootstrap 3's docs.min.js file?

Could someone please provide me with the original version of this file? I've been trying to search for it in the project but haven't had any luck. You can find it here: https://github.com/twbs/bootstrap/blob/master/docs/assets/js/docs.min.js. ...

Issues with method invocation in jQuery's .ajax requestI am having

After reading this Stack Overflow post, I now understand how to retrieve a return value from an AJAX call: function GetIsDataReady(input) { $.ajax({ url: "http://www.blah.com/services/TestsService.svc/IsDataReady", ...