-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocesar_pago.php
More file actions
47 lines (44 loc) · 1.72 KB
/
Copy pathprocesar_pago.php
File metadata and controls
47 lines (44 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
session_start();
require __DIR__ . '/vendor/autoload.php';
MercadoPago\SDK::setAccessToken('TU_ACCESS_TOKEN'); // Reemplaza con tu access token real
header('Content-Type: application/json');
$data = json_decode(file_get_contents('php://input'), true);
// Siempre calcula el monto real desde el carrito y la base de datos
include 'includes/db.php';
$productos = [];
$total = 0;
if (!empty($_SESSION['carrito'])) {
$ids = implode(",", array_map('intval', array_keys($_SESSION['carrito'])));
if (!empty($ids)) {
$sql = "SELECT * FROM productos WHERE id IN ($ids)";
$result = $conexion->query($sql);
while ($row = $result->fetch_assoc()) {
$row['cantidad'] = $_SESSION['carrito'][$row['id']];
$row['subtotal'] = $row['cantidad'] * $row['precio'];
$productos[] = $row;
$total += $row['subtotal'];
}
}
}
try {
$payment = new MercadoPago\Payment();
$payment->transaction_amount = round($total,2);
$payment->token = $data['token'];
$payment->description = "Compra en Carpintería";
$payment->installments = (int)$data['installments'];
$payment->payment_method_id = $data['paymentMethodId'];
$payment->payer = array(
"email" => $data['email']
);
$payment->save();
if ($payment->status == 'approved') {
// Limpia el carrito solo si el pago fue exitoso
unset($_SESSION['carrito']);
echo json_encode(['status'=>'approved']);
} else {
echo json_encode(['status'=>'error','message'=>"Pago rechazado: " . $payment->status_detail]);
}
} catch(Exception $e) {
echo json_encode(['status'=>'error','message'=>'Error: '.$e->getMessage()]);
}