React Native SDK

This is a step-by-step guide to include Conscent.ai package in your app. This package is developed in TypeScript and JavaScript.

Installation

npm install csc-react-native-sdk
run pod install
Initialize SDK

In your App.js file include the ConscentWebView component in Stack.Navigator

//PACKAGES
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import AsyncStorage from '@react-native-async-storage/async-storage';

import { ConscentWebView, StorageKeys, conscentLogger } from 'csc-react-native-sdk';

export default function App() {

    AsyncStorage.setItem(StorageKeys.ClientId, '661907c2487ae1aba956dcc4')
    AsyncStorage.setItem(StorageKeys.ApiEnv, 'SANDBOX')

    // Configure the logger
    conscentLogger.configure({
        enableLog: true,
        enableAllLog: true,
        enableError: true,
        enableWarn: true, // Disable warnings
        logEnvironment: 'development',
    });

    return (
        <NavigationContainer>
        <Stack.Navigator initialRouteName="your_initial_route">
            ...
            <Stack.Screen 
                name="ConscentWebView" 
                component={ConscentWebView}
                options={{
                    headerShown: false
                }} />
        </Stack.Navigator>
        </NavigationContainer>

    );
};
PARAMETERS
DISCRIPTION

yourClientId

Pass your clientId received from Conscent.ai

yourContentId

Unique id of each content

scroll-Y

Pass the scroll depth of your content screen

userAgent

Pass userAgent of your device

ApiEnv

ApiEnv can be set as :

SANDBOX

LIVE

Initialize the paywall

Define these states on the content screen

const paywallRef = useRef(null);
const [scrollY, setScrollY] = useState(0);
const [showContent, setShowContent] = useState(false);

Call the Paywall on top of your content screen

//PACKAGES
import {
    pageExist,
    getEventsEnvDetails,
    PopUp,
    PayWall,
} from 'csc-react-native-sdk';
import { EventRegister } from 'react-native-event-listeners';

// Content Screen
const userAgent = await DeviceInfo.getUserAgent();

useFocusEffect(
        React.useCallback(() => {
            const CONSCENT_MESSAGE_LISTENER = EventRegister.addEventListener(
                "CONSCENT_MESSAGE",
                (data) => {
                    console.log('CONSCENT_MESSAGE', data);
                }
            );
            const CONSCENT_SUCCESS_LISTENER = EventRegister.addEventListener(
                "CONSCENT_SUCCESS",
                (data) => {
                    if (data?.message === 'UNLOCK') {
                        setShowContent(true);
                    }
                    console.log('CONSCENT_SUCCESS', data);
                }
            );
            const CONSCENT_FAILURE_LISTENER = EventRegister.addEventListener(
                "CONSCENT_FAILURE",
                (data) => {
                    console.warn('CONSCENT_FAILURE', data);
                }
            );
            return () => {
                removePage();
                if (typeof CONSCENT_MESSAGE_LISTENER === 'string') {
                    EventRegister.removeEventListener(CONSCENT_MESSAGE_LISTENER);
                }
                if (typeof CONSCENT_SUCCESS_LISTENER === 'string') {
                    EventRegister.removeEventListener(CONSCENT_SUCCESS_LISTENER);
                }
                if (typeof CONSCENT_FAILURE_LISTENER === 'string') {
                    EventRegister.removeEventListener(CONSCENT_FAILURE_LISTENER);
                }
            };
        }, [])
    );

async function removePage() {
        await pageExist(
            getEventsEnvDetails('SANDBOX'),
            clientId,
            contentId,
            scrollY
        );
    }

const goBack = () => {
    // Go back to the previous screen
    props?.navigation.goBack();
}

