Wednesday, 07 August 2019

Integrating the Stripe payment into your web page

Stripe  JavaScript  PHP 

Stripe is one of the popular online payment solutions. It has well-designed APIs and flexible tools for building online businesses. This post shows you how to integrate the Stripe payment into your web page with its PHP API and javascript checkout button.

Download the Stripe PHP API

We can download the Stripe PHP API from GitHub and put the API library under your web server root directory (here, we use WampServer as our web server) and rename the folder as stripe-php.

Config the Stripe secret_key and publishable_key

Under the web server root directory, create a PHP file called config.php to hold your Stripe account's
secret key and publishable key (you can login to your Stripe account to get these keys).

<?php
    $stripe = array(
        "secret_key"      => "sk_test_key",
        "publishable_key" => "pk_test_key"
    );
?>

Create the front-end payment form

Under the web server root directory, create the front-end payment form called index.php. In this example, we use the free HTML template from https://codepen.io/lukepeters/pen/bfFur and its source code can be downloaded from here.

In the PHP file index.php, first we define some variables for the payment:

<?php
    require_once('config.php');
    $customerName = "Tony";
    $customerEmail = "tony@tonyemail.com";
    $freight = "AUD$10";
    $amountTotal = 6000;
    $amountTotalStr = "AUD$60";
    $description = "Payment from ".$customerName;
?>

Then, under the HTML form tag, we pass the variables to the back-end:

<form action="charge.php" method="post">
  <input type="hidden" name="customerEmail" value="<?php echo $customerEmail; ?>">
  <input type="hidden" name="amountTotal" value="<?php echo $amountTotal; ?>">
  <input type="hidden" name="amountTotalStr" value="<?php echo $amountTotalStr; ?>">
  <input type="hidden" name="description" value="<?php echo $description; ?>">

and use the Stripe's javascript checkout button as belows:

<div class="payment-button">
    <script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
          data-key="<?php echo $stripe['publishable_key']; ?>"
          data-amount="<?php echo $amountTotal; ?>" 
          data-description="Payment from: <?php echo $customerName; ?>"
          data-currency="aud">
    </script>
  </div>

Line 3 in the code snippet above, your Stripe account's publishable key is passed to the Stripe's checkout function. Line 4 is the payment amount and line 6 defines the currency ("aud" is for Australian dollar and "usd" is for US dollar).

Create the back-end function

Under the web server root directory, create the back-end function file called charge.php for charging the payment. In the PHP section of this file, we can do as follows:

<?php
  // include configuration file
  require_once('config.php');

  // include Stripe PHP library
  require_once('stripe-php/init.php');

  //set Stripe API key
  \Stripe\Stripe::setApiKey($stripe['secret_key']);

  $customerEmail = $_POST['customerEmail'];
  $amountTotal = $_POST['amountTotal'];
  $amountTotalStr = $_POST['amountTotalStr'];
  $description = $_POST['description'];

  $token  = $_POST['stripeToken'];

  $success =  FALSE;
  $result = "";
  $err = "";
  $content = "";
  $headerColor = "row header green";

  if (!empty($token)){
      try {
          // Add customer to stripe
          $customer = \Stripe\Customer::create(array(
              'email' => $customerEmail,
              'source'  => $token
          ));

          // Charge a credit or a debit card
          $charge = \Stripe\Charge::create(array(
              'customer' => $customer->id,
              'description' => $description,
              'amount'   => $amountTotal,
              'currency' => 'aud'));

          // Get charge details
          $response = $charge->jsonSerialize(); 

          $status = $response['status'];

          if ($status == 'succeeded'){
              $success = TRUE;
          } else {
              $err = $response['failure_message'];
          }

      } catch(Stripe_Error $e) {
          $err = $e->getMessage();
      } catch (Exception $e) {
          $err = $e->getMessage();
      }
  } else {
      $err = "Payment form submission fails";
  }

  if ($success == TRUE) {
      $result = "Payment sucessful";
      $content = "Your payment (".$amountTotalStr.") has been received, thank you!";
  } else {
      $result = "Payment error";
      $content = $err;
      $headerColor = "row header";
  }
?>

Line 6 initializes the Stripe's PHP library, Line 9 set your Stripe account's secret key and line 16 get the return token data from the Stripe's javascript checkout button function. If the returned $token is empty, it means that there is something wrong when submitting data to the Stripe's javascript checkout button. Otherwise, we handle the payment processes one by one. Line 27 calls the Stripe's PHP API to create a customer and line 33 call the API to charge the amount. From the returned data of the function Charge::create, we can check whether the payment is successful or not. Therefore, line 44 checks the payment status. If the payment is failed, get the error message for printing out on the web page.


Showing the payment result message is simple. We can display the relevant message by using HTML code as belows:

<div class="table">
  <div class="<?php echo $headerColor;?>">
    <div class="cell">
      <?php echo $result;?>
    </div>
  </div>
  <div class="row">
    <div class="cell">
      <?php echo $content;?>
    </div>
  </div>
</div>

Conclusion

The whole folder structure under your web server root directory will look like as below:


The folder structure


When opening a browser to access the web page index.php, we can see a payment form with customer contacts, product items and the amount of payment.


The payment form


After clicking the "Pay with Card" blue button, a pre-built payment user interface is shown. You can enter the email and the credit card information. For testing the credit card payment, we can use the testing card number 4242 4242 4242 4242 with any expiration date and CVC number as what you want.


The credit card payment


After confirming the payment, the back-end function (i.e. charge.php) connects to Stripe for the payment process. Finally, the payment result is returned and displayed as below.


The successful page


The full source code of this example can be downloaded from our GitHub repository example-stripe-payment-form



Search