Accepting Credit Cards In Your iOS App Using Stripe

In this tutorial, you will to learn how to accept credit cards in iOS using Stripe, a pain-free, developer-centric way to handle purchases in your apps. By Lorenzo Boaro.

Leave a rating/review
Save for later
Share
You are currently viewing page 3 of 4 of this article. Click here to view the first page.

Setting Up Your Ruby Back End

Setting up a back-end development environment is beyond the scope of this tutorial, so you'll keep it as simple as possible. The back end is going to be a Sinatra web application that expects you to send the token id returned by STPAddCardViewController, along with a few other parameters.

Note: Sinatra is a free, open source DSL for creating web applications in Ruby with minimal effort. It is an alternative to other Ruby web application frameworks such as Ruby on Rails.

Sinatra requires a Ruby environment greater or equal to 1.9.3. In order to check the version currently installed in your machine, open Terminal and paste the following command:

ruby --version

You should get something like:

ruby 2.4.0p0 (2016-12-24 revision 57164) [x86_64-darwin16]

If you have an older version, you need to update it to the latest. The best way to install a new Ruby version is through RVM, a command line utility tool which allows you to easily install, manage, and work with multiple Ruby environments from interpreters to sets of gems.

In Terminal, paste the following command:

curl -sSL https://get.rvm.io | bash -s stable --ruby

Note: Together with the installation of RVM, --ruby flag will install the newest version of Ruby.

Note: Together with the installation of RVM, --ruby flag will install the newest version of Ruby.

Run ruby --version again. Now you should have all set up correctly.

At this point, you can install the Stripe, Sinatra and JSON gems.

Note: A gem is a pretty simple concept. You can think of a gem as a library or plugin. You can learn about them in What is a gem?.

Note: A gem is a pretty simple concept. You can think of a gem as a library or plugin. You can learn about them in What is a gem?.

Switch again to the Terminal and copy the following line:

gem install stripe sinatra json

Here you are instructing Ruby to install three gems into the current Ruby version. If you update your Ruby version, you'll need to repeat this process.

That's it! Now you are able to create your back end.

The Ruby Script

Open your favorite text editor (like Atom or TextEdit) and create a new file.

Paste the following code and save it as web.rb:

#1
require 'sinatra'
require 'stripe'
require 'json'

#2
Stripe.api_key = 'YOUR_TEST_SECRET_KEY'

#3
get '/' do
  status 200
  return "RWPuppies back end has been set up correctly"
end

#4
post '/charge' do
  #5
  payload = params
  if request.content_type.include? 'application/json' and params.empty?
    payload = indifferent_params(JSON.parse(request.body.read))
  end

  begin
    #6
    charge = Stripe::Charge.create(
      :amount => payload[:amount],
      :currency => payload[:currency],
      :source => payload[:token],
      :description => payload[:description]
    )
    #7
    rescue Stripe::StripeError => e
    status 402
    return "Error creating charge: #{e.message}"
  end
  #8
  status 200
  return "Charge successfully created"

end

Following the numbered comments, here’s what this code does:

First, you import several modules the script is going to need.

Your app's request is going to arrive in JSON format, so you need to import the json module to be able to convert the incoming request into a proper dictionary.

  1. First, you import several modules the script is going to need.

    Your app's request is going to arrive in JSON format, so you need to import the json module to be able to convert the incoming request into a proper dictionary.

  2. Here, you need to replace YOUR_TEST_SECRET_KEY with your Test Secret Key that Stripe provided earlier. This is the secret part of the secret/publishable pair of keys necessary to complete a transaction. If there is a mismatch between the secret and publishable keys, the charge will fail.
  3. Create the base / route that will print RWPuppies back end has been set up correctly if the back end has been set up correctly. You'll use this to test your server.
  4. Create /charge route. It will listen for requests from the iOS app and send charge requests to Stripe.
  5. Parse the JSON sent by your iOS application.
  6. Create and invoke Stripe::Charge with various POST parameters.
    • amount: The amount in cents that you’ll charge your customer. You don't need to make any conversion here since your iOS app deals already with cents.
    • currency: A short string that identifies the currency used for the transaction. Its value has been set to usd within your iOS app.
    • source: The one-time token that you get back from STPAddCardViewControllerDelegate.
    • description: A descriptive message that you can easily recognize when you log into the Stripe dashboard. This is a good place for an internal transaction ID.
  7. Keep in mind that errors can occur here as well. For example, you might try to charge a token that you already used. Whatever the outcome, you have to notify your app of what happened. You do this by returning the response that you receive from Stripe.
  8. If everything goes as planned, your Stripe account should have more $$. :]

Save the file and try to run the script you've just created.

Go back to Terminal and paste the following command:

ruby web.rb

You should see something like this:

== Sinatra (v2.0.0) has taken the stage on 4567 for development with backup from Thin

Note: If you don't execute the command in the same directory the ruby file is located in, you will get an error. To fix it, just use the absolute path for that file.

Note: If you don't execute the command in the same directory the ruby file is located in, you will get an error. To fix it, just use the absolute path for that file.

The back end is launched and listening for requests in the port 4567. Open your favorite web browser and type http://localhost:4567 in your address bar. You should see something like this:

Backend Running

Back To Your App

With your back end in place, it’s time to test your application.

Only one little thing is missing. You need to configure the back end URL in the application. As you've just seen, your back end runs locally as a Sinatra web application.

Open Constants.swift file and find the static variable called baseURLString. Replace the placeholder string with http://localhost:4567. Your code should look like the following:

enum Constants {
  static let publishableKey = "pk_test_FGACeszCTD2vvtx3rm5xr8rB"
  static let baseURLString = "http://localhost:4567"
  static let defaultCurrency = "usd"
  static let defaultDescription = "Purchase from RWPuppies iOS"
}

defaultCurrency and defaultDescription are set respectively to usd and Purchase from RWPuppies iOS. Obviously in a real world app those values should not be hardcoded but based on customers' information.

Now, build and run. Go through the entire checkout process. Add one or more favorites puppies to your cart and open the Checkout tab. At this point you should be able to see the list of the puppies you are going to buy and the total amount.

Click Continue. Insert the following card details into the credit card view:

  • Credit Card Number: 4242424242424242
  • Expiration Date: Any month and year in the future
  • CVC Number: Any three or four-digit number

Note: Since you can't use genuine card information while testing your app, Stripe makes available some test credit cards numbers and tokens. For further info take a look at Testing.

Note: Since you can't use genuine card information while testing your app, Stripe makes available some test credit cards numbers and tokens. For further info take a look at Testing.

Tap the Done button in the top right corner. If the payment succeeded, you will get something like the following:

Stripe Payment

More importantly, verify that the charge went through Stripe. Open your Stripe dashboard and go straight to Payments on the left menu. You will find an entry similar to the one below.

Stripe Dashboard

Congratulations!

Well Done!

Lorenzo Boaro

Contributors

Lorenzo Boaro

Author

Ernesto García

Tech Editor

Mike Oliver

Final Pass Editor

Richard Critz

Team Lead

Over 300 content creators. Join our team.