I’m struggling trying to ollow PayPal paiyment on my PHP website. I built wrote the following method to hadle order creation, but I keep getting an error when trying to parse PayPal response to JSON.
function createOrder($amount, $info) {
$pp_env = PAYPAL_ENVIRONMENT_MODE == 1 ? PAYPAL_SANDBOX_ENV : PAYPAL_LIVE_ENV ;
$accessToken = $this->generateAccessToken();
$url = $pp_env."/v2/checkout/orders";
$data = array(
'intent' => 'CAPTURE',
'purchase_units' => array(
array(
'amount' => array(
'currency_code' => CURRENCY_CODE,
'value' => $amount,
),
),
),
);
$headers = array(
"Content-type: application/json",
"Accept: application/json",
"Authorization: Bearer " . $accessToken,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
My error is client-side when I try to convert HTTP response to JSON using this code:
createOrder() {
return fetch("<?=base_url("public/paypal_create")?>", {
method: "POST",
headers: {
"Content-Type": "application/json"
}
})
.then((response) => response.json())
.then((order) => order.id);
}
Following is the response I can see using browser dev tools:
enter image description here
Anyone can figure out whqt I’m doing wrong?
2
Answers
Use the Network tab to see what your server is responding from its create-order and capture-order routes when your buttons are clicked. The response must be only a valid JSON object that the frontend button code JS can parse.
Based on the error information in your question, it appears the response contains additional HTML things (not just the JSON) including a debug_loader, which is invalid for a fetch/XHR trying to parse that response as JSON.
As you are using CodeIgniter, you may need to suppress your debug/developer information. This seems to be impacting the data that your JavaScript is expecting.
On the script that is rendering your JSON add the following code.
https://codeigniter4.github.io/CodeIgniter4/testing/debugging.html#enabling-the-toolbar