Set Up Your Client

Choose an SDK preference:

The Braintree iOS SDK helps you accept payments in your iOS app.

Requirements

Installation

There are multiple ways to include Braintree in your project. See the Installation section of our README.

Setup for app switch

To handle payments that involve switching to another app or SFSafariViewController for authentication, you must register a URL type and configure your app to return from app switches.

Register a URL type

  1. In Xcode, click on your project in the Project Navigator and navigate to App Target > Info > URL Types
  2. Click [+] to add a new URL type
  3. Under URL Schemes, enter your app switch return URL scheme. This scheme must start with your app's Bundle ID and be dedicated to Braintree app switch returns. For example, if the app bundle ID is com.your-company.Your-App, then your URL scheme could be com.your-company.Your-App.payments.
important

If you have multiple app targets, be sure to add the return URL type for all of the targets.

Testing the URL type

You can test out your new URL scheme by opening up a URL that starts with it (e.g. com.your-company.Your-App.payments://test) in Mobile Safari on your iOS Device or Simulator.

In addition, always test your app switching on a real device.

Update your application delegate

In your AppDelegate's application:didFinishLaunchingWithOptions: implementation, use setReturnURLScheme: with the value you set above.

For example:

#import "AppDelegate.h"
#import "BraintreeCore.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [BTAppSwitch setReturnURLScheme:@"com.your-company.Your-App.payments"];
    return YES;
}

Then in your application delegate, pass the payment authorization URL to Braintree for finalization:

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    if ([url.scheme localizedCaseInsensitiveCompare:@"com.your-company.Your-App.payments"] == NSOrderedSame) {
        return [BTAppSwitch handleOpenURL:url options:options];
    }
    return NO;
}

// If you support iOS 7 or 8, add the following method.
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    if ([url.scheme localizedCaseInsensitiveCompare:@"com.your-company.Your-App.payments"] == NSOrderedSame) {
        return [BTAppSwitch handleOpenURL:url sourceApplication:sourceApplication];
    }
    return NO;
}

Supporting iOS 9

iOS 9 introduces new security restrictions that can impact the behavior of the Braintree SDK.

App Transport Security

As of 09/30/2015, all endpoints contacted by the Braintree iOS SDK are compatible with Apple's App Transport Security requirements. No ATS exceptions are necessary.

If your app's Info.plist previously contained NSExceptionDomains entries for api.braintreegateway.com or kaptcha.com (for apps using Kount), we recommend you remove these exceptions. As with any changes which may affect your app in production, please be sure to test and verify all behavior before releasing an update to the App Store.

Initialize Braintree

In your checkout controller or wherever else you handle orders and payments, declare a property:

#import "BraintreeCore.h"

@interface MyViewController ()
@property (nonatomic, strong) BTAPIClient *braintreeClient;
@end

Get a client token

Your server is responsible for generating a client token, which contains the authorization and configuration details that your client needs to initialize the client SDK.

Your app should request a client token from your server. This example uses our sample integration server; please adapt it to use your own backend API.

- (void)fetchClientToken {
    // TODO: Switch this URL to your own authenticated API
    NSURL *clientTokenURL = [NSURL URLWithString:@"https://braintree-sample-merchant.herokuapp.com/client_token"];
    NSMutableURLRequest *clientTokenRequest = [NSMutableURLRequest requestWithURL:clientTokenURL];
    [clientTokenRequest setValue:@"text/plain" forHTTPHeaderField:@"Accept"];

    [[[NSURLSession sharedSession] dataTaskWithRequest:clientTokenRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        // TODO: Handle errors
        NSString *clientToken = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

        // As an example, you may wish to present Drop-in at this point.
        // Continue to the next section to learn more...
    }] resume];
}

You should obtain a new client token often, at least as often as your app restarts. For the best experience, you should kick off this network operation before it would block a user interaction.

important

You must generate a client token on your server once per user checkout session. The endpoint we provide in this example is for demonstration purposes only.

PayPal configuration

