97 lines
2.7 KiB
PHP
97 lines
2.7 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
require __DIR__ . '/common.php';
|
|
|
|
kapvoe_require_post();
|
|
$config = kapvoe_load_config();
|
|
$data = kapvoe_json_input();
|
|
|
|
$required = [
|
|
'product_code',
|
|
'product_name',
|
|
'price',
|
|
'quantity',
|
|
'customer_name',
|
|
'address',
|
|
'postal_code',
|
|
'city',
|
|
'province',
|
|
'phone',
|
|
'email',
|
|
];
|
|
$errors = kapvoe_validate_required($data, $required);
|
|
|
|
if (!filter_var((string)($data['email'] ?? ''), FILTER_VALIDATE_EMAIL)) {
|
|
$errors['email'] = 'Correu electrònic invàlid';
|
|
}
|
|
if (!preg_match('/^\d{5}$/', (string)($data['postal_code'] ?? ''))) {
|
|
$errors['postal_code'] = 'Codi postal invàlid';
|
|
}
|
|
if (!preg_match('/^[0-9+\s]{8,20}$/', (string)($data['phone'] ?? ''))) {
|
|
$errors['phone'] = 'Telèfon invàlid';
|
|
}
|
|
|
|
$price = (float)str_replace(',', '.', (string)$data['price']);
|
|
$quantity = max(1, (int)$data['quantity']);
|
|
|
|
if ($price <= 0) {
|
|
$errors['price'] = 'Preu invàlid';
|
|
}
|
|
|
|
if ($errors) {
|
|
kapvoe_json_response(['ok' => false, 'errors' => $errors], 422);
|
|
}
|
|
|
|
$orderId = 'ORD-' . date('Ymd-His') . '-' . substr(bin2hex(random_bytes(3)), 0, 6);
|
|
$unitAmountCents = (int)round($price * 100);
|
|
|
|
$payload = [
|
|
'order_id' => $orderId,
|
|
'product_code' => trim((string)$data['product_code']),
|
|
'product_name' => trim((string)$data['product_name']),
|
|
'unit_amount_cents' => $unitAmountCents,
|
|
'quantity' => $quantity,
|
|
'customer_name' => trim((string)$data['customer_name']),
|
|
'address' => trim((string)$data['address']),
|
|
'postal_code' => trim((string)$data['postal_code']),
|
|
'city' => trim((string)$data['city']),
|
|
'province' => trim((string)$data['province']),
|
|
'phone' => trim((string)$data['phone']),
|
|
'email' => trim((string)$data['email']),
|
|
];
|
|
|
|
try {
|
|
$session = kapvoe_create_checkout_session($config, $payload);
|
|
|
|
kapvoe_append_order($config, [
|
|
'order_id' => $orderId,
|
|
'created_at' => date('Y-m-d H:i:s'),
|
|
'product_code' => $payload['product_code'],
|
|
'product_name' => $payload['product_name'],
|
|
'unit_price' => $price,
|
|
'quantity' => $quantity,
|
|
'customer_name' => $payload['customer_name'],
|
|
'address' => $payload['address'],
|
|
'postal_code' => $payload['postal_code'],
|
|
'city' => $payload['city'],
|
|
'province' => $payload['province'],
|
|
'phone' => $payload['phone'],
|
|
'email' => $payload['email'],
|
|
'payment_status' => 'pending',
|
|
'stripe_session_id' => $session['id'] ?? '',
|
|
'payment_intent_id' => '',
|
|
]);
|
|
|
|
kapvoe_json_response([
|
|
'ok' => true,
|
|
'checkout_url' => $session['url'] ?? null,
|
|
'order_id' => $orderId,
|
|
]);
|
|
} catch (Throwable $e) {
|
|
kapvoe_json_response([
|
|
'ok' => false,
|
|
'error' => $e->getMessage(),
|
|
], 500);
|
|
}
|