WebOrbiton
v1.1.0.0

StocketBase

512 lines · 19.9 KB
  1. <?php
  2. ​
  3. declare(strict_types=1);
  4. ​
  5. require_once __DIR__ . '/includes/config.php';
  6. require_once __DIR__ . '/includes/database.php';
  7. require_once __DIR__ . '/includes/site-front.php';
  8. ​
  9. header('Content-Type: application/json');
  10. ​
  11. const WEBHOOK_TOLERANCE_SECONDS = 300;
  12. ​
  13. $settings = SiteFront::settings();
  14. $rawBody = (string) file_get_contents('php://input');
  15. ​
  16. $stripeSignature = (string) ($_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '');
  17. $polarSignature = (string) ($_SERVER['HTTP_WEBHOOK_SIGNATURE'] ?? '');
  18. ​
  19. if ($stripeSignature !== '') {
  20. $provider = 'stripe';
  21. $webhookSecret = (string) $settings['payment_webhook_secret'];
  22. } elseif ($polarSignature !== '') {
  23. $provider = 'polar';
  24. $webhookSecret = (string) ($settings['payment_polar_webhook_secret'] !== '' ? $settings['payment_polar_webhook_secret'] : $settings['payment_webhook_secret']);
  25. } else {
  26. webhookRespond(400, ['error' => 'Missing signature header.']);
  27. }
  28. ​
  29. if ($webhookSecret === '') {
  30. webhookRespond(503, ['error' => 'Webhook secret not configured.']);
  31. }
  32. ​
  33. if ($provider === 'stripe') {
  34. if (!verifyStripeSignature($rawBody, $stripeSignature, $webhookSecret)) {
  35. webhookRespond(400, ['error' => 'Invalid signature.']);
  36. }
  37. } else {
  38. $polarWebhookId = (string) ($_SERVER['HTTP_WEBHOOK_ID'] ?? '');
  39. $polarTimestamp = (string) ($_SERVER['HTTP_WEBHOOK_TIMESTAMP'] ?? '');
  40. if (!verifyStandardWebhookSignature($rawBody, $polarWebhookId, $polarTimestamp, $polarSignature, $webhookSecret)) {
  41. webhookRespond(400, ['error' => 'Invalid signature.']);
  42. }
  43. }
  44. ​
  45. $payload = json_decode($rawBody, true);
  46. if (!is_array($payload)) {
  47. webhookRespond(400, ['error' => 'Invalid JSON payload.']);
  48. }
  49. ​
  50. $eventId = $provider === 'polar' ? (string) ($_SERVER['HTTP_WEBHOOK_ID'] ?? '') : (string) ($payload['id'] ?? '');
  51. $eventType = (string) ($payload['type'] ?? ($payload['event'] ?? ''));
  52. ​
  53. if ($eventId === '' || $eventType === '') {
  54. webhookRespond(400, ['error' => 'Missing event id or type.']);
  55. }
  56. ​
  57. $usersDb = Database::users();
  58. ​
  59. $existingStatement = $usersDb->prepare(
  60. 'SELECT id, processing_status FROM payment_webhook_events WHERE provider = :provider AND event_id = :event_id LIMIT 1'
  61. );
  62. $existingStatement->execute(['provider' => $provider, 'event_id' => $eventId]);
  63. $existingEvent = $existingStatement->fetch();
  64. ​
  65. if ($existingEvent && in_array($existingEvent['processing_status'], ['processed', 'ignored'], true)) {
  66. webhookRespond(200, ['status' => 'already_processed']);
  67. }
  68. ​
  69. if ($existingEvent) {
  70. $webhookRowId = (int) $existingEvent['id'];
  71. $usersDb->prepare("UPDATE payment_webhook_events SET processing_status = 'received', processing_error = NULL WHERE id = :id")
  72. ->execute(['id' => $webhookRowId]);
  73. } else {
  74. try {
  75. $usersDb->prepare(
  76. 'INSERT INTO payment_webhook_events (provider, event_id, event_type, payload, processing_status) VALUES (:provider, :event_id, :event_type, :payload, :status)'
  77. )->execute([
  78. 'provider' => $provider,
  79. 'event_id' => $eventId,
  80. 'event_type' => $eventType,
  81. 'payload' => $rawBody,
  82. 'status' => 'received',
  83. ]);
  84. } catch (PDOException $exception) {
  85. webhookRespond(200, ['status' => 'already_processing']);
  86. }
  87. $webhookRowId = (int) $usersDb->lastInsertId();
  88. }
  89. ​
  90. try {
  91. processWebhookEvent($usersDb, $provider, $eventType, $payload);
  92. ​
  93. $usersDb->prepare("UPDATE payment_webhook_events SET processing_status = 'processed', processed_at = NOW() WHERE id = :id")
  94. ->execute(['id' => $webhookRowId]);
  95. ​
  96. webhookRespond(200, ['status' => 'processed']);
  97. } catch (Throwable $exception) {
  98. error_log('StocketBase webhook: ' . $exception->getMessage());
  99. $usersDb->prepare("UPDATE payment_webhook_events SET processing_status = 'failed', processing_error = :error WHERE id = :id")
  100. ->execute(['id' => $webhookRowId, 'error' => substr($exception->getMessage(), 0, 500)]);
  101. ​
  102. webhookRespond(500, ['error' => 'Processing failed.']);
  103. }
  104. ​
  105. function webhookRespond(int $status, array $body): never
  106. {
  107. http_response_code($status);
  108. echo json_encode($body);
  109. exit;
  110. }
  111. ​
  112. function verifyStripeSignature(string $payload, string $signatureHeader, string $secret): bool
  113. {
  114. $timestamp = '';
  115. $signatures = [];
  116. foreach (explode(',', $signatureHeader) as $piece) {
  117. $pair = explode('=', trim($piece), 2);
  118. if (count($pair) !== 2) {
  119. continue;
  120. }
  121. if ($pair[0] === 't') {
  122. $timestamp = $pair[1];
  123. } elseif ($pair[0] === 'v1') {
  124. $signatures[] = $pair[1];
  125. }
  126. }
  127. ​
  128. if ($timestamp === '' || !ctype_digit($timestamp) || empty($signatures)) {
  129. return false;
  130. }
  131. ​
  132. if (abs(time() - (int) $timestamp) > WEBHOOK_TOLERANCE_SECONDS) {
  133. return false;
  134. }
  135. ​
  136. $expected = hash_hmac('sha256', $timestamp . '.' . $payload, $secret);
  137. foreach ($signatures as $signature) {
  138. if (hash_equals($expected, $signature)) {
  139. return true;
  140. }
  141. }
  142. ​
  143. return false;
  144. }
  145. ​
  146. function verifyStandardWebhookSignature(string $payload, string $webhookId, string $timestamp, string $signatureHeader, string $secret): bool
  147. {
  148. if ($webhookId === '' || $timestamp === '' || !ctype_digit($timestamp)) {
  149. return false;
  150. }
  151. ​
  152. if (abs(time() - (int) $timestamp) > WEBHOOK_TOLERANCE_SECONDS) {
  153. return false;
  154. }
  155. ​
  156. $key = str_starts_with($secret, 'whsec_') ? (string) base64_decode(substr($secret, 6), true) : $secret;
  157. if ($key === '') {
  158. return false;
  159. }
  160. ​
  161. $expected = base64_encode(hash_hmac('sha256', $webhookId . '.' . $timestamp . '.' . $payload, $key, true));
  162. ​
  163. foreach (preg_split('/\s+/', trim($signatureHeader)) ?: [] as $entry) {
  164. $parts = explode(',', $entry, 2);
  165. if (count($parts) === 2 && $parts[0] === 'v1' && hash_equals($expected, $parts[1])) {
  166. return true;
  167. }
  168. }
  169. ​
  170. return false;
  171. }
  172. ​
  173. function processWebhookEvent(PDO $usersDb, string $provider, string $eventType, array $payload): void
  174. {
  175. $data = $payload['data']['object'] ?? ($payload['data'] ?? $payload);
  176. if (!is_array($data)) {
  177. return;
  178. }
  179. ​
  180. $normalizedType = strtolower($eventType);
  181. $metadata = is_array($data['metadata'] ?? null) ? $data['metadata'] : [];
  182. $orderId = isset($metadata['order_id']) ? (int) $metadata['order_id'] : 0;
  183. ​
  184. if ($orderId > 0) {
  185. $isStripePaid = $provider === 'stripe'
  186. && (($normalizedType === 'checkout.session.completed' && ($data['payment_status'] ?? '') === 'paid')
  187. || $normalizedType === 'checkout.session.async_payment_succeeded');
  188. $isPolarPaid = $provider === 'polar' && $normalizedType === 'order.paid';
  189. ​
  190. if ($isStripePaid || $isPolarPaid) {
  191. processOrderPaymentEvent($usersDb, $provider, $data, $orderId);
  192. return;
  193. }
  194. ​
  195. if ($provider === 'stripe' && in_array($normalizedType, ['checkout.session.expired', 'checkout.session.async_payment_failed'], true)) {
  196. markOrderFailed($usersDb, $orderId, $normalizedType === 'checkout.session.expired' ? 'Checkout session expired' : 'Payment failed');
  197. return;
  198. }
  199. ​
  200. if ($provider === 'polar' && $normalizedType === 'order.refunded') {
  201. processRefundEvent($usersDb, $provider, $data, $orderId);
  202. return;
  203. }
  204. }
  205. ​
  206. if ($provider === 'stripe' && $normalizedType === 'charge.refunded') {
  207. processRefundEvent($usersDb, $provider, $data, 0);
  208. return;
  209. }
  210. ​
  211. if ($provider === 'stripe' && $normalizedType === 'checkout.session.completed' && ($data['mode'] ?? '') === 'subscription') {
  212. processStripeSubscriptionCheckout($usersDb, $data);
  213. return;
  214. }
  215. ​
  216. if ($provider === 'stripe' && ($metadata['checkout_kind'] ?? '') === 'one_time'
  217. && (($normalizedType === 'checkout.session.completed' && ($data['payment_status'] ?? '') === 'paid') || $normalizedType === 'checkout.session.async_payment_succeeded')) {
  218. $productId = (int) ($metadata['product_id'] ?? 0);
  219. $customer = $data['customer'] ?? '';
  220. upsertSubscription($usersDb, 'stripe', (string) ($data['id'] ?? ''), findUserAccountId($usersDb, $data), [
  221. 'status' => 'active',
  222. 'provider_customer_id' => is_array($customer) ? (string) ($customer['id'] ?? '') : ((string) $customer !== '' ? (string) $customer : null),
  223. 'product_id' => $productId > 0 ? $productId : null,
  224. 'plan_code' => 'lifetime',
  225. ]);
  226. return;
  227. }
  228. ​
  229. if (str_contains($normalizedType, 'subscription')) {
  230. processSubscriptionEvent($usersDb, $provider, $normalizedType, $data);
  231. return;
  232. }
  233. ​
  234. if (($orderId === 0) && SiteFront::settings()['subscription_interval'] === 'lifetime') {
  235. processLifetimeEvent($usersDb, $provider, $normalizedType, $data);
  236. }
  237. }
  238. ​
  239. function markOrderFailed(PDO $usersDb, int $orderId, string $note): void
  240. {
  241. $update = $usersDb->prepare("UPDATE orders SET status = 'failed' WHERE id = :id AND status = 'pending'");
  242. $update->execute(['id' => $orderId]);
  243. if ($update->rowCount() > 0) {
  244. $usersDb->prepare("INSERT INTO order_status_history (order_id, status, note) VALUES (:order_id, 'failed', :note)")
  245. ->execute(['order_id' => $orderId, 'note' => $note]);
  246. }
  247. }
  248. ​
  249. function processOrderPaymentEvent(PDO $usersDb, string $provider, array $data, int $orderId): void
  250. {
  251. $orderStatement = $usersDb->prepare('SELECT * FROM orders WHERE id = :id LIMIT 1');
  252. $orderStatement->execute(['id' => $orderId]);
  253. $order = $orderStatement->fetch();
  254. ​
  255. if (!$order || !in_array($order['status'], ['pending', 'failed'], true)) {
  256. return;
  257. }
  258. ​
  259. if ($provider === 'stripe') {
  260. $paidAmount = isset($data['amount_total']) ? (int) $data['amount_total'] : null;
  261. $paidCurrency = strtoupper((string) ($data['currency'] ?? ''));
  262. if ($paidAmount === null || $paidAmount !== (int) $order['total_cents'] || ($paidCurrency !== '' && $paidCurrency !== strtoupper((string) $order['currency']))) {
  263. $usersDb->prepare("INSERT INTO order_status_history (order_id, status, note) VALUES (:order_id, :status, :note)")
  264. ->execute([
  265. 'order_id' => $orderId,
  266. 'status' => $order['status'],
  267. 'note' => 'Payment amount mismatch: received ' . (string) $paidAmount . ' ' . $paidCurrency . ', expected ' . (int) $order['total_cents'] . ' ' . $order['currency'],
  268. ]);
  269. throw new RuntimeException('Payment amount mismatch for order ' . $orderId);
  270. }
  271. }
  272. ​
  273. $providerCheckoutId = (string) ($data['id'] ?? '');
  274. $paymentIntent = $data['payment_intent'] ?? null;
  275. $providerPaymentId = is_array($paymentIntent) ? (string) ($paymentIntent['id'] ?? '') : (string) ($paymentIntent ?? ($data['id'] ?? ''));
  276. $customer = $data['customer'] ?? ($data['customer_id'] ?? '');
  277. $providerCustomerId = is_array($customer) ? (string) ($customer['id'] ?? '') : (string) $customer;
  278. ​
  279. require_once __DIR__ . '/includes/orders.php';
  280. Orders::markPaid($orderId, [
  281. 'provider' => $provider,
  282. 'checkout_id' => $providerCheckoutId,
  283. 'payment_id' => $providerPaymentId,
  284. 'customer_id' => $providerCustomerId,
  285. ], 'Payment confirmed via webhook');
  286. }
  287. ​
  288. function processRefundEvent(PDO $usersDb, string $provider, array $data, int $orderId): void
  289. {
  290. require_once __DIR__ . '/includes/orders.php';
  291. ​
  292. if ($orderId <= 0 && $provider === 'stripe') {
  293. $paymentIntent = $data['payment_intent'] ?? '';
  294. $paymentIntentId = is_array($paymentIntent) ? (string) ($paymentIntent['id'] ?? '') : (string) $paymentIntent;
  295. if ($paymentIntentId === '') {
  296. return;
  297. }
  298. $statement = $usersDb->prepare("SELECT id FROM orders WHERE provider = 'stripe' AND provider_payment_id = :payment_id LIMIT 1");
  299. $statement->execute(['payment_id' => $paymentIntentId]);
  300. $orderId = (int) $statement->fetchColumn();
  301. }
  302. if ($orderId <= 0) {
  303. return;
  304. }
  305. ​
  306. if ($provider === 'stripe') {
  307. $amount = (int) ($data['amount'] ?? 0);
  308. $refunded = (int) ($data['amount_refunded'] ?? 0);
  309. if (empty($data['refunded']) && ($amount <= 0 || $refunded < $amount)) {
  310. Orders::addHistory($orderId, (string) (Orders::find($orderId)['status'] ?? 'paid'), 'Partial refund in Stripe: ' . $refunded . ' of ' . $amount);
  311. ​
  312. return;
  313. }
  314. }
  315. ​
  316. Orders::close($orderId, 'refunded', 'Refunded at ' . ucfirst($provider), null, true);
  317. }
  318. ​
  319. function findUserAccountId(PDO $usersDb, array $data): ?int
  320. {
  321. $metadata = is_array($data['metadata'] ?? null) ? $data['metadata'] : [];
  322. $metadataUserId = (int) ($metadata['user_account_id'] ?? 0);
  323. if ($metadataUserId > 0) {
  324. $statement = $usersDb->prepare('SELECT id FROM user_accounts WHERE id = :id LIMIT 1');
  325. $statement->execute(['id' => $metadataUserId]);
  326. if ($statement->fetch()) {
  327. return $metadataUserId;
  328. }
  329. }
  330. ​
  331. $email = strtolower(trim((string) (
  332. $data['customer_email'] ??
  333. $data['email'] ??
  334. $data['customer_details']['email'] ??
  335. (is_array($data['customer'] ?? null) ? ($data['customer']['email'] ?? null) : null) ??
  336. ''
  337. )));
  338. ​
  339. if ($email === '') {
  340. return null;
  341. }
  342. ​
  343. $statement = $usersDb->prepare("SELECT id FROM user_accounts WHERE LOWER(email) = :email AND status = 'active' AND email_verified_at IS NOT NULL LIMIT 1");
  344. $statement->execute(['email' => $email]);
  345. $account = $statement->fetch();
  346. ​
  347. return $account ? (int) $account['id'] : null;
  348. }
  349. ​
  350. function mapSubscriptionStatus(string $eventType, array $data): ?string
  351. {
  352. if (str_contains($eventType, 'deleted') || str_contains($eventType, 'revoked') || str_contains($eventType, 'canceled') || str_contains($eventType, 'cancelled')) {
  353. return 'canceled';
  354. }
  355. ​
  356. return match (strtolower((string) ($data['status'] ?? ''))) {
  357. 'active' => 'active',
  358. 'trialing' => 'trialing',
  359. 'past_due', 'unpaid', 'incomplete' => 'past_due',
  360. 'canceled', 'cancelled', 'paused' => 'canceled',
  361. 'incomplete_expired', 'expired' => 'expired',
  362. default => null,
  363. };
  364. }
  365. ​
  366. function subscriptionPeriodEnd(array $data): ?string
  367. {
  368. $raw = $data['current_period_end'] ?? ($data['items']['data'][0]['current_period_end'] ?? null);
  369. if (empty($raw)) {
  370. return null;
  371. }
  372. ​
  373. $timestamp = is_numeric($raw) ? (int) $raw : strtotime((string) $raw);
  374. ​
  375. return $timestamp ? date('Y-m-d H:i:s', $timestamp) : null;
  376. }
  377. ​
  378. function upsertSubscription(PDO $usersDb, string $provider, string $subscriptionId, ?int $userAccountId, array $fields): void
  379. {
  380. $existingStatement = $usersDb->prepare(
  381. 'SELECT id FROM subscriptions WHERE provider = :provider AND provider_subscription_id = :sub_id LIMIT 1'
  382. );
  383. $existingStatement->execute(['provider' => $provider, 'sub_id' => $subscriptionId]);
  384. $existing = $existingStatement->fetch();
  385. ​
  386. if ($existing) {
  387. $sets = [];
  388. $params = ['id' => $existing['id']];
  389. foreach (['status', 'current_period_end', 'provider_customer_id', 'product_id', 'plan_code'] as $column) {
  390. if (array_key_exists($column, $fields) && $fields[$column] !== null) {
  391. $sets[] = $column . ' = :' . $column;
  392. $params[$column] = $fields[$column];
  393. }
  394. }
  395. if (($fields['status'] ?? null) === 'canceled') {
  396. $sets[] = 'canceled_at = COALESCE(canceled_at, NOW())';
  397. }
  398. if (!empty($sets)) {
  399. $usersDb->prepare('UPDATE subscriptions SET ' . implode(', ', $sets) . ' WHERE id = :id')->execute($params);
  400. }
  401. return;
  402. }
  403. ​
  404. if ($userAccountId === null) {
  405. return;
  406. }
  407. ​
  408. $usersDb->prepare(
  409. 'INSERT INTO subscriptions (user_account_id, provider, provider_customer_id, provider_subscription_id, plan_code, product_id, status, current_period_end)
  410. VALUES (:user_id, :provider, :customer_id, :sub_id, :plan_code, :product_id, :status, :period_end)'
  411. )->execute([
  412. 'user_id' => $userAccountId,
  413. 'provider' => $provider,
  414. 'customer_id' => $fields['provider_customer_id'] ?? null,
  415. 'sub_id' => $subscriptionId,
  416. 'plan_code' => $fields['plan_code'] ?? null,
  417. 'product_id' => $fields['product_id'] ?? null,
  418. 'status' => $fields['status'] ?? 'active',
  419. 'period_end' => $fields['current_period_end'] ?? null,
  420. ]);
  421. }
  422. ​
  423. function processStripeSubscriptionCheckout(PDO $usersDb, array $data): void
  424. {
  425. $subscriptionId = is_array($data['subscription'] ?? null) ? (string) ($data['subscription']['id'] ?? '') : (string) ($data['subscription'] ?? '');
  426. if ($subscriptionId === '') {
  427. return;
  428. }
  429. ​
  430. $metadata = is_array($data['metadata'] ?? null) ? $data['metadata'] : [];
  431. $productId = (int) ($metadata['product_id'] ?? 0);
  432. $customer = $data['customer'] ?? '';
  433. ​
  434. upsertSubscription($usersDb, 'stripe', $subscriptionId, findUserAccountId($usersDb, $data), [
  435. 'status' => 'active',
  436. 'provider_customer_id' => is_array($customer) ? (string) ($customer['id'] ?? '') : ((string) $customer !== '' ? (string) $customer : null),
  437. 'product_id' => $productId > 0 ? $productId : null,
  438. 'plan_code' => $productId > 0 ? (string) $productId : null,
  439. ]);
  440. }
  441. ​
  442. function processSubscriptionEvent(PDO $usersDb, string $provider, string $eventType, array $data): void
  443. {
  444. $subscriptionId = (string) ($data['id'] ?? '');
  445. if ($subscriptionId === '') {
  446. return;
  447. }
  448. ​
  449. $metadata = is_array($data['metadata'] ?? null) ? $data['metadata'] : [];
  450. $productId = (int) ($metadata['product_id'] ?? 0);
  451. $customer = $data['customer'] ?? ($data['customer_id'] ?? '');
  452. $customerId = is_array($customer) ? (string) ($customer['id'] ?? '') : (string) $customer;
  453. $planCode = (string) ($data['plan']['id'] ?? ($data['product_id'] ?? ''));
  454. ​
  455. upsertSubscription($usersDb, $provider, $subscriptionId, findUserAccountId($usersDb, $data), [
  456. 'status' => mapSubscriptionStatus($eventType, $data),
  457. 'current_period_end' => subscriptionPeriodEnd($data),
  458. 'provider_customer_id' => $customerId !== '' ? $customerId : null,
  459. 'product_id' => $productId > 0 ? $productId : null,
  460. 'plan_code' => $planCode !== '' ? $planCode : null,
  461. ]);
  462. }
  463. ​
  464. function processLifetimeEvent(PDO $usersDb, string $provider, string $eventType, array $data): void
  465. {
  466. $paymentId = (string) ($data['id'] ?? '');
  467. if ($paymentId === '') {
  468. return;
  469. }
  470. ​
  471. if ($provider === 'polar' && $eventType === 'order.refunded') {
  472. $usersDb->prepare(
  473. "UPDATE subscriptions SET status = 'canceled', canceled_at = NOW() WHERE provider = :provider AND provider_subscription_id = :id AND plan_code = 'lifetime'"
  474. )->execute(['provider' => $provider, 'id' => $paymentId]);
  475. return;
  476. }
  477. ​
  478. $isPaid = ($provider === 'stripe' && $eventType === 'checkout.session.completed'
  479. && ($data['payment_status'] ?? '') === 'paid' && ($data['mode'] ?? 'payment') === 'payment')
  480. || ($provider === 'polar' && $eventType === 'order.paid');
  481. ​
  482. if (!$isPaid) {
  483. return;
  484. }
  485. ​
  486. $userAccountId = findUserAccountId($usersDb, $data);
  487. if ($userAccountId === null) {
  488. return;
  489. }
  490. ​
  491. $existing = $usersDb->prepare(
  492. 'SELECT id FROM subscriptions WHERE provider = :provider AND provider_subscription_id = :id LIMIT 1'
  493. );
  494. $existing->execute(['provider' => $provider, 'id' => $paymentId]);
  495. if ($existing->fetch()) {
  496. return;
  497. }
  498. ​
  499. $customer = $data['customer'] ?? ($data['customer_id'] ?? '');
  500. $customerId = is_array($customer) ? (string) ($customer['id'] ?? '') : (string) $customer;
  501. ​
  502. $usersDb->prepare(
  503. "INSERT INTO subscriptions (user_account_id, provider, provider_customer_id, provider_subscription_id, plan_code, status, current_period_end)
  504. VALUES (:user_id, :provider, :customer_id, :payment_id, 'lifetime', 'active', NULL)"
  505. )->execute([
  506. 'user_id' => $userAccountId,
  507. 'provider' => $provider,
  508. 'customer_id' => $customerId !== '' ? $customerId : null,
  509. 'payment_id' => $paymentId,
  510. ]);
  511. }
  512. ​