Invoking Express Checkout

First, make sure you have registered your URL type and updated your app delegate. Then, use BTPayPalDriver and BTPayPalRequest to start the process. A transaction amount is required to invoke the one-time payment flow. An example integration might look like this:

// MyViewController.m
#import "MyViewController.h"
#import "BraintreePayPal.h"

@interface MyViewController () <BTAppSwitchDelegate, BTViewControllerPresentingDelegate>
@property (nonatomic, strong) BTAPIClient *braintreeClient;
@property (nonatomic, strong) BTPayPalDriver *payPalDriver;
@end

@implementation MyViewController

- (void)startCheckout {
    // Example: Initialize BTAPIClient, if you haven't already
    self.braintreeClient = [[BTAPIClient alloc] initWithAuthorization:@"<#CLIENT_AUTHORIZATION#>"];
    BTPayPalDriver *payPalDriver = [[BTPayPalDriver alloc] initWithAPIClient:self.braintreeClient];
    payPalDriver.viewControllerPresentingDelegate = self;
    payPalDriver.appSwitchDelegate = self; // Optional

    // Specify the transaction amount here. "2.32" is used in this example.
    BTPayPalRequest *request= [[BTPayPalRequest alloc] initWithAmount:@"2.32"];
    request.currencyCode = @"USD"; // Optional; see BTPayPalRequest.h for other options

    [payPalDriver requestOneTimePayment:request completion:^(BTPayPalAccountNonce * _Nullable tokenizedPayPalAccount, NSError * _Nullable error) {
        if (tokenizedPayPalAccount) {
            NSLog(@"Got a nonce: %@", tokenizedPayPalAccount.nonce);

            // Access additional information
            NSString *email = tokenizedPayPalAccount.email;
            NSString *firstName = tokenizedPayPalAccount.firstName;
            NSString *lastName = tokenizedPayPalAccount.lastName;
            NSString *phone = tokenizedPayPalAccount.phone;

            // See BTPostalAddress.h for details
            BTPostalAddress *billingAddress = tokenizedPayPalAccount.billingAddress;
            BTPostalAddress *shippingAddress = tokenizedPayPalAccount.shippingAddress;
        } else if (error) {
            // Handle error here...
        } else {
            // Buyer canceled payment approval
        }
    }];
}

@end

Supported currencies

The currencyCode field determines the currency of the transaction displayed to the customer in the Express Checkout flow. You'll pass the same currency with the transaction request on the server side.

note

When you first create your PayPal business account, you'll be able to pass only the default currency for the country associated with your business account. If you'd like to display transactions in additional currencies, see the multi-currency setup section below.

See the full list of supported currencies for Express Checkout.

Multi-currency setup

In order to display transactions in currencies other than the default currency for the country associated with your business account, you'll need to add them to your account as follows:

  1. Access the My Apps & Credentials page in your PayPal Developer Dashboard
    • Select your Live account
    • View currently enabled currencies for your account
    • Select currencies you would like to add and click the Add Currencies button
  2. Access the My Money page of your PayPal business account

Once a currency is enabled, you can begin passing it in the currencyCode field.

note

Currencies can't be removed from your Developer Dashboard once they have been added. If you no longer wish to display a particular currency, you can choose not to pass it in the currencyCode field. You can close the currency in your business account, if you'd like.

Send payment method nonce to server

Send the resulting payment method nonce to your server (again, adapt this example to your own setup):

- (void)postNonceToServer:(NSString *)paymentMethodNonce {
    // Update URL with your server
    NSURL *paymentURL = [NSURL URLWithString:@"https://your-server.example.com/checkout"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:paymentURL];
    request.HTTPBody = [[NSString stringWithFormat:@"payment_method_nonce=%@", paymentMethodNonce] dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPMethod = @"POST";

    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        // TODO: Handle success and failure
    }] resume];
}

See also

Next Page: Set Up Your Server →

Still Have Questions?

Browse our support options or submit a question to our technical support team.