Wern Ancheta

Adventures in Web Development.

Getting Started With Stripe API

| Comments

In this tutorial I’ll walk you through the Stripe’s API. Let’s start by defining what Stripe is. From the Stripe website itself:

Stripe is a developer-friendly way to accept payments online and in mobile apps.
We process billions of dollars a year for thousands of companies of all sizes.

Now we know that Stripe is a payment processor, similar to Paypal.

With Stripe, you can accept payments in three ways:

  • Embedded Form
  • Custom Form
  • Mobile App Integration

In this tutorial I’ll only be walking you through the first two: embedded form and custom form.

Embedded Form

If you do not want to bother with creating your own checkout forms, an embedded form is the way to go. An embedded form is basically Stripe’s checkout widget. All you have to do is include their script on your website, specifically inside a form element. And the front-end side is already handled for you.

1
2
3
4
5
6
7
8
9
10
<form action="/checkout.php" method="POST">
  <script
    src="https://checkout.stripe.com/checkout.js" class="stripe-button"
    data-key="pk_test_xxxxxxxxxxxxxxxxxxx"
    data-amount="1000"
    data-name="Web Development"
    data-description="Develop a website"
    data-image="http://mywebsite.com/img/logo.png">
  </script>
</form>

Breaking it down. For the script to work, you need to supply a value to the following attributes:

  • src – Stripe’s checkout script. This should be https://checkout.stripe.com/checkout.js
  • data-key – your stripe publishable key. You can find it by clicking on your username, then select ‘account settings’, then click on the ‘api keys’ tab. From there you can use either your test publishable key or your live publishable key. The test key is used for testing. This allows you to supply a fake credit card number and pay for a fake product or service. After successful payment, you can see your fake client from the customers page on your Stripe dashboard. Don’t forget to switch to test.
  • data-amount – the amount you want to charge in cents. Just multiply what you want to charge by 100. So for example you want to charge $10, you need to supply 1000 instead.
  • data-name – the name of your product or service.
  • data-description – the description of your product or service.
  • data-image – your logo. This should be an absolute url.

Next we need to install Stripe’s library via composer. Add the following code on your composer.json file:

1
2
3
4
5
{
  "require": {
    "stripe/stripe-php": "2.*"
  }
}

Once that’s done, execute composer install from your terminal. This will fetch the library from the repository.

Next create the checkout.php file and add the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
require 'vendor/autoload.php';

\Stripe\Stripe::setApiKey('sk_test_xxxxxxxxxxxxxx');

$token = $_POST['stripeToken'];
$email = $_POST['stripeEmail'];


try {
    $charge = \Stripe\Charge::create(array(
      "amount" => 1000,
      "currency" => "usd",
      "source" => $token,
      "description" => $email)
    );

    print_r($charge);
}catch(\Stripe\Error\Card $e){
    echo $e->getMessage();
}
?>

Breaking it down, first we included the vendor/autoload.php file so that we can use the Stripe library on our script. Next we initialize the library by setting the Stripe secret key. Next we get the data supplied by Stripe for us from the front-end. The stripeToken is the unique token generated by Stripe, this represents the transaction that the client made on the front-end. That is, paying $10 for our service. Next is the stripeEmail, this is basically just the email supplied by the client. Next we wrap the stripe charge call in a try catch statement. This allows us to capture any error returned by the API and show it to the client. Calling the stripe charge method requires 4 arguments:

  • amount – the amount that you want to charge in cents.
  • currency – the currency code representing the currency that we want to use.
  • source – the token that stripe generated on the front-end.
  • description – a text that we want to assign to the charge. This is usually the clients email. But you can add more details such as the name of the service if you’re offering more than one product or service.

If the API call is successful, this method returns a whole bunch of data. Such as the amount paid, and the description. In most cases you’ll basically only want the id of the transaction. You can get this by accessing the id property:

1
$charge_id = $charge->id;