return (
        <SafeAreaView style={styles.container}>
            <ScrollView
                onScroll={(e) => {
                    setScrollY(e.nativeEvent.contentOffset.y)
                }}>
                <Text>{'showContent your locked content'}</Text>
                <View>
                    <PayWall
                        ref={paywallRef}
                        clientId={clientId}
                        contentId={contentId}
                        title={contentTitle}
                        contentUrl={'url'}
                        authorName={'name'}
                        publicationDate={'2024-07-17T11:57:27.312Z'}
                        categories={['category1', 'category2']}
                        tags={['free', 'premium', 'metered']}
                        sections={['section1', 'section2', 'section3']}
                        apiEnv={mode}
                        fontFamily={'PlayfairDisplay-Regular'}
                        userAgent={
                            'Mozilla/5.0 (iPhone; CPU iPhone OS 17_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148'
                        }
                        currentStackName={'Content'}
                        navigation={props?.navigation}
                        scrollY={scrollY}
                        goBack={() => {
                            goBack();
                        }}
                    />
                </View>
                {
                    showContent ? <><Text>{'showContent your full content'}</Text></> :
                        <><Text>{'showContent your locked content'}</Text></>
                }
            </ScrollView>
                

            <View>
                <MeterBanner
                    ref={paywallRef}
                    clientId={clientId}
                    contentId={contentId}
                    title={contentTitle}
                    contentUrl={'url'}
                    authorName={'name'}
                    publicationDate={'2024-07-17T11:57:27.312Z'}
                    categories={['category1', 'category2']}
                    tags={['free', 'premium', 'metered']}
                    sections={['section1', 'section2', 'section3']}
                    apiEnv={mode}
                    fontFamily={'PlayfairDisplay-Regular'}
                    userAgent={
                        'Mozilla/5.0 (iPhone; CPU iPhone OS 17_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148'
                    }
                    currentStackName={'Content'}
                    navigation={props?.navigation}
                    scrollY={scrollY}
                    goBack={() => {
                        goBack();
                    }}
                />
            </View>
                <PopUp
                    apiEnv={'SANDBOX'}
                    currentStackName={'Your_current_stack_name'}
                    navigation={props?.navigation}
                    scrollY={scrollY}
                />

        </SafeAreaView >
    )

call removePage() in useFocusEffect

EventListeners for Paywall, Login, Logout and userProfile

Implement the EventRegister method in your component:

  • USER_NOT_LOGIN: Triggered when the user is not logged in.

  • LOGIN_SUCCESS: Triggered when the user successfully logs in to the Conscent system.

  • LOGIN_FAILED: Triggered when the user’s login attempt fails in the Conscent system.

  • LOGOUT_SUCCESS: Triggered when the user logs out successfully.

  • LOGOUT_FAILED: Triggered when the user’s logout attempt fails.

  • USER_DELETE_ACCOUNT_SUCCESS: Triggered when the user’s user deletes the account.

  • PAYWALL_VIEW: Locks the content and displays the paywall.

  • UNLOCK: Unlocks the content and hides the paywall.

  • JOURNEY_FAILURE: Handles errors while displaying the paywall.

  • SUBS_SUCCESS: Handles successful subscription.

  • PAYMENT_SUCCESS: Handles successful subscription payment.

  • RZP_CROSS_BTN_CLICKED: Triggered when the Razorpay cross button is clicked.

  • USER_GO_BACK: Triggered when the user navigates back from ConscentWebView.

  • onPurchaseStarted: Triggered when the user starts purchase

  • onPurchaseCompleted: Triggered when the user Purchase Completed and sends Purchase Success Response.

  • onPurchaseError: Triggered when the user's fails to Purchase

  • onPurchaseCancelled: Triggered when the user's Cancelled Purchase

  • onDismiss: Triggered when the user's Dismiss Purchase

  • USER_PROFILE_UPDATE : Triggered when the user updates the profile.

useEffect(() => {
    const CONSCENT_MESSAGE_LISTENER = EventRegister.addEventListener(
      "CONSCENT_MESSAGE",
      (data) => {
        console.log('CONSCENT_MESSAGE', data);
      }
    );
    const CONSCENT_SUCCESS_LISTENER = EventRegister.addEventListener(
      "CONSCENT_SUCCESS",
      (data) => {
        console.log('CONSCENT_SUCCESS', data);
      }
    );
    const CONSCENT_FAILURE_LISTENER = EventRegister.addEventListener(
      "CONSCENT_FAILURE",
      (data) => {
        console.warn('CONSCENT_FAILURE', data);
      }
    );
    return () => {
      if (typeof CONSCENT_MESSAGE_LISTENER === 'string') {
        EventRegister.removeEventListener(CONSCENT_MESSAGE_LISTENER);
      }
      if (typeof CONSCENT_SUCCESS_LISTENER === 'string') {
        EventRegister.removeEventListener(CONSCENT_SUCCESS_LISTENER);
      }
      if (typeof CONSCENT_FAILURE_LISTENER === 'string') {
        EventRegister.removeEventListener(CONSCENT_FAILURE_LISTENER);
      }
    };
  });

