note

We have upgraded our 3D Secure integration in preparation for 3DS 2 and PSD2 Strong Consumer Authentication (SCA) compliance requirements in 2019.

This guide shows our integration for 3DS 2.

Payment flow

Generate a client token

important

You must generate a client token if you want to use 3D Secure. Tokenization keys can't be used when processing 3D Secure transactions.

Before you can initialize BTPaymentFlowDriver, you will need to set up the SDK and initialize it with a client token generated on your server.

Update your SDK version

CocoaPods

3DS 2 support requires version 4.26.3 or higher, as well as the Payment Flow subspec. Update your Podfile to require at least the minimum version and include the Payment Flow subspec:

Ruby
pod 'Braintree'
pod 'Braintree/PaymentFlow'

Carthage

Add github "braintree/braintree_ios" to your Cartfile, and add the frameworks to your project.

For 3DS 2, you must add the following framework:

CardinalMobile.framework

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 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;
}

Specify a merchant account

If you would like to use a merchant account ID other than your default, specify the merchant_account_id when generating the client token.

note

This merchant account ID must match the merchant account ID used to create the transaction.

Render a checkout page

To minimize the need for issuing banks to present authentication challenges to customers, update your checkout page to collect as many of these customer data fields as possible. These new fields are not strictly required, but without them, you and your customers won't get the most out of 3DS 2.

Field Name Description
givenName Customer's first name.
surname Customer's last name.
streetAddress Customer's billing street address.
extendedAddress Customer's billing extended address when available (e.g. Apt. #3).
locality Customer's billing city.
region Customer's billing state, county, or province, if applicable.
postalCode Customer's billing postal code.
countryCodeAlpha2 Customer's ISO 3166-1 alpha-2 country code for their billing address.
billingPhoneNumber Customer's billing phone number.
email Customer's email.

You can structure your native checkout flow however you'd like. If you don't already have a credit card form, consider our Drop-in UI.

Start by adding an import statement:

#import "BraintreePaymentFlow.h"

@interface YourCheckoutViewController () <BTViewControllerPresentingDelegate>

@property (nonatomic, strong, readwrite) BTPaymentFlowDriver *paymentFlowDriver;

@end

Then initialize the BTPaymentFlowDriver and set the viewControllerPresentingDelegate:

- (void)setupPaymentFlowDriver {
    self.paymentFlowDriver = [[BTPaymentFlowDriver alloc] initWithAPIClient:self.apiClient];
    self.paymentFlowDriver.viewControllerPresentingDelegate = self;
}

Your view controller should conform to BTViewControllerPresentingDelegate in order to handle view controller presentation.

- (void)paymentDriver:(id)driver requestsPresentationOfViewController:(UIViewController *)viewController {
    [self presentViewController:viewController animated:YES completion:nil];
}

- (void)paymentDriver:(id)driver requestsDismissalOfViewController:(UIViewController *)viewController {
    [self dismissViewControllerAnimated:YES completion:nil];
}

Verify a credit card

  1. Construct a BTCard object by collecting customer card details.
  2. Make a call to tokenizeCard:completion with this card data to generate a payment method nonce.
  3. Construct a BTThreeDSecureRequest containing the nonce and transaction amount.
    • The transaction amount is required at verification for two reasons. First, it's an additional check to make sure the transaction being verified is the same as that being eventually authorized and settled. For this reason, the amount submitted for verification must match the amount sent to the Braintree server for authorization. Second, some issuers use the amount to help determine whether they should challenge the user to authenticate.
  4. Construct BTThreeDSecurePostalAddress and BTThreeDSecureAdditionalInformation as properties on the BTThreeDSecureRequest.
    • To reduce the need for issuing banks to challenge cardholders to authenticate with 3DS 2, pass as many parameters from the code snippet below to BTThreeDSecureRequest as possible.
  5. Implement the required BTThreeDSecureRequestDelegate protocol.
    • The onLookupComplete:result:next is a required delegate method that is called after the lookup completes and before a challenge is initiated. You must call next() to continue the flow.
  6. Verify the transaction with startPaymentFlow:completion:.
    • This call will refer to card data derived from the payment method nonce and will present the cardholder with a 3D Secure authentication challenge if needed.
