iOS Integration

Accept payments in iPhone and iPad apps, with built-in support for Apple Pay. If you need help after reading this, check out our answers to common questions or chat live with other developers in #stripe on freenode.

The Stripe iOS SDK makes it easy to build an excellent payment experience in your iOS app. It provides powerful, customizable, UI elements to use out-of-the-box to collect your users' payment details.

We also expose the low-level APIs that power those elements to make it easy to build fully custom forms. This guide will take you all the way from integrating our SDK to accepting payments from your users via both credit cards and Apple Pay.

Install and configure the SDK

You can choose to install the Stripe iOS SDK via your favorite method. We support CocoaPods, Cathage, both static and dynamic frameworks, as well as Fabric.

  1. If you haven't already, install the latest version of CocoaPods.
  2. Add this line to your Podfile:
    pod Stripe
  3. Run the following command:
    pod install
  4. Don't forget to use the .xcworkspace file to open your project in Xcode, instead of the .xcodeproj file, from here on out.
  5. In the future, to update to the latest version of the SDK, just run:
    pod update Stripe
  1. If you haven't already, install the latest version of Carthage.
  2. Add this line to your Cartfile:
    github "stripe/stripe-ios"
  3. Follow the Carthage installation instructions.
  4. In the future, to update to the latest version of the SDK, run the following command:
    carthage update stripe-ios --platform ios

The Stripe SDK is available from Twitter's Fabric platform. You can head over to Fabric.io to install their Mac app and follow their instructions from there.

Note: This is only compatible with iOS 8 and above.

  1. Head to our GitHub releases page and download and unzip Stripe.framework.zip.
  2. Drag Stripe.framework to the "Embedded Binaries" section of your Xcode project's "General" settings. Make sure to select "Copy items if needed".
  3. Head to the "Build Phases" section of your Xcode project settings, and create a new "Run Script Build Phase". Paste the following snippet into the text field:
    bash "${BUILT_PRODUCTS_DIR}/${FRAMEWORKS_FOLDER_PATH}/Stripe.framework/integrate-dynamic-framework.sh"
  4. In the future, to update to the latest version of our SDK, just repeat steps 1 and 2.

Note: We only recommend this approach if you need to support iOS 7 in your application.

  1. Head to our GitHub releases page and download and unzip StripeiOS-Static.zip.
  2. In Xcode, with your project open, click on "File" then "Add files to Project...".
  3. Select Stripe.framework in the directory you just unzipped.
  4. Make sure "Copy items if needed" is checked.
  5. Click "Add".
  6. In Xcode, click on "File", then "Add files to Project...".
  7. Select Stripe.bundle, located within Stripe.framework.
  8. Make sure "Copy items if needed" is checked.
  9. Click "Add".
  10. In the future, to update to the latest version of our SDK, just repeat steps 1-9.

Configure your Stripe integration in your App Delegate

After you're done installing the SDK, configure it with your Stripe API keys.

import UIKit
import Stripe

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        STPPaymentConfiguration.sharedConfiguration().publishableKey = "pk_test_6pRNASCoBOKtIshFeQd4XMUh"
        // do any other necessary launch configuration
        return true
    }
}
#import "AppDelegate.h"
@import Stripe;

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[STPPaymentConfiguration sharedConfiguration] setPublishableKey:@"pk_test_6pRNASCoBOKtIshFeQd4XMUh"];
    // do any other necessary launch configuration
    return YES;
}
@end

Set up Apple Pay (optional)

Getting ready to accept Apple Pay in your app involves some (very quick) setup on the Apple Developer website, which we have as a separate guide to help get started. After you've obtained an Apple Merchant ID, set it in your configuration:

STPPaymentConfiguration.sharedConfiguration().appleMerchantIdentifier = "your apple merchant identifier"
[[STPPaymentConfiguration sharedConfiguration] setAppleMerchantIdentifier:@"your apple merchant identifier"];

Begin accepting payments

This guide will take you through building your app's payment flow with a utility called STPPaymentContext. It's a high-level abstraction that handles all the complexity of capturing, storing, and retrieving your user's payment details. If you find that it's not flexible enough for your needs, though, all of the subcomponents it uses under the hood are available for you to use as well. For this, please read our custom iOS integration guide.

