News

Build a PHP and Stripe eCommerce solution

Discover how to sell digital goods simply and securely with new Stripe platform

stripe

Processing credit cards is unfortunately far more difficult than we might hope as developers. Given that it’s such a common task, is it really necessary that we jump through countless hoops (surrounded by fire, of course) for the sole purpose of processing a payment? Merchants? Gateways? SSL? Security? Very quickly, a seemingly simple operation can become an overwhelmingly confusing and, more importantly, dangerous task. Any time you find yourself handling a user’s sensitive data, you better be on your toes.

Wouldn’t be it amazing if there was a service that could make this process as easy as it could possibly be? A service built by developers for developers – what a thought! Enter Stripe; where there are no merchant accounts and no gateways. An API call, along with a few safety guidelines, is all that you need to begin accepting credit card payments today.
While Stripe isn’t free, they only ask for 2.9% of each charge (plus 30 cents). That’s it. No set-up fees, storage fees, hidden costs – none of that. Just 2.9%. Compared to many alternatives, that’s really not bad at all.

5 KEY STRIPE FEATURES

1 Simple
Processing credit cards manually can be very difficult and dangerous. With Stripe, doing so is a cinch. You can even process charges from the command line.

2 Cheap
Various payment merchants are notorious for their hidden fees. Stripe tells you upfront exactly what you can expect to pay: 2.9% per charge + 30 cents. No set-up fees,  no hidden fees and no card storage fees.

3 An intuitive API
Stripe’s API is easy to use, clean and restful, much like the idea itself. There’s nothing here that will give you problems.

4 Used by cool kids
If adoption is a concern, it needn’t be. Countless services leverage Stripe, including Reddit, Grooveshark and Shopify.

5 Built by developers
Very clearly, Stripe was built to scratch a developer’s itch. The team is full of developers and entrepreneurs, just like you.

Let’s Do This

Let’s process the first test payment. Of course, before beginning, visit www.stripe.com, create a new account for free and fill out the various forms, such as the statement descriptor and your banking information.

Stripe’s attention to elegance extends to its design department

Charging a user requires two core steps:

1. Fetch the user’s credit card information and send an AJAX request to Stripe’s server, which will return a unique token that represents this secure data.

2. Using your server-side language of choice (PHP for this article), create a new Stripe charge, passing through the unique token.

Build a payment form

Naturally, the first step is to build a payment form for your product. You can use Stripe’s checkout script which will automatically create the form, validate the user’s input and generate the unique token for the user’s credit card data. In situations when configuration and styling are flexible, this is an excellent route to take. Insert a script tag, along with a handful of custom HTML5 attributes, and you’re done.

001 <form action=”” method=”POST”>
 002     <script
 003        src=”https://checkout.stripe.com/    v2/    checkout.js” class=”stripe-button”
 004        data-key=”pk_test_            G5YhIkq2PEq84lwU064TZENT”
 005        data-amount=”2000”
 006        data-name=”Demo Site”
 007        data-description=”2 widgets     ($20.00)”
 008        data-image=”/128x128.png”>
 009      </script>
 010    </form>                    
 011

However, in most situations, you’ll require full control. As such, for the purposes of this article, we’ll use a custom form. In this section, we’ll accomplish three things:

1. Use a form to collect user’s credit card information
2. Convert that data to a unique single-use token
3. Submit the form to the server, along with the token

A basic payment form might look like this:

001 <form action=”” method=”POST” id=”payment-        form”>
 002      <span class=”payment-errors”></span>
 003      <div class=”row”>
 004        <label>
 005          <span>Card Number</span>
 006          <input type=”text” data-            stripe=”number”>
 007        </label>
 008      </div>
 009      <div class=”row”>
 010        <label>
 011          <span>CVC</span>
 012          <input type=”text” data-            stripe=”cvc”>
 013        </label>
 014      </div>
 015      <div class=”row”>
 016        <label>
 017          <span>Expiration (MM/YYYY)</span>
 018          <input type=”text” data-        stripe=”exp-    month”>
 019        </label>
 020        <input type=”text” data-        stripe=”exp-    year”>
 021      </div>
 022      <button type=”submit”>Buy Now</button>
 023    </form>



