I’m trying to create a Stripe checkout session, but I’m having trouble with the line_items part. When I want to checkout 1 product, there is no problem, but when I want to checkout multiple items I get invalid array back from the Stripe API.
The Stripe documentation about checkout session line_items tells me line_items needs to be an ‘array of hashes’ and I believe that’s where I run into the problem.
$items = array();
foreach($cart as $itemInCart){
array_push($items, array(
'price' => $itemInCart['product']['stripeData']['price']['id'],
'quantity' => $itemInCart['quantity'],
));
}
When I dd($items) after running the code above:
^ array:2 [▼
0 => array:2 [▼
"price" => "price_1LkRKDGA4B3lyBQM1AyPTB3g"
"quantity" => 1
]
1 => array:2 [▼
"price" => "price_1LkRLsGA4B3lyBQMgZvay5zZ"
"quantity" => 1
]
]
But if I’m not mistaken, Stripe expects it to be:
^ array:2 [▼
[▼
"price" => "price_1LkRKDGA4B3lyBQM1AyPTB3g"
"quantity" => 1
],
[▼
"price" => "price_1LkRLsGA4B3lyBQMgZvay5zZ"
"quantity" => 1
]
]
The amount of items in $cart may vary, so I can’t ‘hardcode’ the list_items; it needs to be dynamic.
$checkout_session = $stripe->checkout->sessions->create([
'payment_method_types' => ['card'],
'line_items' => $items, // <-- Here is the $items variable
'mode' => 'payment',
'automatic_tax' => [
'enabled' => true,
],
'shipping_options' => [
'shipping_rate_data' => [
'display_name' => 'Bezorging door PostNL',
'type' => 'fixed_amount',
'delivery_estimate' => [
'maximum' => 5,
'minimum' => 2,
],
'fixed_amount' => [
'amount' => 6.25,
'currency' => 'eur',
],
'tax_behavior' => 'inclusive',
],
],
'success_url' => route('checkout.success'),
'cancel_url' => route('checkout.cancel'),
]);
Is there a way to remove the keys from the array to make it an array of hashes, or do I need to do something else?