Prepare your API

Our prebuilt UI elements operate on the assumption that you have a single Customer object for each of your users. We strongly recommend you create this Customer at the same time you create your user on your own backend, so that every user is guaranteed to have an associated Customer (this is fine even if you don't collect your user's payment information when they sign up—it's totally OK to have a Customer without any attached cards).

In order for our prebuilt UI elements to function, you need to provide them with information about your user's saved payment information. To fetch this information, you should expose three APIs on your backend for your iOS app to communicate with.

Endpoint 1: Retrieve the Customer object for the currently logged-in user

This is called to populate the user's list of payment methods in our UI. For this, you can just call the Stripe Retrieve Customer API and return its unmodified response as JSON.

require "json"

# Using Sinatra (http://www.sinatrarb.com/)
get "/customer" do
  begin
    customer_id = "..." # Load the Stripe Customer ID for your logged in user
    customer = Stripe::Customer.retrieve(customer_id)
  rescue Stripe::StripeError => e
    status 402
    return "Error retrieving customer: #{e.message}"
  end
  status 200
  content_type :json
  customer.to_json
end
import json
from django.http import HttpResponse
from django.http import JsonResponse

# Using Django (https://www.djangoproject.com/)
def my_customer_view(request):
  try:
    customer_id = "..." # Load the Stripe Customer ID for your logged in user
    customer = stripe.Customer.retrieve(customer_id)
    return JsonResponse(customer)
  except stripe.error.StripeError as e:
    return HttpResponse(status=402)
try {
  $customer_id = "..."; // Load the Stripe Customer ID for your logged in user
  $customer = \Stripe\Customer::retrieve($customer_id);
  header('Content-Type: application/json');
  echo $customer->jsonSerialize();
} catch(\Stripe\Error $e) {
  http_response_code(402);
}
// Using Express (http://expressjs.com/)
app.get('/customer', function(request, response) {
  var customerId = '...'; // Load the Stripe Customer ID for your logged in user
  stripe.customers.retrieve(customerId, function(err, customer) {
    if (err) {
      response.status(402).send('Error retrieving customer.');
    } else {
      response.json(customer);
    }
  })
});
// Using Spark framework (http://sparkjava.com)
import com.google.gson.Gson;

private Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();

get("/customer", (request, response) -> {
  String customerID = "..."; // Load the Stripe Customer ID for your logged in user
    try {
      Customer customer = Customer.retrieve(customerID);
      response.status(200);
      return gson.toJson(customer);
    } catch (StripeException e) {
      response.status(402);
      return "";
    }
});

Endpoint 2: Attach a new payment source to the Customer for the currently-logged in user

This is called when the user adds a new payment method via our UI. For this, you can call the Stripe Create Card API.

require "json"

# Using Sinatra (http://www.sinatrarb.com/)
post "/customer/sources" do
  begin
    customer_id = "..." # Load the Stripe Customer ID for your logged in user
    customer = Stripe::Customer.retrieve(customer_id)
    customer.sources.create({:source => params[:source]})
    status 200
  rescue Stripe::StripeError => e
    status 402
    return "Error retrieving customer: #{e.message}"
  end
end
import json
from django.http import HttpResponse

# Using Django (https://www.djangoproject.com/)
def my_customer_source_view(request):
  try:
    customer_id = "..." # Load the Stripe Customer ID for your logged in user
    customer = stripe.Customer.retrieve(customer_id)
    source = request.POST['source']
    customer.sources.create(source=source)
    return HttpResponse(status=200)
  except stripe.error.StripeError as e:
    return HttpResponse(status=402)
$customer_id = "..."; // Load the Stripe Customer ID for your logged in user

try {
  $customer = \Stripe\Customer::retrieve($customer_id);
  $customer->sources->create(array("source" => $_POST["source"]));
  http_response_code(200);
} catch(\Stripe\Error $e) {
  http_response_code(402);
}
// Using Express (http://expressjs.com/)
app.post('/customer/sources', function(request, response) {
  var customerId = '...'; // Load the Stripe Customer ID for your logged in user
  stripe.customers.createSource(customerId, {
    source: request.body.source
  }, function(err, source) {
    if (err) {
      response.status(402).send('Error attaching source.');
    } else {
      response.status(200).end();
    }
  });
});
// Using Spark framework (http://sparkjava.com)
post("/customer/sources", (request, response) -> {
  String customerID = "..."; // Load the Stripe Customer ID for your logged in user
    try {
      Customer customer = Customer.retrieve(customerID);
      Map<String, Object> params = new HashMap<String, Object>();
      params.put("source", request.params("source"));
      customer.getSources().create(params);
      response.status(200);
    } catch (StripeException e) {
      response.status(402);
    }
    return "";
});

Endpoint 3: Select a new default payment source on the Customer for the currently logged-in user

This is called when the user changes their selected payment method in our UI. For this, you can call the Stripe Customer Update API and specify a new default_source.

require "json"

# Using Sinatra (http://www.sinatrarb.com/)
post "/customer/default_source" do
  begin
    customer_id = "..." # Load the Stripe Customer ID for your logged in user
    customer = Stripe::Customer.retrieve(customer_id)
    customer.default_source = params[:default_source]
    customer.save
    status 200
  rescue Stripe::StripeError => e
    status 402
    return "Error retrieving customer: #{e.message}"
  end
end
import json
from django.http import HttpResponse

# Using Django (https://www.djangoproject.com/)
def my_customer_default_source_view(request):
  try:
    customer_id = "..." # Load the Stripe Customer ID for your logged in user
    customer = stripe.Customer.retrieve(customer_id)
    customer.default_source = request.POST['default_source']
    customer.save()
    return HttpResponse(status=200)
  except stripe.error.StripeError as e:
    return HttpResponse(status=402)
$customer_id = "..." // Load the Stripe Customer ID for your logged in user

try {
  $customer = \Stripe\Customer::retrieve($customer_id);
  $customer->default_source = $_GET["default_source"];
  $customer->save();
  http_response_code(200);
} catch(\Stripe\Error $e) {
  http_response_code(402);
}
// Using Express (http://expressjs.com/)
app.post('/customer/default_source', function(request, response) {
  var customerId = '...'; // Load the Stripe Customer ID for your logged in user
  stripe.customers.update(customerId, {
    default_source: request.body.defaultSource
  }, function(err, customer) {
    if (err) {
      response.status(402).send('Error setting default source.');
    } else {
      response.status(200).end();
    }
  });
});
// Using Spark framework (http://sparkjava.com)
post("/customer/sources", (request, response) -> {
  String customerID = "..." # Load the Stripe Customer ID for your logged in user
    try {
      Customer customer = Customer.retrieve(customerID);
      Map<String, Object> updateParams = new HashMap<String, Object>();
      updateParams.put("default_source", request.params("default_source"));
      customer.update(updateParams);
      response.status(200);
    } catch (StripeException e) {
      response.status(402);
    }
    return "";
});

Next, you need to have a way for your iOS app to communicate with these endpoints. To make this easier, we've come up with a concept of an "API Adapter"—a Swift/Objective-C class that communicates with your backend API and returns objects that the prebuilt Stripe UI knows how to process. To do this, you should make an API client class that conforms to the STPBackendAPIAdapter protocol which has three required methods (note how they align with the new endpoints you've exposed on your backend API):

  • - retrieveCustomer:completion: Read more
  • - attachSourceToCustomer:completion: Read more
  • - selectDefaultCustomerSource:completion: Read more