You can then save this on your database as a reference. But of course you can always see this on your payments page.

Custom Forms

If you need to ask additional information from your clients. Or you just want to use your own form. You can use custom forms. This allows you to write your own markup, supply your own fields and style them the way you want it with css. Here’s an example of how a custom checkout form might look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<form action="checkout.php" method="POST" id="payment-form">
  <div class="errors"></div>

  <div>
    <label for="email">Email</label>
    <input type="email" id="email" name="email">
  </div>

  <div>
    <label for="name">Name</label>
    <input type="text" id="name" name="name">
  </div>

  <div>
    <label for="card-number">Card Number</label>
    <input type="text" size="20" data-stripe="number" id="card-number" name="card-number">
  </div>

  <div>
    <label for="cvc">Security Code</label>
    <input type="text" size="4" data-stripe="cvc" id="cvc" name="cvc">
  </div>

  <div>
    <label>Expiration (MM/YYYY)</label>
    <input type="text" data-stripe="exp-month" name="exp-month">
    <span> / </span>
    <input type="text" data-stripe="exp-year" name="exp-year"/>
  </div>

  <button type="submit">Pay</button>
</form>

This form works with the Stripe checkout script by adding the data-stripe attribute to the following fields. Just supply the value on the right-hand side as the value for the data-stripe attribute depending on the field:

  • card number – card-number
  • security code or cvc – cvc
  • card expiration month – exp-month
  • card expiration year – exp-year

Next we need to include the stripe checkout script:

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

And then set the publishable key. This allows stripe to identify which stripe account the request came from:

1
2
3
<script>
Stripe.setPublishableKey('pk_test_xxxxxxxxxxxxxxxxxxx');
</script>

Next we need to define the method that will process the response that we get from Stripe when the client submits the payment form. This takes up 2 parameters: status and response. The status is the status code. The response contains the actual Stripe response. This is an object containing information about the transaction. One of those is the id which is basically the token that we need to pass in to the back-end. All we have to do is to append it to the payment form so it gets submitted with the rest of the fields. If there is an error with the request, an error property becomes available in the response object. This contains the error message, we just show it to the user by supplying it as a value to the errors div. After that, we enable the submit button so the client can fix the errors and submit the form again:

1
2
3
4
5
6
7
8
9
10
11
12
function processStripeResponse(status, response){
  var form = $('#payment-form');

  if(response.error){
    form.find('.errors').text(response.error.message);
    form.find('button').prop('disabled', false);
  }else{
    var token = response.id;
    form.append($('<input type="hidden" name="stripeToken" />').val(token));
    form.get(0).submit();
  }
};

Next we define the event handler for when the payment form is submitted. This calls the createToken method which requires the payment form and the response handler as its arguments. Don’t forget to return false so the form doesn’t get submitted. The response handler will be the one which will trigger the submit if the response doesn’t have any errors:

1
2
3
4
5
6
7
8
9
10
$(function(){
  $('#payment-form').submit(function(event) {
    var form = $(this);
    form.find('button').prop('disabled', true);

    Stripe.card.createToken(form, processStripeResponse);

    return false;
  });
});

On the back-end we can just use the previous code and use the custom fields that we added. Note that the stripeToken field stays the same. We don’t need to pass the card number, security code and expiration date:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
require 'vendor/autoload.php';

\Stripe\Stripe::setApiKey('sk_test_xxxxxxxxxxxxxx');

$token = $_POST['stripeToken'];

$email = $_POST['email'];
$name = $_POST['name'];

try {
    $charge = \Stripe\Charge::create(array(
      "amount" => 1000,
      "currency" => "usd",
      "source" => $token,
      "description" => $email)
    );

    print_r($charge);
}catch(\Stripe\Error\Card $e){
    echo $e->getMessage();
}
?>

Conclusion

That’s it! You’ve learned how to interact with the Stripe API in order to easily process payments.

Resources

Comments