Info
Content

[ReactNative] 1. consentmanager SDK Integration

CMP SDK is a React Native library that facilitates the management of user consent for data processing and storage. It is designed to help developers comply with various data protection regulations.

Installation

npm install cmp-sdk-react-native-v3

Getting Started

Linking (React Native 0.59 and below)

If you are using React Native 0.59 or below, you need to link the native modules manually:

Usage

Import the Consentmanager from the cmp-sdk package in your code:

import { Consentmanager } from 'cmp-sdk';

Initializing the SDK

You can initialize the CMP SDK using either the direct configuration or a config object:

  const initializeConsent = async () => {
    try {
      await CmSdkReactNativeV3.setUrlConfig({
        id: '09cb5dca91e6b',
        domain: 'delivery.consentmanager.net',
        language: 'EN',
        appName: 'CMDemoAppReactNative',
      });

      await CmSdkReactNativeV3.setWebViewConfig({
        position: 'fullScreen',
        backgroundStyle: { type: 'dimmed', color: 'black', opacity: 0.5 },
        cornerRadius: 5,
        respectsSafeArea: true,
        allowsOrientationChanges: true,
      });

      await CmSdkReactNativeV3.checkWithServerAndOpenIfNecessary();
      console.log('CMPManager initialized and open consent layer opened if necessary');
    } catch (error) {
      console.error('Error initializing consent:', error);
    } finally {
      setIsLoading(false);
    }
  };

To manage the consent layer:

Consentmanager.openConsentlayer();

Event Handling

Add event listeners to handle various consent-related events:

const removeListeners = Consentmanager.addEventListeners({
  onOpen: () => console.log('Consent layer opened'),
  onClose: () => console.log('Consent layer closed'),
  // Add other event handlers as needed
});

Remember to remove the event listeners when they are no longer needed:

removeListeners();

You can check for vendor and purpose consents:

Consentmanager.hasVendor('vendorID').then((hasConsent) => {
  console.log('Has vendor consent: ', hasConsent);
});

Check Purpose Consent:

Consentmanager.hasPurpose('purposeID').then((hasConsent) => {
  console.log('Has purpose consent: ', hasConsent);
});
Consentmanager.reset();
Consentmanager.exportCmpString().then((cmpString) => {
  console.log('CMP String: ', cmpString);
});

Additional Methods

The CMP SDK provides various methods to retrieve or manage consent data, such as:

  • getAllVendors()
  • getAllPurposes()
  • getEnabledVendors()
  • getEnabledPurposes()
  • getDisabledVendors()
  • getDisabledPurposes()
  • getUSPrivacyString()
  • getGoogleACString()

Refer to the SDK documentation for detailed information on these methods.

On this document, you'll find general information on how to integrate our SDK to your project. For further details, please refer to our API Reference documentation. 

1. Installation

consentmanager SDK is a comprehensive solution for managing user consent in mobile applications. Designed to handle GDPR compliance, user privacy preferences, and ad tracking transparency, this SDK provides a seamless integration for iOS and Android platforms. Additionally, it offers wrapper plugins/bridges for React Native, Flutter, and Unity, making it versatile across various development environments.

Steps - High Level Description

  1. Integration and Configuration:

    • Integrate the SDK into your app.
    • Configure the SDK settings according to your needs.
  2. Creating an Instance and displaying the Consent Layer:

    • On app startup, create an instance of the CMPManager class. This instance will handle the consent process.
    • The SDK will automatically display the consent screen if needed.
  3. Processing user's consent data:

    • Once consents are collected, info is stored and is available for querying through different properties and methods exposed by our SDK. You'll have information about rejected or accepted consents, vendors and purposes.

1.1 Integration and Configuration

NPM

Run this line on your terminal:

npm install cmp-sdk-react-native-v3

Linking (React Native 0.59 and below)

If you are using React Native 0.59 or below, you need to link the native modules manually:

1.2 Creating an instance and displaying consent layer

Within your code, you must create an instance of class CMPManager. You'll need to set up two objects that will be passed to the getInstance method: UrlConfig, which handles your CMP configuration, like Code-ID and default language, and ConsentLayerUIConfig. which will configure the looks of the WebView that will display the consent layer. After that, you're ready to use the method checkWithServerAndOpenIfNecessary() to automatically fetch the necessary data from our server and determine if the consent screen needs to be shown or not. If so, the SDK will automatically show the consent screen at this point, via a WebView created by our SDK, which will display the consent layer with the text and buttons according to your CMP configurations (chosen via the Code-ID of your CMP), collect the data and persist the consent information in the NSUserDefaults/UserPreferences area of the device, so the app can display the targeted ads accordingly. 

