#native_company# #native_desc#
#native_cta#

Integrate a Stripe Payment Gateway with PHP

By Voja Janjic
on September 15, 2016

Stripe is a payment gateway that is becoming increasingly popular in the Web industry. It offers payment processing services, which can be easily integrated into your Web application using the Stripe API.

Although it is not free (2.9% + 30 cents per transaction), Stripe saves time and reduces cost in many ways: seamless integration and good documentation reduces the amount of time and development hours needed, while it offers complete control over sensitive data which saves hundreds of thousands of dollars that would otherwise be spent on ensuring PCI compliance.

Since we have clarified the why, let’s now see how. But before we start with that, double-check that you have at least PHP 5.3 on your server, that HTTPS is enabled and that you have installed the Stripe API PHP library.

The Checkout Flow

In general, the Stripe checkout flow has the following steps:

   1. Customer loads the secure checkout page and enters the data

   2. Once the customer clicks the “Buy now” button,

       an AJAX request is sent to the Stripe server

   3. Stripe server returns the token

   4. The form containing the obtained token is submitted to your server

   5. Your server uses the token to charge the customer

Let’s see an example of how the entire flow works.

Sample Checkout

Once the Stripe API library has been installed through Composer and autoloaded, there are a few more integration steps remaining. First, let’s create a form where the customer will enter his or her credit card data, as well as other required information.

Custom HTML Form

We will collect the following information: Customer’s name, e-mail address, credit card number, card expiration date and CVC number:

<form action="" method="POST" id="payment-form">
	<span class="payment-errors"></span>

	<fieldset>
		<label>Name:</label>
		<input type="text" name="name" />
	</fieldset>

	<fieldset>
		<label>E-mail Address:</label>
		<input type="text" name="email" />
	</fieldset>

	<fieldset>
		<label>Card Number:</label>
		<input type="text" data-stripe="number" />
	</fieldset>

	<fieldset>
		<label>Expiration date (mm/yy):</label>
		<input type="text" data-stripe="exp-month" />

		<input type="text" data-stripe="exp-year" />
	</fieldset>

	<fieldset>
		<button type="submit">Buy now</button>
	</fieldset>
</form>

The important thing to note is that the sensitive data is being sent directly to the Stripe server over a secure connection. Due to security concerns, it is not supposed to go to your server under any circumstances. To make sure it stays that way, omit the name attributes on input fields.

The next step is obtaining the token from Stripe. Stripe.js library will be used for that. Note that Stripe.js must be loaded directly from their server:

<script type="text/javascript" src="https://js.stripe.com/v2/"></script>

Also, the public key must be set (don’t forget to replace it with your account’s public key):

<script type="text/javascript">
  Stripe.setPublishableKey('pk_test_6pRNASCoBOKtIshFeQd4XMUh');
</script>

The code that sends an AJAX request for the token will be bound to form submit event:

$(function() {
	var $form = $('#payment-form');
  	$form.submit(function(event) {
		// Disable the submit button to prevent repeated clicks
		$form.find('.submit').prop('disabled', true);

		 // Request a token from Stripe
		Stripe.card.createToken($form, stripeResponseHandler);

		// Prevent the form from being submitted:
		return false;
	});
});

While the Stripe.card.createToken function sends the request for the token, the callback function stripeResponseHandler is supposed to handle the response and to submit the form to your server:

function stripeResponseHandler(status, response) {
	// Grab the form:
	var $form = $('#payment-form');

	if (response.error) { // Problem!
		// Show the errors on the form:
		$form.find('.payment-errors').text(response.error.message);
		$form.find('.submit').prop('disabled', false); // Re-enable submission

	} else { // Token was created!

		// Get the token ID:
		var token = response.id;

		// Insert the token ID into the form so it gets submitted to the server:
		$form.append($('<input type="hidden" name="stripeToken">').val(token));

		// Submit the form:
		$form.get(0).submit();
	}
};

At this point, we are almost there. The form has been submitted to your server and now you need to charge the customer. The following code would go to the controller that has received the form:

<?php
require_once('vendor/autoload.php');

$stripe = array(
  "secret_key"      => "sk_test_BQokikJOvBiI2HlWgH4olfQ2",
  "publishable_key" => "pk_test_6pRNASCoBOKtIshFeQd4XMUh"
);

StripeStripe::setApiKey($stripe['secret_key']);

$token  = $_POST['stripeToken'];

$customer = StripeCustomer::create(array(
	'email' => $_POST['email'],
	'source'  => $token
));

$charge = StripeCharge::create(array(
	'customer' => $customer->id,
	'amount'   => 100,
	'currency' => 'usd'
));

// Show success message

And that’s it — the customer’s credit card has been charged!