Login/Logout Functionality

The client can use the ConsCent Login, Logout System using this functionality:

await login('Your_current_stack_name', props.navigation)

await logOut('Your_current_stack_name', props?.navigation)

Google Login Process (Android)

Share the Google ClientID

Google Login Process (iOS)

Share the Google ClientID

  1. To use Google login functionality you need to install pod in your project.

run pod install
  1. Add your OAuth client ID and custom URL scheme

Update your app's Info.plist file to add your OAuth client ID and a custom URL scheme based on the reversed client ID.

The reversed client ID is your client ID with the order of the dot-delimited fields reversed. This is also shown under "iOS URL scheme" when selecting an existing iOS OAuth client in the Cloud console. For example: com.googleusercontent.apps.1234567890-abcdefg

<key>GIDClientID</key>
<string>YOUR_IOS_CLIENT_ID</string>
<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>YOUR_DOT_REVERSED_IOS_CLIENT_ID</string>
    </array>
  </dict>
</array>

Facebook Login
  1. Install the library

using either Yarn:

yarn add react-native-fbsdk-next

or npm:

npm install --save react-native-fbsdk-next
  1. Link

React Native 0.60+

CLI autolink feature links the module while building the app.

Note For iOS using cocoapods, run:

$ cd ios/ && pod install

React Native <= 0.59

Note: For support with React Native <= 0.59, please refer to React Native FBSDK

If you can't or don't want to use the CLI tool, you can also manually link the library using the instructions below (click on the arrow to show them):

Manually link the library on iOS:

Either follow the instructions in the React Native documentation to manually link the framework or link using Cocoapods by adding this to your Podfile:

pod 'react-native-fbsdk-next', :path => '../node_modules/react-native-fbsdk-next'

Manually link the library on Android

Make the following changes:

android/settings.gradle

include ':react-native-fbsdk-next' 
project(':react-native-fbsdk-next').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fbsdk-next/android') 

android/app/build.gradle

dependencies { ... 
implementation project(':react-native-fbsdk-next') } 

android/app/src/main/.../MainApplication.java

On top, where imports are:

import com.facebook.reactnative.androidsdk.FBSDKPackage; 

Add the FBSDKPackage class to your list of exported packages.

@Override 
protected List getPackages() 
{ return Arrays.asList( 
new MainReactPackage(), 
new FBSDKPackage() ); 
}
  1. Configure projects 3.1 Android Before you can run the project, follow the Getting Started Guide for Facebook Android SDK to set up a Facebook app. You can skip the build.gradle changes since that's taken care of by the rnpm link step above, but make sure you follow the rest of the steps such as updating strings.xml and AndroidManifest.xml. In addition, keep in mind that you have to point the Key Hash generation command at your app's debug.keystore file. You can find its location by checking storeFile in one of the build.gradle files (its default path is android/app/build.gradle however this can vary from project to project). 3.2 iOS Follow steps 2, 3 and 4 in the Getting Started Guide for Facebook SDK for iOS. Note: The above link (Step 3 and 4) contains Swift code instead of Objective-C which is inconvenient since react-native ecosystem still relies on Objective-C. To make it work in Objective-C you need to do the following in /ios/PROJECT/AppDelegate.m: Step 1: Add

#import <AuthenticationServices/AuthenticationServices.h>
#import <SafariServices/SafariServices.h>
#import <FBSDKCoreKit/FBSDKCoreKit-Swift.h>

Step 2: Inside didFinishLaunchingWithOptions, add the following:

[[FBSDKApplicationDelegate sharedInstance] application:application 
didFinishLaunchingWithOptions:launchOptions]; 

Step 3: After this step, if you run into this build issue: Undefined symbols for architecture x86_64:, then you need to create a new file File.swift on your project folder. After doing this, you will get a prompt from Xcode asking if you would like to create a Bridging Header. Click accept.

Step 4: From the facebook-ios-sdk docs steps 1-3, but in Objective-C since they have moved to Swift for their examples - make something like the following code is in AppDelegate.m:

- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
  return [[FBSDKApplicationDelegate sharedInstance]application:app
                                                      openURL:url
                                                      options:options];
}

Without this code login might not work if Facebook app is installed, see thebergamo/react-native-fbsdk-next#59 (comment) - if you are also using react-native deep-linking you may need have multiple entries in this openURL method, as detailed in the next section

