iOS Integration

Our iOS libraries let you easily accept mobile payments on iPhones and iPads. If you need help, check out our answers to common questions or chat live with our developers in #stripe on freenode.

Stripe has created a number of libraries for iOS integration that help with sending cards to our servers, formatting card numbers and accepting card input. This tutorial covers a custom UIView component we've built, but if you need a lower-level approach, feel free to directly use our iOS bindings.

At a high level, here's what you'll accomplish in this tutorial:

  • Collect credit card information using the iOS bindings
  • Convert those details to a single-use token
  • Send these details to your server and create a charge

You can also find the full source code for this tutorial on GitHub.

This article assumes some knowledge of XCode and iOS development. If you need more help getting started with iOS development, we recommend looking at Apple's guides first.

Step 1: Collecting card information

The first step is to actually collect the payment information with the STPView.

Let's download the Stripe iOS bindings, and add them to your XCode project:

  1. In the menubar, click on 'File' then 'Add files to "Project"...'
  2. Select the 'Stripe' directory in the downloaded repository
  3. Make sure 'Copy items into destination group's folder (if needed)' is checked
  4. Click 'Add'

Stripe iOS relies on Quartz Animation, which means you'll need to import the relevant framework. Navigate to your application's target, scroll down to 'Linked Frameworks and Libraries', and add the QuartzCore.framework.

Next create a class called PaymentViewController inheriting from UIViewController. Open the class's header, and import STPView.h.

#import <UIKit/UIKit.h>
#import "STPView.h"

@interface PaymentViewController : UIViewController <STPViewDelegate>
@property STPView* stripeView;
@end

Notice that we're declaring a stripeView variable of type STPView, and we're adopting the STPViewDelegate protocol.

Next, let's instantiate the STPView and append it as a subview.

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.stripeView = [[STPView alloc] initWithFrame:CGRectMake(15,20,290,55)
                                              andKey:@"pk_test_6pRNASCoBOKtIshFeQd4XMUh"];
    self.stripeView.delegate = self;
    [self.view addSubview:self.stripeView];
}

This will add a UIView to the controller to accept card numbers, dates, CVCs, and zip codes. It'll format the input, and validate it on the fly.

We've placed your test publishable API key as the publishableKey argument. You'll need to swap it out with your live publishable key in production. You can see all your keys in your dashboard.

When all the card data is added and valid the stripeView:withCard:isValid: delegate method will be called. In the callback, for example, we could enable a 'save button' that allows users to submit their valid cards:

- (void)stripeView:(STPView *)view withCard:(PKCard *)card isValid:(BOOL)valid
{
    // Toggle navigation, for example
    // self.saveButton.enabled = valid;
}

Take a look at the full example for a demonstration of how you could enable or disable a button in the navigational controller.

Step 2: Creating a single use token

With our mobile library, we shoulder the burden of PCI compliance by helping you avoid the need to send card data directly to your server. Instead, our libraries send the card data directly to our servers, where we can convert them to tokens. You can charge these tokens later in your server-side code.

Once the STPView is valid, you can call the createToken method, instructing the library to send off the credit card data to Stripe and return a token.

- (IBAction)save:(id)sender
{
    // Call 'createToken' when the save button is tapped
    [self.stripeView createToken:^(STPToken *token, NSError *error) {
        if (error) {
            // Handle error
            // [self handleError:error];
        } else {
            // Send off token to your server
            // [self handleToken:token];
        }
    }];}

In the example above, we're calling createToken when a save button is tapped. The important thing to ensure is the createToken isn't called before the card data is valid (otherwise it won't do anything).

Handling error messages and network pending notifications are up to you. In the full example we use MBProgressHUD to show a spinner whenever the network's pending, and handle network errors by showing a UIAlertView.

- (void)handleError:(NSError *)error
{
    UIAlertView *message = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", @"Error")
                                                      message:[error localizedDescription]
                                                     delegate:nil
                                            cancelButtonTitle:NSLocalizedString(@"OK", @"OK")
                                            otherButtonTitles:nil];
    [message show];
}

Step 3: Sending the token to your server

The block you gave to createToken will be called whenever Stripe returns with a token (or error). You'll need to send the token off to your server so you can, for example, charge the card.

- (void)handleToken:(STPToken *)token
{
  NSLog(@"Received token %@", token.tokenId);

  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://example.com"]];
  request.HTTPMethod = @"POST";
  NSString *body     = [NSString stringWithFormat:@"stripeToken=%@", token.tokenId];
  request.HTTPBody   = [body dataUsingEncoding:NSUTF8StringEncoding];

  [NSURLConnection sendAsynchronousRequest:request
                                     queue:[NSOperationQueue mainQueue]
                         completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                             if (error) {
                                 // Handle error
                             }
                         }];
}

You then just need to set up a endpoint on your server that can receive a HTTP POST call containing a parameter called stripeToken. Make sure any communication with your server is SSL secured to prevent eavesdropping.

Now we have a Stripe token representing a card on our server we can go ahead and charge it, save it for charging later, or sign the user up for a subscription. For more information, take a look at our tutorial on creating charges.

Take a look at the full example application to see everything put together.