Stripe

Instructions and guidelines to stripe module integration to existing drupal site.

First you will need to download and install stripe to your drupal website either manually or by composer :

composer require “drupal/stripe”

Manual download : https://www.drupal.org/project/stripe
Don’t forget to enable to module.

Then navigate to the module settings page to enter your stripe account details available on your stripe dashboard.

For this example we will be on test environnement but same settings should be done for the live one.

Secondly create a drupal form in a custom module : in this example the custom module name is : custom_stripe

Form file path : web\modules\custom\custom_stripe\src\Form\CustomStripeForm.php

Sample working Form php file in multiple parts :

1. Namespace and stripe library integration :

namespace Drupal\custom_stripe\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;
use Stripe\Charge;
use Stripe\Stripe;
use Stripe\Error\Card;
use Drupal\Component\Serialization\Json;

2. Build form class : this is where you set the stripe element to your form

public function buildForm(array $form, FormStateInterface $form_state) {
    $uid = \Drupal::currentUser()->id();
    $form['first'] = [
      '#type' => 'textfield',
      '#title' => 'First Name',
    ];
    $form['last'] = [
      '#type' => 'textfield',
      '#title' => 'Last Name',
    ];
    // default amount set to 100 USD cents
    $form['amount_centime'] = [
      '#type' => 'hidden',
      '#value' => $total_amount * 100,
    ];
    $form['stripe'] = [
      '#type' => 'stripe',
      '#title' => $this->t('Credit card'),
      //Selectors are gonna be looked within the enclosing form only.
      "#stripe_selectors" => [
        'first_name' => ':input[name="first"]',
        'last_name' => ':input[name="last"]',
      ],
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Pay'),
    ];
    $form['#theme'] = 'custom-stripe-form-html';
    return $form;
  }

3. Form validation : this is where all the action is.

Try in case of successful payment and the catch handles errors and rejections.

public function validateForm(array &$form, FormStateInterface $form_state) {
    // Process the transaction with Stripe.com.
      Stripe::setApiKey('sk_test_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
      try {
        $uid = \Drupal::currentUser()->id();
        $email = \Drupal::currentUser()->getEmail();
        $charge = Charge::create(array(
          "amount" => $form_state->getValue('amount_centime'),
          "currency" => "eur",
          "source" => $form_state->getValue('stripe'),
          "description" => $desc,
          "statement_descriptor" => $desc,
          "receipt_email" =>  $email)
        );
        $response = $charge->getLastResponse()->body;
        $json = json_decode($response, true);
        $charge_id = $json['id'];
        $uid = \Drupal::currentUser()->id();
        $paid = $json['paid'];
        if ($paid) {
          $success = 1;
          $content = $jsonResponse->getContent();
          $result = json_decode($content, true);
          if($result){
            $form_state->setValue('status', TRUE);
          } else {
            $form_state->setValue('status', FALSE);
          }
        } else {
          $success = 0;
        }
        $code = $json['outcome']['type'];
        // do something with responses above here -- process payment
      }
      catch (Card $e) {
        $uid = \Drupal::currentUser()->id();
        $email = \Drupal::currentUser()->getEmail();
        $response = $e->httpBody;
        $message = $e->getMessage();
        $code = $e->getDeclineCode();
        $charge_id = $e->jsonBody['error']['charge'];
        $success = 0;

        $form_state->setValue('status', FALSE);

        // do something with error responses here

        return;
      }

  }

4. Redirection depending on payment outcome.

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $payment_status = $form_state->getValue('status');

    if($payment_status) {
      $form_state->setRedirect("payment_success_route");
    } else {
      $form_state->setRedirect("payment_error_route");
    }
  }

5. Result – form with stripe element :

Please follow and like us:

Leave a Reply

Your email address will not be published. Required fields are marked *