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:
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?
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.