You can consult the Example App in our SDK to see this in practice.

Implement your app's checkout flow using STPPaymentContext

We've created a new class called STPPaymentContext that is designed to make building your app's checkout flow as easy as possible, including collecting, saving, and reusing your users' payment details. Think of it as the data source for your checkout view controller—it handles asynchronously retrieving the data you need, when you need it, and notifies its delegate when its UI should change. Most importantly, it lets you build a single integration to accept payments via both credit card and Apple Pay instead of having multiple code paths.

Setting the delegate and host view controller

To work with STPPaymentContext, you'll need to write a class that conforms to STPPaymentContextDelegate. This has 4 required methods (note, the code samples in this section are for example purposes; your implementation might be a little different depending on the structure of your app):

- paymentContextDidChange:

This is called, as you might expect, when the payment context's contents change. This is called, for example, when the user selects a new payment method. This is a good place to update your UI:

func paymentContextDidChange(paymentContext: STPPaymentContext) {
    self.activityIndicator.animating = paymentContext.loading
    self.paymentButton.enabled = paymentContext.selectedPaymentMethod != nil
    self.paymentLabel.text = paymentContext.selectedPaymentMethod?.label
    self.paymentIcon.image = paymentContext.selectedPaymentMethod?.image
}
- (void)paymentContextDidChange:(STPPaymentContext *)paymentContext {
    self.activityIndicator.animating = paymentContext.loading;
    self.paymentButton.enabled = paymentContext.selectedPaymentMethod != nil;
    self.paymentLabel.text = paymentContext.selectedPaymentMethod.label;
    self.paymentIcon.image = paymentContext.selectedPaymentMethod.image;
}

