store->all('SELECT id, name, unit_minor, currency FROM products WHERE active = 1 AND merchant_id = 10 ORDER BY unit_minor'); } public function checkout(Actor $actor, array $input): array { if (array_diff(array_keys($input), ['operation', 'currency', 'items', 'scenario'])) { throw new Problem('untrusted_fields'); } $key = $input['operation'] ?? ''; if (!is_string($key)) { throw new Problem('invalid_operation'); } Store::operation($key); $currency = $input['currency'] ?? null; if ($currency !== 'usd') { throw new Problem('currency_mismatch'); } $items = $input['items'] ?? null; if (!is_array($items) || !array_is_list($items) || count($items) < 1 || count($items) > 10) { throw new Problem('invalid_items'); } $seen = []; foreach ($items as $item) { if (!is_array($item) || array_diff(array_keys($item), ['product_id', 'quantity'])) { throw new Problem('untrusted_fields'); } if (!is_int($item['quantity'] ?? null) || $item['quantity'] < 1 || $item['quantity'] > 10) { throw new Problem('invalid_quantity'); } if (!is_string($item['product_id'] ?? null) || strlen($item['product_id']) > 40 || isset($seen[$item['product_id']])) { throw new Problem('invalid_items'); } $seen[$item['product_id']] = true; } $items = array_map(fn (array $item): array => ['product_id' => $item['product_id'], 'quantity' => $item['quantity']], $items); usort($items, fn (array $a, array $b): int => strcmp($a['product_id'], $b['product_id'])); $scenario = $input['scenario'] ?? 'success'; if (!in_array($scenario, ['success', 'timeout'], true)) { throw new Problem('unknown_scenario'); } $fingerprint = hash('sha256', json_encode([$currency, $items, $scenario], JSON_THROW_ON_ERROR)); $operation = $this->store->atomic(function () use ($actor, $key, $currency, $items, $fingerprint): array { $existing = $this->store->one('SELECT * FROM checkout_operations WHERE actor_id = ? AND client_key = ?', [$actor->id, $key]); if ($existing) { if (!hash_equals($existing['fingerprint'], $fingerprint)) { throw new Problem('idempotency_mismatch', 409); } return $existing; } $snapshot = []; $amount = 0; foreach ($items as $item) { $product = $this->store->one('SELECT * FROM products WHERE id = ? AND active = 1 AND merchant_id = 10', [$item['product_id']]); if (!$product) { throw new Problem('unknown_product'); } if ($product['currency'] !== $currency) { throw new Problem('currency_mismatch'); } $amount += $product['unit_minor'] * $item['quantity']; $snapshot[] = ['product_id' => $product['id'], 'name' => $product['name'], 'unit_minor' => $product['unit_minor'], 'quantity' => $item['quantity']]; } $id = Store::id(); $operation = ['id' => Store::id(), 'order_id' => $id]; $this->store->run('INSERT INTO orders (id, owner_id, merchant_id, currency, amount_minor, items, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)', [$id, $actor->id, 10, $currency, $amount, json_encode($snapshot, JSON_THROW_ON_ERROR), time()]); $this->store->run('INSERT INTO checkout_operations (id, actor_id, client_key, fingerprint, order_id, created_at) VALUES (?, ?, ?, ?, ?, ?)', [$operation['id'], $actor->id, $key, $fingerprint, $id, time()]); return $this->store->one('SELECT * FROM checkout_operations WHERE id = ?', [$operation['id']]); }); $order = $this->order($actor, $operation['order_id']); if (!$order['session_id']) { if (!$this->claimAttempt('checkout_operations', $operation['id'])) { return ['order' => $this->order($actor, $order['id']), 'notice' => 'offline_checkout_created']; } try { $session = $this->gateway->createSession($order, 'lab.checkout.'.$operation['id'], $scenario); SandboxGuard::object($session); if ($session['order_id'] !== $order['id'] || $session['amount_minor'] !== $order['amount_minor'] || $session['currency'] !== $order['currency']) { throw new Problem('session_mismatch', 502); } $this->store->atomic(function () use ($session, $order): void { $current = $this->store->one('SELECT session_id FROM orders WHERE id = ?', [$order['id']]); if ($current['session_id'] !== null && $current['session_id'] !== $session['id']) { throw new Problem('session_mismatch', 502); } $this->store->run('UPDATE orders SET session_id = ? WHERE id = ?', [$session['id'], $order['id']]); }); } catch (GatewayTimeout $error) { return ['order' => $order, 'notice' => 'gateway_timeout']; } } return ['order' => $this->order($actor, $order['id']), 'notice' => 'offline_checkout_created']; } public function order(Actor $actor, string $id): array { $order = $this->store->one('SELECT * FROM orders WHERE id = ? AND owner_id = ?', [$id, $actor->id]); if (!$order) { throw new Problem('order_not_found', 404); } $order['items'] = json_decode($order['items'], true, flags: JSON_THROW_ON_ERROR); return $order; } public function refund(Actor $actor, string $orderId, string $key, int $amount): array { Store::operation($key); $refund = $this->store->atomic(function () use ($actor, $orderId, $key, $amount): array { $order = $this->store->one('SELECT * FROM orders WHERE id = ?', [$orderId]); if (!$order || $actor->role !== 'merchant' || $order['merchant_id'] !== $actor->merchantId || $order['owner_id'] !== $actor->id) { throw new Problem('refund_forbidden', 403); } $existing = $this->store->one('SELECT * FROM refunds WHERE actor_id = ? AND client_key = ?', [$actor->id, $key]); if ($existing) { if ($existing['order_id'] !== $orderId || $existing['amount_minor'] !== $amount) { throw new Problem('idempotency_mismatch', 409); } return $existing; } if ($order['payment_state'] !== 'paid' || $amount < 1 || $amount > $order['amount_minor'] - $order['refunded_minor'] - $order['reserved_refund_minor']) { throw new Problem('refund_balance', 409); } $id = Store::id(); $this->store->run('INSERT INTO refunds (id, actor_id, client_key, order_id, amount_minor, created_at) VALUES (?, ?, ?, ?, ?, ?)', [$id, $actor->id, $key, $orderId, $amount, time()]); $this->store->run("UPDATE orders SET reserved_refund_minor = reserved_refund_minor + ?, refund_state = 'pending' WHERE id = ?", [$amount, $orderId]); return $this->store->one('SELECT * FROM refunds WHERE id = ?', [$id]); }); if ($refund['status'] !== 'reserved' || !$this->claimAttempt('refunds', $refund['id'])) { return $this->order($actor, $orderId); } try { $result = $this->gateway->refund($this->order($actor, $orderId), $amount, 'lab.refund.'.$refund['id']); SandboxGuard::object($result); if ($result['amount_minor'] !== $amount) { throw new Problem('refund_mismatch', 502); } } catch (GatewayTimeout $error) { return $this->order($actor, $orderId); } $this->store->atomic(function () use ($result, $refund, $orderId, $amount): void { $current = $this->store->one('SELECT * FROM refunds WHERE id = ?', [$refund['id']]); if ($current['status'] !== 'reserved' || !in_array($result['status'], ['succeeded', 'failed', 'canceled'], true)) { return; } $this->store->run('UPDATE refunds SET status = ?, gateway_id = ? WHERE id = ?', [$result['status'], $result['id'], $refund['id']]); $this->store->run('UPDATE orders SET reserved_refund_minor = reserved_refund_minor - ?, refunded_minor = refunded_minor + ? WHERE id = ?', [$amount, $result['status'] === 'succeeded' ? $amount : 0, $orderId]); $order = $this->store->one('SELECT * FROM orders WHERE id = ?', [$orderId]); $state = $order['reserved_refund_minor'] > 0 ? 'pending' : ($order['refunded_minor'] === $order['amount_minor'] ? 'refunded' : ($order['refunded_minor'] > 0 ? 'partial' : 'none')); $this->store->run('UPDATE orders SET refund_state = ? WHERE id = ?', [$state, $orderId]); }); return $this->order($actor, $orderId); } private function claimAttempt(string $table, string $id): bool { return $this->store->atomic(function () use ($table, $id): bool { $operation = $this->store->one('SELECT * FROM '.$table.' WHERE id = ?', [$id]); if ($table === 'refunds' && $operation['status'] !== 'reserved') { return false; } if ($table === 'checkout_operations' && $this->store->one('SELECT session_id FROM orders WHERE id = ?', [$operation['order_id']])['session_id'] !== null) { return false; } // API v1 may prune provider idempotency keys after at least 24 hours. if ($operation['created_at'] <= time() - 23 * 3600) { throw new Problem('reconciliation_required', 409); } $this->store->run('UPDATE '.$table.' SET attempted_at = ? WHERE id = ?', [time(), $id]); return true; }); } }