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 3 of this article. Click here to view the first page.

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.

  • 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.
  1. 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.
  2. 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.
  3. Create /charge route. It will listen for requests from the iOS app and send charge requests to Stripe.
  4. Parse the JSON sent by your iOS application.
  5. Create and invoke Stripe::Charge with various POST parameters.
  6. 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.
  7. 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.

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.

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!

Where To Go From Here?

You've successfully implemented Stripe checkout in iOS from start to finish and your app can now accept credit cards. Whenever you want to start charging your customers, verify your Stripe account and switch all the test API keys to the live API keys.

Here are the finished iOS project and finished server script.

There are lots of cool things you can do with Stripe's API that this tutorial didn’t cover. For example, if you know you are going to be charging the same person in the future, you may want to create a customer object. If you need to collect shipping details, you can do that as well. Stripe also lets you create subscription plans and invoices if that suits your business model. Furthermore, in live mode, Stripe lets you to send email to charged customers for payment recaps.

I encourage you to peruse Stripe's docs if you're interested in implementing any of the features I mentioned above. If you have any tips or suggestions for using Stripe with iOS, or if you’ve implemented a checkout cart in the past, please share in the comments section.

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.