- paymentContext:didCreatePaymentResult:completion:

This is called when the user has successfully selected a payment method and completed their purchase. You should pass the contents of the paymentResult object to your backend API, which should then finish charging your user using the create charge API. When this API request is finished, call the provided completion block with nil as its only argument if the call succeeded, or, if an error occurred, with that as the argument instead.

func paymentContext(paymentContext: STPPaymentContext,
  didCreatePaymentResult paymentResult: STPPaymentResult,
  completion: STPErrorBlock) {

  myAPIClient.createCharge(paymentResult.source.stripeID, completion: { (error: NSError?) in
      if let error = error {
          completion(error)
      } else {
          completion(nil)
      }
  })
}
- (void)paymentContext:(STPPaymentContext *)paymentContext
didCreatePaymentResult:(STPPaymentResult *)paymentResult
            completion:(STPErrorBlock)completion {
    [self.apiClient createCharge:paymentResult.source.stripeID completion:^(NSError *error) {
        if (error) {
            completion(error);
        } else {
            completion(nil);
        }
    }];
}

- paymentContext:didFinishWithStatus:error:

This is called after the previous method, when any auxiliary UI that has been displayed (such as the Apple Pay dialog) has been dismissed. You should inspect the returned status and show an appropriate message to your user. For example:

func paymentContext(paymentContext: STPPaymentContext,
  didFinishWithStatus status: STPPaymentStatus,
  error: NSError?) {

    switch status {
    case .Error:
        self.showError(error)
    case .Success:
        self.showReceipt()
    case .UserCancellation:
        return // Do nothing
    }
}
- (void)paymentContext:(STPPaymentContext *)paymentContext
   didFinishWithStatus:(STPPaymentStatus)status
                 error:(NSError *)error {
    switch (status) {
        case STPPaymentStatusSuccess:
            [self showReceipt];
        case STPPaymentStatusError:
            [self showError:error];
        case STPPaymentStatusUserCancellation:
            return; // Do nothing
    }
}

- paymentContext:didFailToLoadWithError:

This is called in the rare case that the payment context's initial loading call fails, usually due to lack of internet connectivity. You should dismiss your checkout page when this occurs and invite the user to try again. You can also optionally attempt to try again by calling retryLoading on the payment context.

func paymentContext(paymentContext: STPPaymentContext,
  didFailToLoadWithError error: NSError) {
    self.navigationController?.popViewControllerAnimated(true)
    // Show the error to your user, etc.
}
- (void)paymentContext:(STPPaymentContext *)paymentContext didFailToLoadWithError:(NSError *)error {
     [self.navigationController popViewControllerAnimated:YES];
     // Show the error to your user, etc.
}

This is called in the rare case that the payment context's initial loading call fails, usually due to lack of internet connectivity. You should dismiss your checkout page when this occurs and invite the user to try again.

