1
0

stripe_webhook.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php /** @noinspection PhpPossiblePolymorphicInvocationInspection */
  2. use Stripe\Exception\SignatureVerificationException;
  3. use Stripe\StripeClient;
  4. use Stripe\Webhook;
  5. $payload = @file_get_contents('php://input');
  6. if(!$payload) {
  7. exit();
  8. }
  9. $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? "";
  10. $event = null;
  11. try {
  12. $stripe = new StripeClient(STRIPE_SECRET_KEY);
  13. $event = Webhook::constructEvent($payload, $sig_header, STRIPE_WEBHOOK_SECRET);
  14. $event_type_parts = explode(".", $event->type);
  15. $event_action = array_pop($event_type_parts);
  16. $event_entity = implode(".", $event_type_parts);
  17. // Handle the event
  18. switch($event_entity) {
  19. case "invoice": {
  20. /** @var \Stripe\Invoice $invoice */
  21. $invoice = $event->data->object;
  22. $stripe_customer = $stripe->customers->retrieve($invoice->customer);
  23. $location = Location::queryOne(["stripe_customer_id" => $stripe_customer->id]);
  24. if(!$location) {
  25. goto HTTP_OK;
  26. }
  27. switch($event_action) {
  28. case "payment_succeeded": {
  29. $test_id = $invoice->metadata->test_id ?? null;
  30. if($test_id) {
  31. $test = Test::get($test_id);
  32. $test->dts_paid = DB::dts();
  33. $test->commit();
  34. }
  35. break;
  36. }
  37. }
  38. break;
  39. }
  40. default:
  41. http_response_code(400);
  42. exit();
  43. }
  44. }
  45. catch(UnexpectedValueException $e) {
  46. // Invalid payload
  47. http_response_code(400);
  48. exit();
  49. }
  50. catch(SignatureVerificationException $e) {
  51. http_response_code(400);
  52. exit();
  53. }
  54. catch(Exception $e) {
  55. http_response_code(400);
  56. die($e->getMessage());
  57. }
  58. HTTP_OK:
  59. http_response_code(200);
  60. exit;