# So You Want to Accept Credit Cards Online?

Difficulty:BeginnerLength:LongLanguages:

Until recently, accepting credit cards on a website was expensive and complicated. But that was before Stripe: a radically different and insanely awesome credit card processing company. Today, I'll show you how to start accepting cards in 30 minutes or less - without spending a dime.

Republished Tutorial

Every few weeks, we revisit some of our reader's favorite posts from throughout the history of the site. This tutorial was first published in June, 2012.

## Step 2: Create Your Payment Form

The next thing we need is a form that our customers fill out to place a credit card order with us. Today, we'll use this vastly over-simplified PHP page, called "buy.php":

There are three things to note about the code snippet above.

1. First, we've set the form's action to "javascript:" rather than providing a path to a server-side script. (You'll see why in just a minute.)
2. Secondly, there's a short snippet of PHP that automatically populates our expiration-year field with the next 20 years so that we don't have to update that manually in the future.
3. Thirdly, none of the form fields have a "name" parameter set. This is crucial because it will prevent the value of the field (such as the credit card number) from being sent to our server when the form is submitted. We'll talk about why this is important in just a minute.

### How Much Info Should I Collect?

The only things you absolutely must have to charge a credit card are the card number and the expiration date. But you should always collect at least some additional information. Here's why: if a customer disputes the charge on their card, you'll be required to prove that they did, in fact, place an order with you.

The more information you collect, the easier it will be to prove that the customer (as opposed to an identity thief) placed the order on your site.

## Step 5: Create a Server-Side Script

The only thing left to do is create the server-side PHP script that actually triggers the charge on our customer's card. First, we'll need Stripe's PHP library. To download it, go to Stripe's website, click the "Documentation" link in the upper right, and then choose the "API Libraries" section. (Or you can go straight there by clicking here.) Scroll down the page until you see the PHP section, which looks like this:

Download the latest version and unzip it. You'll see two items: "Stripe.php" and a folder named "Stripe" that contains a bunch of other PHP files. Drop both these items into your website's folder.

Now, create a new file called "pay.php". We'll start coding this file with some basic stuff:

At the top, we have a simple function that we'll call whenever our script hits an error. It returns a JSON object with two items: "result" and "errorMessage". This JSON object is sent back to "buy-controller.js" (where we used jQuery's AJAX function to call this server-side script). There, we can inspect the value of "result" to see what happened. If it's 0, the payment script completed successfully. If it's 1, the script hit an error and we can use the "errorMessage" item to report what happened to the user.

Next, we bring in Stripe's PHP library that we downloaded earlier. There's nothing too complicated here; just make sure you update the path in the require statement to the relative location of the Stripe PHP library. After that, we have both of our SECRET API keys. We call the "setApiKey" function (which is part of Stripe's PHP library) and pass it our trial key. Combined with the "publishable" key that we set earlier, Stripe now has all the information it needs to verify our identity and associate this transaction with our account. Of course, when we take the website live, we would switch this statement to use $liveAPIKey! Warning: Don't forget to switch to the LIVE API keys when you publish your site! You must switch both the "publishable" key in the HEAD element of "buy.php" and the "secret" key, which appears in "pay.php", above. And finally, we grab all the data that we passed from the AJAX call in "buy-controller.js". Note that Stripe requires us to specify the charge amount in cents. Here, we passed the value in dollars, so we multiply by 100 to convert it to cents. ### Actually Charge The Card Here's the rest of the code for pay.php: Surprisingly simple, no? First, we verify that none of our variables are null. Although we don't need all of them to charge the card, we might want to record this information in a database or use it to email the customer a receipt, so we don't want to proceed if it's not available. Then, we use the "Stripe_Charge::create()" method, which is part of the Stripe PHP library. This is the line that actually charges the user's card (or attempts to, anyway). The first two items in the array are self-explanatory. The third, "card", is where we pass the token that we requested from Stripe earlier. The fourth item, "description" is vitally important. Whatever we pass here is what WE will see when we log into Stripe and view our transactions. You should choose something short that identifies the customer who placed this order. An email address is your best bet, as many customers might have the same name. ### Why Might The Charge Fail At This Point? If we were able to successfully get a token from Stripe, why would the charge fail at this point? The answer is that the validation Stripe performed earlier checked only that the credit card data was well-formed; it did not run a transaction through the credit card networks. It may be the case that the customer's card is over its limit. Or, if it's a debit card, there may not be enough money in the customer's account to cover this purchase. It could also be that the credit card company simply flags the transaction as unusual and requires the customer's approval to let it through (this has happened to me with American Express cardholders). In situations like these, the card will validate correctly when we request a token, but fail when we attempt to actually charge it. Fortunately, Stripe makes it really easy to handle these failures. We simply use try/catch blocks, as you see above. ### Charge The Card Last! If that customer is me, you're in for a cactus beating. If your website needs to do things, such as generating a serial number for a software license, you should do that BEFORE you charge the customer's card. If you charge the card first and then your site fails to generate a serial for any reason, your customer is going to be ticked off. (If that customer is me, you're in for a cactus beating.) They might even call their credit card company to cancel the charge, which results in a$15 fee to you and the loss of a sale. So play it safe: be sure you have everything ready to go BEFORE you charge the customer!

That's it! That's all the code you need to charge a credit card on your website. The rest of the article covers some additional details about using Stripe that you might find handy:

## Testing & Debugging

When we're using the "test" API keys, we can use special credit card numbers that force Stripe to return a certain type of response so that we can thoroughly test our code. Here's the special numbers:

• 4242-4242-4242-4242: Simulate a successful card transaction
• 4000-0000-0000-0002: Force a "card declined" response
• 4242-4242-4242-4241: Force an "invalid card number" response

In test mode, any 3 or 4-digit CVC number is considered valid. Any expiration date that is in the future is valid. You can pass a two-digit CVC number to test that error case. Likewise, you can pass any date in the past to test the invalid expiration date response. And finally, if you'd like to test the "invalid amount" response, simply pass any non-integer (such as 1.35) as the amount to charge.

For exhaustive information on testing Stripe, you can visit their documentation page.

## Subscriptions, Storing Card Info & More

Stripe allows you to do more than one-time charges to a customer's card. You can set up a subscription that will charge the card a specified amount at an interval of your choosing. The APIs you need to do this are part of Stripe's PHP library and the website contains excellent documentation that will walk you through the process.

What if you want to store credit card information so that customers don't have to enter it every time they visit your site? Stripe lets you do that too! You simply create a "customer" object in much the same way that we created a token. This object contains all the sensitive data that pertains to a particular customer. Stripe will securely store this information on their end (which means you don't have to risk a cactus beating) and you can bill the user whenever you like simply by requesting the appropriate "customer" object, just like we did with the token. Again, all the APIs are part of Stripe's PHP library and the website will walk you through it.

## See it in Action

So that's it: Stripe in a nutshell! If you'd like to see a working example of what we've just covered with a bit more complexity and design, swing by this page and inspect the source. (Hint: it will look familiar.) Otherwise, if you've got questions leave a comment below, check out the Stripe Support Page or find me on Twitter: @bdkjones. Thanks and good luck!