Reputation: 4862
I'm using the PHP MercadoPago SDK module. Here is my code:
$mp = new MP("CLIENT_ID", "CLIENT_SCRET");
foreach ($_SESSION["carrito"] as $value){
$itemCode = $value['tagme'];
$itemDesc = get_pedido($itemCode);
$itemQty = $value['cant']; // it comes from $_POST['cant']
$unitPrice = $value['unit_price'];
$items[] = array(
"title" => $itemDesc,
"quantity" => $itemQty,
"currency_id" => "ARS",
"unit_price" => $unitPrice
);
}
$preference = array(
"items" => $items,
"payer" => array(
'name' => $name,
'email' => $email
),
"back_urls" => array(
'success' => 'http://example.com/success.php',
'pending' => 'http://example.com/pending.php'
)
);
echo '<pre>';print_r($items); echo '</pre>';
$mp->sandbox_mode(TRUE);
$preferenceResult = $mp->create_preference($preference);
The $items
outputs as below:
Array
(
[0] => Array
(
[title] => Test Product
[quantity] => 1
[currency_id] => ARS
[unit_price] => 36
)
[1] => Array
(
[title] => Shipping Cost
[quantity] => 1
[currency_id] => ARS
[unit_price] => 42
)
)
But I got the following error:
Fatal error: Uncaught exception 'Exception' with message 'quantity must be a number' in /home/..../public_html/mercadopago-sdk/mercadopago.php:227 Stack trace: #0 /home/..../public_html/mercadopago-sdk/mercadopago.php(240): MPRestClient::exec('POST', '/checkout/prefe...', Array, 'application/jso...') #1 /home/..../public_html/mercadopago-sdk/mercadopago.php(126): MPRestClient::post('/checkout/prefe...', Array) #2 /home/..../public_html/confirm.php(140): MP->create_preference(Array) #3 {main} thrown in /home/..../public_html/mercadopago-sdk/mercadopago.php on line 227
Any idea?
Upvotes: 0
Views: 2822
Reputation: 4862
I solved the problem by typecasting the quantity to INT.
foreach ($_SESSION["carrito"] as $value){
$itemCode = $value['tagme'];
$itemDesc = get_pedido($itemCode);
$itemQty = $value['cant']; // it comes from $_POST['cant']
$unitPrice = $value['unit_price'];
$items[] = array(
"title" => $itemDesc,
"quantity" => intval($itemQty), // this solved the error
"currency_id" => "ARS",
"unit_price" => $unitPrice
);
}
My quantity seems to be string which comes from hidden and stores in session:
<input type="hidden" name="cant" value="1" />
But, MercadoPago API expects an integer in that field. So, I had to use intval().
Upvotes: 2