Once you've written a class that conforms to STPPaymentContextDelegate, you can actually go about initializing an STPPaymentContext with an API adapter. After you do this, set its delegate and hostViewController properties (these will usually be the same object, a UIViewController instance). You should also set the payment context's paymentAmount property, which will be displayed to your user in the Apple Pay dialog (you can also change it later, if the amount of the user's purchase changes).

init() {
    // Here, MyAPIAdapter is your class that implements STPBackendAPIAdapter (see above)
    self.paymentContext = STPPaymentContext(apiAdapter: MyAPIAdapter())
    super.init(nibName: nil, bundle: nil)
    self.paymentContext.delegate = self
    self.paymentContext.hostViewController = self
    self.paymentContext.paymentAmount = 5000 // Measured in cents, i.e. $50 USD
}
- (instancetype)init {
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
       // Here, MyAPIAdapter is your class that implements STPBackendAPIAdapter (see above)
       id<STPBackendAPIAdapter> apiAdapter = [[MyAPIAdapter alloc] init];
       self.paymentContext = [[STPPaymentContext alloc] initWithAPIAdapter:apiAdapter];
       self.paymentContext.delegate = self;
       self.paymentContext.hostViewController = self;
       self.paymentContext.paymentAmount = 5000 // Measured in cents, i.e. $50 USD
    }
    return self;
}

Let your user select their payment method

When you'd like to give your user the chance to enter or change their payment method (say, they tapped a button on your checkout page that lets them do this), STPPaymentContext can do this for you automatically. You can specify whether you'd like the payment selector view controller to be presented modally, or pushed onto a UINavigationController stack:

// If you prefer a modal presentation
func choosePaymentButtonTapped() {
    self.paymentContext.presentPaymentMethodsViewController()
}

// If you prefer a navigation transition
func choosePaymentButtonTapped() {
    self.paymentContext.pushPaymentMethodsViewController()
}
// If you prefer a modal presentation
- (void)choosePaymentButtonTapped {
    [self.paymentContext presentPaymentMethodsViewController];
}

// If you prefer a navigation transition
- (void)choosePaymentButtonTapped {
    [self.paymentContext pushPaymentMethodsViewController];
}

This will set up and present an STPPaymentMethodsViewController on the payment context's hostViewController. If the user doesn't have any stored payment methods, it'll automatically prompt them to enter one. If the user has ever made a purchase in another app that uses STPPaymentContext (and opted in, of course) they'll have the option to autofill their payment details by entering an SMS code. For more information, take a look at our custom iOS integration guide.

Finishing a payment

Finally, when your user taps "Buy", just call requestPayment on your payment context. It'll display any required UI (such as the Apple Pay dialog) and call the appropriate methods on its delegate as your user finishes their payment.

func payButtonTapped() {
    self.paymentContext.requestPayment()
}
- (void)payButtonTapped {
    [self.paymentContext requestPayment];
}

Customizing the look-and-feel of Stripe UI elements

We built the payment selector so that you can define your own appearance and apply the attributes you want to customize from the default theme that we provide.

Stripe iOS UI Theming

You can override any of the properties from the default theme, typically in your AppDelegate:

STPTheme.defaultTheme().accentColor = UIColor.blueColor()
[[STPTheme defaultTheme] setAccentColor:[UIColor blueColor]];

Here is a list of properties you can customize and their respective usage inside the payment selector UI:

Property Name Description
primaryBackgroundColor Background color for any views in this theme
secondaryBackgroundColor Background color for any supplemental views inside a view (for example the cells of a table view)
primaryForegroundColor Text color for any important labels in a view
secondaryForegroundColor Text color for any supplementary labels in a view
accentColor Color for any buttons and other elements on a view that are important to highlight
errorColor Color for rendering any error messages or views
font Font to be used for all views
emphasisFont Medium-weight font to be used for all bold text in views

We also let you customize all the fonts used in this payment selector flow. By default, the SDK will use the system font at different weight and sizes. To override the defaults, set the font and emphasisFont properties and the SDK will automatically use your choice instead and infer the rest.

More information

If you'd like more help, we provide an example app that implements all of the code in this tutorial.

In addition, if you'd like to implement a custom payment flow, all of the sub-components of STPPaymentContext are usable individually. You can read more about them in our custom iOS integration guide.