Notice how we don’t require much information to process a credit card. Technically, the only information that Stripe demands is a credit card number and expiration date. However, as a rule of thumb, the more information that you fetch from the user, the better. Should the charge be disputed, this extra information will come in handy. In other words, the more information you request, the more likely it is that the true owner of the credit card is placing the transaction. The key is to find the line between enough and so much that the user doesn’t bother filling out the form. At minimum, request the user’s name, email address, credit card number, expiration date and CVC number.

To remind you, never allow sensitive credit card data to touch your server. Doing so has the potential to create a world of hurt if performed incorrectly. Instead, take the easy road: ensure that the inputs for the user’s credit card data do not contain name attributes. By omitting this, the data can’t be posted to your server.

Pay attention to the custom attributes on the inputs, such as ‘data-stripe=”number”’. Stripe offers a plug-in, `stripe.js`, which assists in compiling the user’s provided data and generating the token. Stripe will search for those attributes and fetch their respective values.

To make use of `stripe.js`, reference the script within your project, and set your publishable key, which will be provided when you sign up with Stripe. We’ll also be using jQuery, though it’s certainly not required.

001 <script src=”//code.jquery.com/jquery-    2.0.2.min.js”></script>
 002    <script src=”//js.stripe.com/v2/”></    script>        <script>
 003        (function() {
 004            Stripe.setPublishableKey(‘YOUR     PUBLISHABLE KEY’);
 005        })();
 006    </script>

Think of `setPublishableKey` as a way of identifying your website when communicating with Stripe. Upon signing up, you’ll be presented with two different versions of this key, for testing and production.

Next, we need to create the unique, single-use token for the user’s credit card data. We can use the `Stripe` object, provided by the script that we imported, for this purpose. Even better, we needn’t worry about serialising the payment form’s data; simply pass through the form jQuery object and Stripe will handle the rest.

