You are here

function commerce_stripe_pi_webhook in Commerce Stripe Payment Intent 7

Get Stripe async response after payment intent.

1 string reference to 'commerce_stripe_pi_webhook'
commerce_stripe_pi_menu in ./commerce_stripe_pi.module
Implements hook_menu().

File

./commerce_stripe_pi.module, line 86
Payment intent stripe payment integration.

Code

function commerce_stripe_pi_webhook() {
  commerce_stripe_pi_load_library();
  $payload = @file_get_contents('php://input');
  $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
  $payment_method = commerce_payment_method_instance_load('commerce_stripe_pi|commerce_payment_commerce_stripe_pi');
  $endpoint_secret = $payment_method['settings']['webhooks']['secret'];
  $event = NULL;
  try {
    if (empty($endpoint_secret)) {
      watchdog('commerce_stripe_pi', 'Webhook: Secret signature is not defined, please get the secret key from stripe dashboard and update your stripe pi payment settings for security reasons.', array(), WATCHDOG_WARNING);
      $event = Event::constructFrom(json_decode($payload, TRUE));
    }
    else {
      $event = \Stripe\Webhook::constructEvent($payload, $sig_header, $endpoint_secret);
    }
  } catch (\UnexpectedValueException $e) {
    watchdog('commerce_stripe_pi', 'Webhook: Invalid payload %payload', array(
      '%payload' => $payload,
    ), WATCHDOG_ERROR);

    // Invalid payload.
    http_response_code(400);
    drupal_exit();
  } catch (\Stripe\Exception\SignatureVerificationException $e) {
    watchdog('commerce_stripe_pi', 'Webhook: Invalid signature %signature for payload %payload', array(
      '%signature' => $sig_header,
      '%payload' => $payload,
    ), WATCHDOG_ERROR);

    // Invalid signature
    http_response_code(400);
    drupal_exit();
  }
  $unexpected = FALSE;

  // Handle the event.
  switch ($event->type) {
    case 'payment_intent.succeeded':
    case 'payment_intent.payment_failed':
      watchdog('commerce_stripe_pi', 'Webhook: Handle event type `%type` for order `%order` with event : %event', array(
        '%type' => $event->type,
        '%order' => isset($event->data->object->metadata['order_id']) ? $event->data->object->metadata['order_id'] : '',
        '%event' => print_r($event, TRUE),
      ), WATCHDOG_DEBUG);

      // Contains a \Stripe\PaymentIntent.
      $paymentIntent = $event->data->object;

      // Get order id from metadata.
      $order_id = $paymentIntent->metadata['order_id'];
      commerce_stripe_pi_create_transaction($order_id, $paymentIntent);
      break;
    default:

      // Unexpected event type.
      $unexpected = TRUE;
  }
  drupal_alter('commerce_stripe_pi_webhook', $event, $unexpected);
  if ($unexpected) {
    watchdog('commerce_stripe_pi', 'Webhook: Unexpected event type `%type` with event : %event', array(
      '%type' => $event->type,
      '%event' => print_r($event, TRUE),
    ), WATCHDOG_DEBUG);
    http_response_code(400);
    drupal_exit();
  }
}