# Integrate with Click to Pay for Mobile source: https://developer.mastercard.com/mastercard-checkout-solutions/documentation/tutorials-and-guides/mobile-tutorial/index.md There is currently no native SDK support for building your own SRCI experience within a merchant application. You need to implement a web checkout experience as described in the [Integration Overview](https://developer.mastercard.com/mastercard-checkout-solutions/documentation/tutorials-and-guides/index.md) (for example using the [Javascript SDK](https://developer.mastercard.com/mastercard-checkout-solutions/documentation/sdk-reference/index.md)), and then provide this experience in the mobile application using an embedded WebView. This direct integration approach may be described as application-to-web or **app-to-web** (as opposed to web-to-web). There are some details to do with the messaging between the windows inside the webview that need to be handled within your iOS view controller or Android Activity code that are described below. The following information describes how you as SRCI might construct a suitable set of classes for use in merchant applications. If you have several mobile DPA applications that you will support as SRCI, it may make sense to consider creating your own library of classes along these lines so that you can re-use the solution---however the same event handling code is needed whether or not you choose to abstract the solution into your own library, or simply implement once within the application. The instructions below show a suggested approach. ## Prerequisites {#prerequisites} * You have a working web based implementation that is suitable for display on mobile. Your web based SRCI implementation can be invoked using a URL. * You have constructed the bulk of your mobile application and are ready to add Click to Pay within a view (**ViewController** in iOS, **Activity** in Android) via a webview (**WKWebview** for iOS, **WebView** for Android). * Your ViewController/Activity is able to handle the interaction between the SRCI screens you are hosting and the DCF screens that the card network is hosting. Both are presented via webviews within your checkout view controller or activity. The instructions below explain how to add suitable web views for the SRCI and DCF functionality and to handle the interaction. When complete, the architecture of your solution will look something like the following: ![Mobile App to Web Flow](https://static.developer.mastercard.com/content/mastercard-checkout-solutions/documentation/images/mobile_app_to_web_flow.png) ## 1. Build Web Components to Load in Native WebView {#1-build-web-components-to-load-in-native-webview} As an integrator, you can create your own code (either within an app or as library you provide for use in multiple apps) that handles the checkout flow via the SRCI and DCF screens, and returns control back to the merchant application when the transaction is resolved. ### Components needed {#components-needed} A typical mobile application (DPA) that provides Click to Pay need to implement something suitable for the following (either directly in the application or via some library shared between the applications that you as SRCI support): 1. Configuration object - To allow the application to specify the list of supported payment cards (Mastercard, Visa, American express etc), supported Locale etc. 2. Checkout Request object - A data object with transaction-specific parameters needed to complete checkout. This request can also override existing merchant configurations. The application needs to be able to form the request correctly. 3. A class to handle initialization with a configuration object, launching a suitable web-view to handle the SRCI experience and connecting to DCF providers. The web experience is the same as the web experience you as SRCI provide for web applications (see the Client Side Integration pages on using the JavaScript SDK and Building the SRCI Screens). 4. A way to handle the checkout result and notify the merchant application. One issue that you need to address is to ensure that the transition between the part of the checkout experience that you create (the SRCI pages) and the part provided by the card network DCF is handled correctly when working inside web-views inside a mobile application, since the normal web page method of passing control between web pages will not be sufficient without your application handling events inside the Android Activity or iOS ViewController. The documentation in this section describes a possible approach for this, as an example. The code samples provided illustrate possible solutions using the following approaches: * iOS --- ViewController using **WKWebView** from the WebKit framework. Refer to the Apple developer documentation [here](https://developer.apple.com/documentation/webkit/wkwebview). * Android --- Activity with **WebView** . Refer to the Android developer documentation [here](https://developer.android.com/guide/webapps/webview). ### Configuration and checkout {#configuration-and-checkout} You could implement a configuration class as the following sample shows: * Java * Objective-C ```java // Sample configuration Locale locale = Locale.US; String checkoutId = CHECKOUT_ID; // unique id for a particular Merchant or PSP String checkoutUrl = CHECKOUT_URL; // URL to launch SRCI web experience Set allowedCardTypes = Collections.emptySet(); allowedCardTypes.add(CardType.MASTER); Configuration config = new Configuration(locale, checkoutId, checkoutUrl, allowedCardTypes); MerchantSDK sdk = MerchantSDK.getInstance(); sdk.initialize(config, context); ``` ```objective-C // Sample configuration @implementation MCSConfiguration - (instancetype _Nonnull) initWithLocale: (NSLocale * ) locale checkoutId: (NSString * ) checkoutId checkoutUrl: (NSString * ) checkoutUrl callbackScheme: (NSString * ) scheme allowedCardTypes: (NSSet < MCSCardType > * ) allowedCardTypes presentingViewController: (UIViewController * _Nullable) presentingViewController { if (self = [super init]) { self.locale = locale; self.checkoutId = checkoutId; self.checkoutUrl = checkoutUrl; self.callbackScheme = scheme; self.allowedCardTypes = allowedCardTypes; self.presentingViewController = presentingViewController; } return self; } @end ``` A sample checkout request could be: * Java * Objective-C ```java // Sample Checkout request @Override public CheckoutRequest getCheckoutRequest() { Set cryptoFormat = new HashSet<>(); cryptoFormat.add(CryptoFormat.UCAF); CryptoOptions cryptoOptions = new CryptoOptions(cryptoFormat); Set cryptoOptionsSet = new HashSet<>(); cryptoOptionsSet.add(cryptoOptions); CheckoutRequest request = new CheckoutRequest.Builder() .amount(totalAmount) .cartId(UUID.randomUUID().toString()) .currency("USD") .cryptoOptions(cryptoOptionsSet) .build(); return request; } ``` ```objective-c // Sample Checkout request + (NSDictionary *)dictionaryForCheckoutRequest:(MCSCheckoutRequest *)checkoutRequest configuration:(MCSConfiguration *)configuration { NSMutableDictionary *checkoutRequestDictionary = [[NSMutableDictionary alloc] init]; [checkoutRequestDictionary setValue:[checkoutRequest.amount stringValue] forKey:kAmountKey]; [checkoutRequestDictionary setValue:checkoutRequest.cartId forKey:kCartIdKey]; [checkoutRequestDictionary setValue:checkoutRequest.currency forKey:kCurrencyKey]; [checkoutRequestDictionary setValue:configuration.locale.localeIdentifier forKey:kLocaleKey]; [checkoutRequestDictionary setValue:configuration.checkoutId forKey:kCheckoutIDKey]; [checkoutRequestDictionary setValue:[MCSCheckoutUrlBuilder nilOrStringForBool:checkoutRequest.suppress3Ds] forKey:kSuppress3Ds]; [checkoutRequestDictionary setValue:[MCSCheckoutUrlBuilder nilOrStringForBool:checkoutRequest.cvc2Support] forKey:kCVC2SupportKey]; [checkoutRequestDictionary setValue:[MCSCheckoutUrlBuilder nilOrStringForNumber:checkoutRequest.validityPeriodMinutes] forKey:kValidityPeriodMinutesKey]; [checkoutRequestDictionary setValue:checkoutRequest.unpredictableNumber forKey:kUnpredictableNumberKey]; [checkoutRequestDictionary setValue:checkoutRequest.shippingLocationProfile forKey:kShippingLocationProfileKey]; [checkoutRequestDictionary setValue:[configuration.allowedCardTypes.allObjects componentsJoinedByString:@","] forKey:kAllowedCardTypesKey]; [checkoutRequestDictionary setValue:kChannelValue forKey:kChannelKey]; if (checkoutRequest.cryptoOptions != nil) { for (MCSCryptoOptions *option in checkoutRequest.cryptoOptions) { NSString *cryptoFormatKey = [NSString stringWithFormat:@"%@CryptoFormat", option.cardType]; NSString *cryptoFormatValue = [[option.format allObjects] componentsJoinedByString:@","]; [checkoutRequestDictionary setValue:cryptoFormatValue forKey:cryptoFormatKey]; } } // Used for remote logging NSBundle *frameworkBundle = [NSBundle bundleForClass:[self class]]; [checkoutRequestDictionary setValue:frameworkBundle.infoDictionary[@"CFBundleShortVersionString"] forKey:kSdkVersionKey]; [checkoutRequestDictionary setValue:kPlatformValue forKey:kPlatformKey]; return checkoutRequestDictionary; } ``` Using the two components above (configuration and checkout request), the merchant application can build a checkout URL similar the following: https://[SRCI_DOMAIN]/?cartId=123ABC&amount=11.22¤cy=USD&allowedCardTypes=master &locale=en_US&channel=mobile&masterCryptoFormat=UCAF. The example URL above assumes that you have set up the required SRCI experience and hosted it on your own domain (represented by **\[SRCI_DOMAIN\]** ). The **cartId** , **currency** , **allowedCardTypes** , **locale** , **channel** and **masterCryptoFormat** need to be passed to your SRCI implementation (for example as shown via URL parameters) so that these values can be used to first, display the card types accepted in your SRC checkout experience, and second, correctly communicate with the card network DCF system (for example, Mastercard DCF). For example, **channel** as shown above would allow your SRCI code to indicate that the mobile channel is being used when calling the JavaScript SDK. The value **cartId** is shown as an example value that may be important to your implementation; it is not required by Mastercard or the JavaScript SDK (your SRCI web code may communicate with a merchant back end system using such an id, for example). Note: In some cases the SRCI web code may use suitable default values when initializing the JavaScript SDK, rather than requiring them to be passed by the DPA application here - this is a design decision that is up to you. The above is only an example, you could design your URL to require a different set of parameters. You need to ensure that the DPA application is passing sufficient information to enable your web code to create the correct **dpaTransactionOptions** and other configuration data that is required to use the JavaScript SDK (or you will need some other method of communicating these values between the app and your SRCI web code). See the [JavaScript SDK Reference Page](https://developer.mastercard.com/mastercard-checkout-solutions/documentation/sdk-reference/index.md) for details of the data needed to initialize the JavaScript SDK. ### Differentiating Native Application and Web Traffic {#differentiating-native-application-and-web-traffic} If the SRCI implementation requires differentiating native application and web traffic, an additional query parameter (for example, channel=native) can be added when invoking SRCI experience from a native app. Using the additional query parameter, the SRCI can alter its runtime behavior as necessary based on web to web or app to web scenarios. ```javascript var url = new URL(window.location); var params = new URLSearchParams(url.search); if (params.channel === 'native') { // app to web specific logic } ``` ## 2. Create a View Controller {#2-create-a-view-controller} Now we have enough information to initiate a checkout experience. The merchant application can create an Android activity or iOS view controller that handles creating web-views, launching SRCI flows, and handling results from the SRC back-end. The following code samples illustrate the setting up of a view controller or activity that can be used to display the SRCI and DCF web pages inside a web view. The web view for your SRCI experience, **srciWebView**, is created and initialized to point to the URL of your SRCI web experience, and then associated with the native view in the view controller or activity. Later another web-view for the DCF screen is needed, the way to handle this is described in the following section. * Java * Objective-C ```java // Sample CheckoutActivity public class CheckoutActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WebView.setWebContentsDebuggingEnabled(true); WebView srciWebView = new WebView(this); srciWebView.getSettings().setJavaScriptEnabled(true); srciWebView.getSettings().setDomStorageEnabled(true); srciWebView.getSettings().setSupportMultipleWindows(true); srciWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); srciWebView.setWebViewClient(new CustomWebViewClient(activity)); srciWebView.setWebChromeClient(new CustomWebChromeClient(activity)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { CookieManager.getInstance().setAcceptThirdPartyCookies(srciWebView, true); } setContentView(srciWebView); // URL should be loaded after all setup of web clients is done. srciWebView.loadUrl(url); // provide the url of your SRCI experience } } ``` ```objective-c // Sample CheckoutController - (void)viewDidLoad { [super viewDidLoad]; WKPreferences *preferences = [[WKPreferences alloc] init]; preferences.javaScriptCanOpenWindowsAutomatically = true; WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; configuration.preferences = preferences; [configuration setURLSchemeHandler:self forURLScheme:self.scheme]; _srciWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration]; _srciWebView.UIDelegate = self; _srciWebView.navigationDelegate = self; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:_url]; // provide the url of your SRCI experience [_srciWebView loadRequest:request]; [_srciWebView setAllowsBackForwardNavigationGestures:YES]; [self.view setBackgroundColor:[UIColor whiteColor]]; [self.view addSubview:_srciWebView]; [self setConstraintsForView:_srciWebView]; [self.view addSubview:_indicatorView]; } ``` ## 3. Establish Communication Between SRCI and DCF {#3-establish-communication-between-srci-and-dcf} In a web to web scenario the merchant web page can be used as a communication bridge between SRCI and DCF (for example, via postMessage). Under these circumstances, the SRCI and DCF need not both be active at the same time; scripts running within the merchant web page can facilitate communication, maintain state, and orchestrate flow. However, because of the communication limitations between native application code and WebViews, a different communication pattern must be utilized in app to web scenarios. During app to web flow, both the SRCI and DCF should be opened in individual WebViews and communication between the two should be real-time and direct (for example, via postMessage). The web view **srciWebView** created in the previous code samples needs to be able to handle the DCF being invoked. In a web application this would involve a pop-up window, with mobile the view controller or activity needs to handle web views for the SRCI and DCF within the same native view. * For Android, your SRCI WebView requires **WebChromeClient** to handle creation of pop-ups. WebChromeClient provides methods to create a separate WebView that can route to the DCF provider. * For iOS, you should handle this by implementing **WKUIDelegate** and **WKNavigationDelegate**. * Java * Objective-C ```code // Sample WebChromeClient implementation srciWebView.setWebChromeClient(new WebChromeClient() { @Override public boolean onCreateWindow(final WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) { final WebView dcfWebView = new WebView(activity); dcfWebView.getSettings().setJavaScriptEnabled(true); dcfWebView.getSettings().setSupportZoom(true); dcfWebView.getSettings().setBuiltInZoomControls(true); dcfWebView.getSettings().setSupportMultipleWindows(true); dcfWebView.setLayoutParams( new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { CookieManager.getInstance().setAcceptThirdPartyCookies(dcfWebView, true); } view.addView(dcfWebView); WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj; transport.setWebView(dcfWebView); resultMsg.sendToTarget(); // Set DCF webView logic for WebView dcfWebView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // This should be the same shouldOverrideUrlLoading used in the srci WebView return WebCheckoutActivity.this.shouldOverrideUrlLoading(url); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { // This should be the same shouldOverrideUrlLoading used in the srci WebView return shouldOverrideUrlLoading(view, request.getUrl().toString()); } }); // DCF WebChromeClient provides a way to handle all popups using HitTestResult dcfWebView.setWebChromeClient(new WebChromeClient() { @Override public void onCloseWindow(WebView window) { // Remove the DCF view from the Activity's views when closing view.removeView(dcfWebView); } public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) { WebView.HitTestResult result = view.getHitTestResult(); if (result.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE) { //If the user has selected an anchor link, open in browser Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(result.getExtra())); startActivity(browserIntent); return false; } return true; } }); return true; } } ``` ```objective-c // Sample WKUIDelegate, WKNavigationDelegate implementation - (WKWebView *) webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures { _dcfWebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration]; _dcfWebView.UIDelegate = self; _dcfWebView.navigationDelegate = self; _receiveNavigationForDCFPopupCount = 0; [self.view addSubview:_dcfWebView]; [self setConstraintsForView:_dcfWebView]; [self.view addSubview:_indicatorView]; [self.view bringSubviewToFront:_indicatorView]; [_indicatorView show]; [self.view addSubview:_dcfWebView]; [self setConstraintsForView:_dcfWebView]; return _dcfWebView; } - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation { if (_dcfWebView != nil) { _receiveNavigationForDCFPopupCount += 1; if (_receiveNavigationForDCFPopupCount == 2) { [_indicatorView hide]; [_indicatorView removeFromSuperview]; } } else { [_indicatorView hide]; [_indicatorView removeFromSuperview]; } } ``` ### Returning control to the merchant app {#returning-control-to-the-merchant-app} The DCF provider (for example, the Mastercard DCF) notifies a successful checkout or a user-cancelled action, which you need to handle. For this to work you need to define a suitable URL scheme for links to the application so that control can return to the application. * Java * Objective-C ```java // Sample shouldOverrideUrlLoading() implementation on WebViewClient. // The intent scheme should be defined in the merchant application AndroidManifest.xml // to receive intent from SRCI. @Override private boolean shouldOverrideUrlLoading(String url) { String urlScheme = URI.create(url).getScheme(); Log.d(TAG, "Navigating to: " + url); if (urlScheme.equals(INTENT_SCHEME)) { handleIntent(url); return true; } else { return false; } } private void handleIntent(String intentUriString) { try { Intent intent = Intent.parseUri(intentUriString, Intent.URI_INTENT_SCHEME); String intentApplicationPackage = intent.getPackage(); String currentApplicationPackage = getApplication().getApplicationInfo().packageName; Uri intentUri = Uri.parse(intentUriString); String transactionId = intentUri.getQueryParameter(QUERY_PARAM_TRANSACTION_ID); String status = intentUri.getQueryParameter(QUERY_PARAM_STATUS); if (STATUS_CANCEL.equals(status)) { finish(); } else if (intentApplicationPackage != null && intentApplicationPackage.equals(currentApplicationPackage)) { intent.putExtra(COMMERCE_TRANSACTION_ID, transactionId); intent.putExtra(COMMERCE_STATUS, status); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } else { throw new IllegalStateException( "The Intent is not valid for this application: " + intentUriString); } } catch (URISyntaxException e) { Log.e(TAG, "Unable to parse Intent URI. You must provide a valid Intent URI or checkout will not work.", e); throw new IllegalStateException(e); } } ``` ```objective-c // Sample webView:decidePolicyForNavigationAction:decisionHandler - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { if (navigationAction.navigationType == WKNavigationTypeLinkActivated) { NSURL *url = navigationAction.request.URL; [UIApplication.sharedApplication openURL:url options:@{} completionHandler:nil]; decisionHandler(WKNavigationActionPolicyCancel); } else { decisionHandler(WKNavigationActionPolicyAllow); } } - (void)webView:(nonnull WKWebView *)webView startURLSchemeTask:(nonnull id)urlSchemeTask { NSURL *callbackUrl = urlSchemeTask.request.URL; NSURLComponents *urlComponents = [[NSURLComponents alloc] initWithURL:callbackUrl resolvingAgainstBaseURL:YES]; MCSCheckoutResponse *checkoutResponse = [[MCSCheckoutResponse alloc] init]; NSURLResponse *urlResponse = [[NSURLResponse alloc] init]; [urlSchemeTask didReceiveResponse:urlResponse]; [urlSchemeTask didFinish]; for (NSURLQueryItem *item in [urlComponents queryItems]) { if ([item.name isEqualToString:@"oauth_token"]) { checkoutResponse.transactionId = item.value; } else if ([item.name isEqualToString:@"mpstatus"]) { checkoutResponse.status = item.value; } } [self dismiss]; [_delegate checkoutCompletedWithResponse:checkoutResponse]; } - (WKWebView *) webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures { _dcfWebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration]; _dcfWebView.UIDelegate = self; _dcfWebView.navigationDelegate = self; _receiveNavigationForDCFPopupCount = 0; [self.view addSubview:_dcfWebView]; [self setConstraintsForView:_dcfWebView]; [self.view addSubview:_indicatorView]; [self.view bringSubviewToFront:_indicatorView]; [_indicatorView show]; [self.view addSubview:_dcfWebView]; [self setConstraintsForView:_dcfWebView]; return _dcfWebView; } ``` #### Defining a suitable URL scheme {#defining-a-suitable-url-scheme} The above code samples rely on a suitable URL scheme being defined such that when the checkout experience is complete, a redirect to the native application can be made successfully. The following details show how this may be done for Android and iOS. ##### Android - Sample AndroidManifest.xml on Merchant application (DPA) {#android---sample-androidmanifestxml-on-merchant-application-dpa} If the url parameter passed to `shouldOverrideUrlLoading()` matches the defined intent scheme, then the checkout experience is complete or cancelled and the result should be returned to Merchant application. The merchant application (DPA) should define an intent-filter to receive the intent message and this should match the callback URL sent by the SRCI. ```xml ``` The example above has CartActivity on Merchant application receiving the intent scheme. The Merchant will define an URI similar to `intent://fancyshop/#Intent;package=com.fancyshop;scheme=fancyshop;end` The intent can be configured to return transactionID or similar information to confirm successful checkout. This can be used by the merchant application (DPA) to process payment data and authorize the transaction. ##### iOS - Sample Merchant application plist configuration {#ios---sample-merchant-application-plist-configuration} For an iOS merchant application (DPA), the scheme can be configured on the project preferences. The callbackUrl from the SRCI should return the same URI scheme similar to `fancyshop://` ![](https://static.developer.mastercard.com/content/mastercard-checkout-solutions/documentation/images/mobile_xcode_iOS_plist_config.png) ## Building for Native Mobile Applications {#building-for-native-mobile-applications} If you are building a native mobile application, you can still use the JavaScript SDK and build your user experience as a web page that you can then display within the mobile app via a WebView. Note that to do so there are some issues to do with how to pass control between the windows within the WebView -- we provide some suggestions about how to handle this in the [Mobile Integration](https://developer.mastercard.com/mastercard-checkout-solutions/documentation/tutorials-and-guides/mobile-tutorial/index.md) section. Mastercard supports the following web frameworks: | OS / Browser | Version | |-----------------------------------|-----------------------------------------------------------------------------------------------------------------------| | ChromeTab | v63+ **Requires additional Merchant Integration to launch in ChromeTab** | | Android Webview | v68+ **Requires additional Merchant Integration to launch in WebView** | | Safari (In-App) - Webview | v11+ **Requires additional Merchant Integration to launch in Safari WebView** | | SafariViewController | v11+ **Requires additional Merchant Integration to launch in Safari ViewController** | | Safari AsWebAuthenticationSession | v11+ **Note: WebAuthenticationSession is a launch mechanism to launch the checkout experience on the Safari browser** | ### Building screens for Click to Pay {#building-screens-for-click-to-pay} To provide your consumers with Click to Pay Checkout experience, you must create the following screens: * Consumer Identity Entry * Consumer Assurance * SRC Candidate List * Payment Method and Cardholder Information Confirmation Refer to [EMV Secure Remote Commerce User Interface Guidelines and Requirements PDF](https://3ds-ux-guidelines.emvco.com/), which provides reference examples of how screens can be built using SRC elements and components.