- (IBAction)tappedCheckout {
    // Create a BTCard based on the UI state
    BTCard *details = [[BTCard alloc] init];
    details.number = self.cardNumberField.text;
    details.expirationMonth = self.expirationMonthField.text;
    details.expirationYear = self.expirationYearField.text;

    // Tokenize the card
    [self.cardClient tokenizeCard:details completion:^(BTCardNonce *tokenizedCard, NSError *error) {
        if (error) {
          // Handle errors
          return;
        }

        BTThreeDSecureRequest *request = [[BTThreeDSecureRequest alloc] init];
        request.amount = [NSDecimalNumber decimalNumberWithString:@"10"];
        request.nonce = tokenizedCard.nonce;
        request.email = @"test@email.com";
        request.versionRequested = BTThreeDSecureVersion2;

        // Make sure that self conforms to the BTThreeDSecureRequestDelegate protocol
        request.threeDSecureRequestDelegate = self;

        BTThreeDSecurePostalAddress *address = [BTThreeDSecurePostalAddress new];
        address.givenName = @"Jill";
        address.surname = @"Doe";
        address.phoneNumber = @"5551234567";
        address.streetAddress = @"555 Smith St";
        address.extendedAddress = @"#2";
        address.locality = @"Chicago";
        address.region = @"IL";
        address.postalCode = @"12345";
        address.countryCodeAlpha2 = @"US";
        request.billingAddress = address;

        // Optional additional information.
        // For best results, provide as many of these elements as possible.
        BTThreeDSecureAdditionalInformation *additionalInformation = [BTThreeDSecureAdditionalInformation new];
        additionalInformation.shippingAddress = address;
        request.additionalInformation = additionalInformation;

        [self.paymentFlowDriver startPaymentFlow:request completion:^(BTPaymentFlowResult * _Nonnull result, NSError * _Nonnull error) {
            if (error) {
                // Handle error
            } else if (result) {
                BTThreeDSecureResult *threeDSecureResult = (BTThreeDSecureResult *)result;

                if (threeDSecureResult.tokenizedCard.threeDSecureInfo.liabilityShiftPossible) {
                    if (threeDSecureResult.tokenizedCard.threeDSecureInfo.liabilityShifted) {
                        // 3D Secure authentication success
                    } else {
                        // 3D Secure authentication failed
                    }
                } else {
                    // 3D Secure authentication was not possible
                }

                // Use the `threeDSecureResult.tokenizedCard.nonce`
            }
        }];
    }];
}

- (void)onLookupComplete:(__unused BTThreeDSecureRequest *)request result:(__unused BTThreeDSecureLookup *)lookup next:(void (^)(void))next {
    // Optionally inspect the lookup result and prepare UI if a challenge is required
    next();
}
  • If the user successfully completes the 3D Secure process, the startPaymentFlow callback block will receive a BTThreeDSecureResult with a tokenizedCard property. You should transmit the tokenizedCard.nonce to your server and create a transaction.

  • If the user cancels the 3D Secure authentication, the completion block will be called with an error where code is BTPaymentFlowDriverErrorTypeCanceled.

  • If the 3D Secure process fails, the completion block will be called with an error.

In order to perform 3D Secure authentication again, a new nonce needs to be supplied.

For each request to verify a card, the completion block will be called exactly once.

Verify a vaulted credit card

First, on the server, generate and return a payment method nonce for the vaulted credit card.

Then on the client, you can use the startPaymentFlow:completion: method just as before and pass it the newly-generated nonce.

Validation errors

Braintree will evaluate any fields passed against Cardinal's documentation. You will receive a validation error from Braintree if a field is incorrect.

Advanced client-side options

We expose additional information about the authentication request that you can use for more advanced UI flows or risk assessment. You should be aware that making such assessments may result in accepting the liability for fraudulent transactions.

These parameters pass through the client-side first and should not be trusted for your server-side risk assessment. They should be used for UI flow only.

// In this example, `card` is a `BTCardNonce`.
if (card.threeDSecureInfo.liabilityShiftPossible) {
    if (card.threeDSecureInfo.liabilityShifted) {
        // 3D Secure authentication success
    } else {
        // 3D Secure authentication failed
    }
} else {
    // 3D Secure authentication was not possible
}
  1. liabilityShifted indicates that 3D Secure worked and authentication succeeded. This will also be true if the issuing bank does not support 3D Secure, but the payment method does. In both cases, the liability for fraud has been shifted to the bank. You should go on creating a transaction using the new nonce.
  2. liabilityShiftPossible indicates that the payment method was eligible for 3D Secure. If liabilityShifted is false, then the user failed 3D Secure authentication. In this situation, the card brands recommend asking the user for another form of payment. However, if you have server-side risk assessment processes that allow for it, you can still use the new nonce to create a transaction. If you want to use a nonce that did not pass 3D Secure authentication, you need to set the required option to false in your server integration.
  3. If both of the above values are false then this card was ineligible for 3D Secure. You can continue to create the transaction with the new nonce. However, liability shift will not apply to this transaction. This case may be useful if you would like to ask the user for additional verification (AVS, etc).
important

For American Express SafeKey, liabilityShifted may be returned as true but Amex may later revoke the liability shift for the transaction based on your merchant behavior and fraud rate.

Next Page: Server-side →