You are here

public static function StripeBase::ajaxStripeElementCallback in Stripe 2.x

Webform computed element Ajax callback.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

array The computed element element.

File

src/Element/StripeBase.php, line 270

Class

StripeBase
Provides the base for our Stripe elements

Namespace

Drupal\stripe\Element

Code

public static function ajaxStripeElementCallback(array $form, FormStateInterface $form_state) {
  $config = \Drupal::config('stripe.settings');
  $apikeySecret = $config
    ->get('apikey.' . $config
    ->get('environment') . '.secret');

  // Stripe form element from trigger
  $trigger = $form_state
    ->getTriggeringElement();
  $key = $trigger['#parents'][0];
  $payment_intent = $form_state
    ->getValue([
    $key,
    'payment_intent',
  ]);
  $response = new AjaxResponse();

  // Instantiate our event.
  $event = new StripePaymentEvent($form, $form_state, $key);

  // Dispatch our event to allow modules to update client-side elements of
  // the stripe elements
  $event_dispatcher = \Drupal::service('event_dispatcher');
  $event_dispatcher
    ->dispatch(StripeEvents::PAYMENT, $event);
  $settings = [
    'trigger' => $form_state
      ->getValue([
      $key,
      'trigger',
    ]),
    'error' => $form_state
      ->hasAnyErrors(),
  ];
  $total = $event
    ->getTotal();
  if (!empty($total)) {
    $settings['total'] = $total;
    if ($payment_intent) {
      $stripe = new \Stripe\StripeClient($apikeySecret);
      $stripe->paymentIntents
        ->update($payment_intent, [
        'amount' => $total['amount'],
      ]);
    }
  }
  $billing_details = $event
    ->getBillingDetails();
  if (!empty($billing_details)) {
    $settings['billing_details'] = $billing_details;
  }
  $response
    ->addCommand(new InvokeCommand(NULL, 'stripeUpdatePaymentIntent', [
    $settings,
  ]));
  return $response;
}