I need to send my cart contens in orderlines.
I can get the my orderlines as follows:
foreach ($jcart->get_contents() as $item) {
$queryString .= 'name' . $count. '=' . urlencode($item['name']);
$queryString .= 'unit_price' . $count . '=' . urlencode($item['price']);
$queryString .= 'quantity' . $count . '=' . urlencode($item['qty']);
$queryString .= 'total_amount' . $count . '=' . (urlencode($item['qty']) * urlencode($item['price']));
// Increment the counter
$count;
}
I want to send it as follows:
$data = <<<DATA
{
"intent": "buy",
"purchase_country": "GB",
"purchase_currency": "GBP",
"locale": "en-GB",
"order_amount": 10,
"order_tax_amount": 0,
"order_lines": [
{
"name": "name0",
"quantity": quantity0,
"unit_price": unit_price0,
"total_amount": total_amount0
},
{
"name": "name1",
"quantity": quantity1,
"unit_price": unit_price1,
"total_amount": total_amount1
}]
}
DATA;
How can I get my for each loop to populate the orderlines. so they can be send as example above
I tried:
$data = <<<DATA
{
"intent": "buy",
"purchase_country": "GB",
"purchase_currency": "GBP",
"locale": "en-GB",
"order_amount": 10,
"order_tax_amount": 0,
"order_lines": [$queryString]
}
DATA;
This needs to be send as follows:
$url = "https://api.playground.klarna.com/payments/v1/sessions";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"Authorization: Basic $auth",
"Content-Type: application/json",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($curl);
curl_close($curl);
This does not work Any help welcome
CodePudding user response:
First you should populate the data into an array instead of a string.
$queryArray[] = [
'name' => $item['name'],
'quantity' => ...
]
Next encode the array with json.
$json = json_encode($queryArray);
Finally insert the encoded string into the payload.
$data = <<<DATA
{
"intent": "buy",
"purchase_country": "GB",
"purchase_currency": "GBP",
"locale": "en-GB",
"order_amount": 10,
"order_tax_amount": 0,
"order_lines": $json
}
DATA;
CodePudding user response:
Create an array using the right structure and use json_encode()
instead of trying to make the JSON string yourself.
// create data structure
$payload = [
'intent' => 'buy',
'purchase_country' => 'GB',
// ...
'order_lines' => [],
];
// Populate order-lines
foreach ($jcart->get_contents() as $item) {
$payload['order_lines'][] = [
'name' => $item['name'],
'unit_price' => $item['price'],
'quantity' => $item['qty'],
'total_amount' => $item['qty'] * $item['price'],
];
}
And use :
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($payload));