001    // Event Listeners
 002    $(‘#payment-form’).on(‘submit’,         generateToken);
001    var generateToken = function(e) {
 002        var form = $(this);
001        // No pressing the buy now button     more     than once
 002        form.find(‘button’).        prop(‘disabled’,     true);
001        // Create the token, based on the     form     object
 002        Stripe.create(form,             stripeResponseHandler);
001        // Prevent the form from submitting
 002        e.preventDefault();
 003    };
001    var stripeResponseHandler =         function(status, response) {};

With this bit of JavaScript, when the payment form is submitted, Stripe will attempt to generate a single-use token, using the related data from the inputs that include `stripe-` specific custom attributes. The second argument to the create method is a callback that will receive the token `response.id` from Stripe’s server, and then proceed accordingly.

Within this callback, it’s important to verify the result (was all of the credit card information provided correctly?). Insert the token into a hidden input and submit the form to your server. Again, note that the credit card information should not and will not hit your server if this has all been done correctly – only the token and non-sensitive data will reach you. This is extremely important, so write acceptance or functional tests to verify it all.

Your callback might look like so:

001 var stripeResponseHandler =         function(status,     response) {
 002        var form = $(‘#payment-form’);
001        // Any validation errors?
 002        if (response.error) {
 003            // Show the user what they did     wrong
 004            form.find(‘.payment-errors’).    text(response.error.message);
001            // Make the submit clickable     again
 002            form.find(‘button’).        prop(‘disabled’, false);
 003        } else {
 004            // Otherwise, we’re good to go.     Submit the form.
001            // Insert the unique token into the     form
 002            $(‘<input>’, {
 003                ‘type’: ‘hidden’,
 004                ‘name’: ‘stripeToken’,
 005                ‘value’: response.id
 006            }).appendTo(form);
001            // Call the native submit method on     the form
 002            // to keep the submission from     being cancelled
 003            form.get(0).submit();
 004        }
 005    };
 006

It’s really quite simple! Submit an AJAX request to Stripe’s API (using their helpful JavaScript plug-in), fetch the generated token, insert it into the form, and post it to your server. It’s as easy as that.

Charging

If following along, you’ve now generated a single-use token and submitted the payment form. Now, it’s time for your server-side language to physically create the charge. Remember, no charge has been made. We only generated a token that represented the credit card data.

Stripe offers a number of server-side libraries for registering new charges, or even arranging subscriptions. Chances are high that your preferred language is represented (PHP, Ruby, Python, etc.).

Similarly to the previous section, submitting a new charge may be accomplished in a few steps:

1. Declare your API key
2. Using the Stripe library, make an API call, passing through the details of the transaction
3. Validate the charge, and proceed accordingly.

Refer to Stripe’s library page (stripe.com/docs/libraries) for installation instructions. If using PHP, as we will be in this article, it’s recommended that you leverage Composer (getcomposer.org) to download the Stripe package.

001    {
 002        “require”: {
 003           “stripe/stripe-php”: “dev-master”
 004        }
 005    }

Composer is the future of PHP dependency management, so get on board now, if you haven’t already. A basic Stripe charge might take the form of:

001 // Set your API key
 002    Stripe::setApiKey(“YOUR API KEY”);
001    try {
 002        Stripe_Charge::create([
 003‘amount’ => 2000, // this is in cents: $20
 004            ‘currency’ => ‘usd’,
 005  ‘card’ => $_POST[‘stripeToken’],
 006  ‘description’ => ‘Describe your     product’
 007        ]);
 008    } catch (Stripe_CardError $e) {
 009 // Declined. Don’t process their     purchase.
 010        // Go back, and tell the user to try a     new card
 011    }

That’s it – the API key will authenticate you as a valid Stripe user. Similar to the publishable key, Stripe will provide you with two different versions of this key: one for testing and production, respectively.

NOTE: Please note that all charges to Stripe should be declared in cents (based on the currency, of course). If prices are stored in your database as dollars, euros or pounds, then you’ll want to compensate accordingly, when making the charge.

If no exception is thrown, you may rest assured that the charge has successfully processed. Proceed by offering the user their digital download, or registering their purchase with your system.

Believe it or not, Stripe’s work is finished. There’s certainly more that you can do, such as creating customers and managing subscriptions, but when it comes to simply processing a single payment, you’re done! …Except you’re not.

SSL

While, yes, Stripe’s work is finished, yours is most certainly not. Regardless of the payment provider, any time that you work with credit card information, security should be one of your top concerns. We’ve already taken the important first steps, by ensuring that the credit card data never touches the server, but there’s still more to do. We next must secure the user’s connection to your server. In other words, you will need an SSL certificate. Under no circumstances should you skip this step – it’s an important part of making users feel secure when making payments online.

When a user offers a website their credit card information, they will expect to see `https` within the address bar. Luckily, purchasing an SSL certificate is far easier than it used to be. In fact, most hosts offer an SSL add-on, which turns the entire process into a single click. The same is true for various SaaS options, such as Pagoda Box or Heroku.

Once you enable SSL, it’s possible that images and assets will break. To fix this, ensure that all URLs use `https`, rather than `http`. Or, as a better solution, use protocol-relative URLs.

001 <!-- Not good for SSL -->
 001    <img src=”http://domain.com/images/foo.    jpg” alt=”Foo Bar”>
001    <!-- Better -->
 002    <img src=”//domain.com/images/foo.jpg”     alt=”Foo Bar”>

With this techique, popularised by Paul Irish, if the current page is using HTTPS, then the asset will also be requested with HTTPS.

Assuming that your host offers a one-click SSL add-on, simply point your user to the `https://` version of the order page, and you’re all set to go!

Conclusion

The wonderful thing about Stripe is that it translates a complicated, confusing and dangerous operation into a single, simple API call. There are no merchant accounts, no gateways and happily, no hidden fees. There’s a reason why people say that Stripe is laughably easy to use – it genuinely is.

×