Example:

const HomeScreen: React.FC = () => {
  const [isLoading, setIsLoading] = useState(true);
  const [toastMessage, setToastMessage] = useState<string | null>(null);

  useEffect(() => {
    initializeConsent();
  }, []);

  const initializeConsent = async () => {
    try {
      await CmSdkReactNativeV3.setUrlConfig({
        id: '09cb5dca91e6b',
        domain: 'delivery.consentmanager.net',
        language: 'EN',
        appName: 'CMDemoAppReactNative',
      });

      await CmSdkReactNativeV3.setWebViewConfig({
        position: 'fullScreen',
        backgroundStyle: { type: 'dimmed', color: 'black', opacity: 0.5 },
        cornerRadius: 5,
        respectsSafeArea: true,
        allowsOrientationChanges: true,
      });

      await CmSdkReactNativeV3.checkWithServerAndOpenIfNecessary();
      console.log('CMPManager initialized and open consent layer opened if necessary');
    } catch (error) {
      console.error('Error initializing consent:', error);
    } finally {
      setIsLoading(false);
    }
  };

1.3 Processing users' consent data

Checking users's consents

Our SDK offer different methods to check and retrieve consent information. The main methods are displayed in the example below:

// On the example below retrieved from our Demo App, we have some examples 
// of how to check consents from the user, either accepted or rejected. 

// Helper function
const handleApiCall = async (
  apiCall: () => Promise<any>,
  successMessage: (result: any) => string,
  errorMessage: string = 'An error occurred'
) => {
  try {
    const result = await apiCall();
    showToast(successMessage(result));
  } catch (error) {
    showToast(`${errorMessage}: ${error}`);
  }
};

const buttons = [
  {
    title: 'Has User Choice?',
    onPress: () => handleApiCall(
      CmSdkReactNativeV3.hasUserChoice,
      (result) => `Has User Choice: ${result}`
    ),
  },
  {
    title: 'Has Purpose ID c53?',
    onPress: () => handleApiCall(
      () => CmSdkReactNativeV3.hasPurposeConsent('c53'),
      (result) => `Has Purpose: ${result}`
    ),
  },
  {
    title: 'Has Vendor ID s2789?',
    onPress: () => handleApiCall(
      () => CmSdkReactNativeV3.hasVendorConsent('s2789'),
      (result) => `Has Vendor: ${result}`
    ),
  },
]

For further information about the other methods, pleae refer to our full API Documentation

Reopening the Consent Layer to check the users' choices

In order to allow the user to verify or change their choices, you can simply call openConsentLayer()

CmSdkReactNativeV3.openConsentLayer

This method will display the consent layer via the same WebView instance created in the previous steps. 

In some cases an native app might contain webviews in order to display information, like advertising or content. In order to transmit the consent information from the SDK to the webview, you can retrieve the consent string using:

CmSdkReactNativeV3.exportCMPInfo

This will export the consent information and all further data that is needed by the CMP. You can then pass this information to the CMP that is in your webview by adding it to the URL that is called in the webview.

If, otherwise, you need to import the consent string using the SDK, you can use the example below:

() => CmSdkReactNativeV3.importCMPInfo(
          'Q1FERkg3QVFERkg3QUFmR01CSVRCQkVnQUFBQUFBQUFBQWlnQUFBQUFBQUEjXzUxXzUyXzUzXzU0XzU1XzU2XyNfczI3ODlfczI3OTBfczI3OTFfczI2OTdfczk3MV9VXyMxLS0tIw'
      )

Integration with Apple Tracking Transparency (ATT)

In case you are using tracking or analytics in your app, we recommend to read the guide on ATT implementation here.

Creating a custom layout

To create a customized view of the WKWebView, like changing its positioning or background, for example, you can change the configuration passed to the ConsentLayerUIConfig object like below:

ConsentLayerUIConfig(
    position: .halfScreenTop,
    backgroundStyle: .dimmed(.grey, 0.75),
    cornerRadius: 20,
    respectsSafeArea: false,
    allowsOrientationChanges: true)

Logging

When using our iOS SDK, you may find the need to debug or analyze log information for various purposes. The logs generated by our SDK are tagged under "CMP", allowing you to easily filter and view only the relevant logs. For further information, please refer to this section of our documentation.

 

Back to top