csc-react-native-sdk
v2.2.3
Published
React-native sdk provides paywalling and analytics
Downloads
501
Readme
csc-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
Initialize SDK
In your App.js file include 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>
);
}
Initialize the paywall
- yourClientId : Pass your clientId received from Conscent.ai.
- yourContentId : Unique id of each content
- ApiEnv can be set as :
SANDBOX
LIVE
- scroll-Y : Pass the scroll depth of your content screen
- userAgent : Pass userAgent of your device
- call removePage() in useFocusEffect
Event Listener
implement EventRegister method in your component
- UNLOCK: Unlocks the content and hides the paywall.
- PAYWALL_VIEW: Locks the content and displays the paywall.
- JOURNEY_FAILURE: Handles errors while displaying the paywall.
- USER_GO_BACK: Triggered when the user navigates back from
ConscentWebView
. - USER_PROFILE_UPDATE : Triggered when the user updates the profile.
- LOGIN_SUCCESS: Triggered when the user successfully logs in to Conscent system
- LOGIN_FAILED: Triggered when the user logout successfully into the Conscent system
- USER_DELETE_ACCOUNT_SUCCESS: Triggered when the user’s user deletes the account.
- LOGOUT_SUCCESS: Triggered when the user logs out successfully
- LOGOUT_FAILED: Triggered when the user logs out failed.
- USER_NOT_LOGIN: Triggered when the user is not logged in.
- SUBS_SUCCESS: Handles successful subscription.
- PAYEMENT_SUCCESS: Handles successful subscription payment.
- RZP_CROSS_BTN_CLICKED: Triggered when the Razorpay cross button is clicked.
- 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
Define these states on content screen
const paywallRef = useRef(null);
const [scrollY, setScrollY] = useState(0);
const [showContent, setShowContent] = useState(false);
Call Paywall and Pop-Up 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>
);
ConsCent Event Listener for login, logout, userProfile
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 Functionality
The client can use ConsCent Login, Logout System using this functionality:
await login('Your_current_stack_name', props.navigation);
await logOut('Your_current_stack_name', props?.navigation);
1. Google Login
Google Login Process (Android)
📝 Note: Share the Google ClientID .
Google Login Process (iOS)
📝 Note: Share the Google ClientID .
- To use Google login functionality you need to install pod in your project.
run pod install
- 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>
2. Apple Login
To enable Apple login follow these steps:
Xcode Steps:
- Open Xcode project.
- Go to Target Settings → Signing & Capabilities.
- Add "Sign in with Apple" capability.
- Verify entitlements.
- Ensure proper signing.
App Store Connect Steps:
- Go to App Store Connect.
- Select the app under "My Apps."
- Go to "App Information."
- Add "Sign in with Apple" information (privacy policy and terms of service URLs).
- Enable "Sign in with Apple."
- Submit changes for review.
3. Facebook Login
1. Install the library
using either Yarn:
yarn add react-native-fbsdk-next
or npm:
npm install --save react-native-fbsdk-next
2. 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
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):
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'
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<ReactPackage> getPackages() {
return Arrays.asList(
new MainReactPackage(),
new FBSDKPackage()
);
}
3. 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
:
- Add
#import <AuthenticationServices/AuthenticationServices.h>
#import <SafariServices/SafariServices.h>
#import <FBSDKCoreKit/FBSDKCoreKit-Swift.h>
- Inside
didFinishLaunchingWithOptions
, add the following:[[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
- After this step, if you run into this
build
issue:Undefined symbols for architecture x86_64:
, then you need to create a new fileFile.swift
on your project folder. After doing this, you will get a prompt fromXcode
asking if you would like to create aBridging Header
. Click accept. - 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:
Without this code login might not work if Facebook app is installed, see https://github.com/thebergamo/react-native-fbsdk-next/issues/59#issuecomment-1038149447 - 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- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options { return [[FBSDKApplicationDelegate sharedInstance]application:app openURL:url options:options]; }
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
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
andres/values/strings.xml
with Facebook app settings.
You get duplicate symbol errors.
- Make sure that
FBSDK[Core, Login, Share]Kit.framework
are not inLink Binary with Libraries
for your root project when using CocoaPods.
- Make sure that
You get this build error:
no type or protocol named UIApplicationOpenURLOptionsKey
.- Your Xcode version is too old. Upgrade to Xcode 10.0+.
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.
- add a new file named
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
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 calledsetAppId
, you may be able to fix it by adding the following lines toAppDelegate.m
inside the- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
, just before thereturn YES
statement:[[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
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.
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.
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 permissionApp 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.
User Profile Functionality
The client can use ConsCent User Profile System using this functionality:
await openUserProfile('Your_current_stack_name', props.navigation);
The client can get user details using this functionality:
const userdetails = await getUserDetails();
Demo app Link
Contributing
See the contributing guide to learn how to contribute to the repository and the development workflow.
License
MIT
Made with create-react-native-library