If you're not using cocoapods already you can also follow step 1.1 to set it up.

If you're using React Native's RCTLinkingManager

The AppDelegate.m file can only have one method for openUrl. If you're also using RCTLinkingManager to handle deep links, you should handle both results in your openUrl method.

#import <AuthenticationServices/AuthenticationServices.h> // <- Add This Import
#import <SafariServices/SafariServices.h> // <- Add This Import
#import <FBSDKCoreKit/FBSDKCoreKit-Swift.h> // <- Add This Import
#import <React/RCTLinkingManager.h> // <- Add This Import

- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
  if ([[FBSDKApplicationDelegate sharedInstance] application:app openURL:url options:options]) {
    return YES;
  }

  if ([RCTLinkingManager application:app openURL:url options:options]) {
    return YES;
  }

  return NO;
}

NOTE: Always ensure that the RCTLinkingManager condition is added as the last condition in your deep linking logic. If placed before FBSDKApplicationDelegate condition, it will intercept the Facebook SSO link, treating it as a standard deep link. This misconfiguration will break the Facebook Single Sign-On (SSO) functionality, leading to unexpected behavior in your app. Proper ordering is critical for seamless SSO integration..

Troubleshooting:

  1. You cannot run the Android project.

    • Make sure you added the code snippet in step 3.1.

    • Make sure you set up a Facebook app and updated the AndroidManifest.xml and res/values/strings.xml with Facebook app settings.

  2. You get duplicate symbol errors.

    • Make sure that FBSDK[Core, Login, Share]Kit.framework are not in Link Binary with Libraries for your root project when using CocoaPods.

  3. You get this build error: no type or protocol named UIApplicationOpenURLOptionsKey.

    • Your Xcode version is too old. Upgrade to Xcode 10.0+.

  4. You get a compilation error with the error Undefined symbols for architecture x86_64.

Undefined symbols for architecture x86_64:
    "_swift_FORCE_LOAD$_swiftUniformTypeIdentifiers", referenced from:
    _swift_FORCE_LOAD$swiftUniformTypeIdentifiers$_FBSDKShareKit in libFBSDKShareKit.a(Enums+Extensions.o)
    (maybe you meant: _swift_FORCE_LOAD$swiftUniformTypeIdentifiers$_FBSDKShareKit)
    "_swift_FORCE_LOAD$_swiftCoreMIDI", referenced from:
    _swift_FORCE_LOAD$swiftCoreMIDI$_FBSDKShareKit in libFBSDKShareKit.a(Enums+Extensions.o)
    (maybe you meant: _swift_FORCE_LOAD$swiftCoreMIDI$_FBSDKShareKit)
    "_swift_FORCE_LOAD$_swiftWebKit", referenced from:
    _swift_FORCE_LOAD$swiftWebKit$_FBSDKCoreKit in libFBSDKCoreKit.a(AccessToken.o)
    _swift_FORCE_LOAD$swiftWebKit$_FBSDKCoreKit in libFBSDKCoreKit.a(Permission.o)
    _swift_FORCE_LOAD$swiftWebKit$_FBSDKCoreKit in libFBSDKCoreKit.a(Settings.o)
    _swift_FORCE_LOAD$swiftWebKit$_FBSDKLoginKit in libFBSDKLoginKit.a(FBLoginButton.o)
    _swift_FORCE_LOAD$swiftWebKit$_FBSDKLoginKit in libFBSDKLoginKit.a(LoginManager.o)
    _swift_FORCE_LOAD$swiftWebKit$_FBSDKShareKit in libFBSDKShareKit.a(Enums+Extensions.o)
    (maybe you meant: _swift_FORCE_LOAD$swiftWebKit$_FBSDKLoginKit, _swift_FORCE_LOAD$swiftWebKit$_FBSDKShareKit , _swift_FORCE_LOAD$swiftWebKit$_FBSDKCoreKit )
    ld: symbol(s) not found for architecture x86_64

After facebook-ios-sdk v7 (written with Swift parts) you need to coordinate Swift language usage with Objective-C for iOS.

Either:

  • add a new file named File.Swift in the main project folder and answer "yes" when Xcode asks you if you want to "Create Bridging Header" The empty swift file makes this change to the Header Search Path on your build settings:

$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)
$(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME)

or add this stanza in the postinstall section of your Podfile as a possible workaround (then pod deintegrate && pod install):

  # Mixing Swift and Objective-C in a react-native project may be problematic.
  # Workaround:  https://github.com/facebookarchive/react-native-fbsdk/issues/755#issuecomment-787488994
  installer.aggregate_targets.first.user_project.native_targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['LIBRARY_SEARCH_PATHS'] = ['$(inherited)', '$(SDKROOT)/usr/lib/swift']
    end
  end

Both result in fixing search paths.

  1. AppLink.fetchDeferredAppLink does not work (on iOS at least).

Both the Facebook App and your app have to have App Tracking Transparency (ATT) permission granted for facebook deferred app links to work. See this related issue

  1. You get an exception App ID not found. Add a string value with your app ID for the key FacebookAppID to the Info.plist or call [FBSDKSettings setAppID:].

If you find yourself in this situation, and you are certain that you have the FacebookAppID in your Info.plist or that you have called setAppId, you may be able to fix it by adding the following lines to AppDelegate.m inside the - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions, just before the return YES statement:

  [[FBSDKApplicationDelegate sharedInstance] application:application
  didFinishLaunchingWithOptions:launchOptions];
  1. You don't see any events in the Facebook Events Manager

    For it to work you need to:

    • Run the app on a real device

    • Have the facebook app running in the background and logged in to an account

    • Have that account you used on Facebook added as an "Advertising Account" for your app on Facebook's dashboard

    • Most important: Have ATT enabled on both the Facebook app and your app.

    This will make it so events you log on your app by you – which I guess they determine by seeing who is logged in on the Facebook App – are the ones to show up on the Event manager.

  2. You get “There is an error in logging you into this application” when attempting to log in via the native Facebook app on Android.

    This typically means the appropriate signing certificate hash hasn’t been saved to your Facebook app.

    You can follow the instructions here to generate and save the hash from your signing certificate.

    Note: If Google is signing your releases, you’ll need to get the SHA-1 from the Release > App signing > App signing key certificate in the Play Console and run this command:

echo YOUR_SHA1_HERE | xxd -r -p | openssl base64

If you’re also using App Tester for internal releases, you’ll need to run the same command for the SHA-1 from Release > Internal app sharing > Internal test certificate and save that hash as well.

Once you have your hashes, return here and enter them under Key Hashes.

  1. You are forced to use the limited option when trying to login in iOS. Although, the official documentation has nothing to say about this issue, the permission App Tracking Transparency is required to use the non-limited/default login in iOS devices (NOTE: it works fine in android without the permission). Ask for this permission and if the user allows it, the default facebook login page will open. If this permission is disabled, then the limited version of login will be opened which makes the Graph API endpoints unusable.

Note: If the above configurations does not work for Android then here are the steps that you need to follow:

In android/app/build.gradle

implementation 'com.facebook.android:facebook-login:17.0.2'

In android/app/src/main/java/com/csc_demo/MainApplication.kt

import android.app.Application
import com.facebook.FacebookSdk

class MainApplication : Application(), ReactApplication {
    override fun onCreate() {
        super.onCreate()
        

        FacebookSdk.setClientToken("e7081219432d2049c5189d64b19cae93");
        FacebookSdk.sdkInitialize(applicationContext)
    }
}

In android/app/src/main/AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      >
      <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
        android:launchMode="singleTask"
        android:windowSoftInputMode="adjustResize"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>
</manifest>

android/app/src/main/res/values/strings.xml

<resources>
    <string name="app_name">csc_demo</string>
    <string name="facebook_app_id">451670000858184</string>
</resources>

android/build.gradle

facebookSdkVersion = "13.1.0"

To enable Apple login follow these steps:

Xcode Steps:

  1. Open Xcode project.

  2. Go to Target Settings → Signing & Capabilities.

  3. Add "Sign in with Apple" capability.

  4. Verify entitlements.

  5. Ensure proper signing.

App Store Connect Steps:

  1. Select the app under "My Apps."

  2. Go to "App Information."

  3. Add "Sign in with Apple" information (privacy policy and terms of service URLs).

  4. Enable "Sign in with Apple."

  5. Submit changes for review.

UserProfile Functionality
await openUserProfile('Your_current_stack_name', props.navigation, '')

DEMO APP Link

Last updated