> For the complete documentation index, see [llms.txt](https://docs.conscent.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.conscent.ai/version-1.0/mobile-sdk/react-native-sdk.md).

# React Native SDK

<details>

<summary><strong>Installation</strong></summary>

```javascript
npm install csc-react-native-sdk
```

</details>

<details>

<summary><strong>Initialize SDK</strong></summary>

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

```javascript
import { ConscentWebView } from 'csc-react-native-sdk';

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

  );
};
```

</details>

| 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                                                                               |
| Mode          | <p>Mode can be set as : </p><p><code>STAGING</code></p><p><code>SANDBOX</code> </p><p><code>LIVE</code></p> |

### Initialize the paywall

**Define these states on the content screen**

```javascript
    const [scrollY, setScrollY] = useState(0);
    const paywallRef = useRef(null);
    const [showPaywall, setShowPaywall] = useState(true);
    const [showContent, setShowContent] = useState(false);
    const [mode, setMode] = useState('SANDBOX');
```

**Call the Paywall on top of your content screen**

<pre class="language-javascript"><code class="lang-javascript">import PayWall, { getEventsEnvDetails, pageExist, onTouchListener, PopUp } from 'csc-react-native-sdk';
<strong>
</strong><strong>const userAgent = await DeviceInfo.getUserAgent();
</strong>
useFocusEffect(
        React.useCallback(() => {
            return () => {
                removePage();
            };
        }, [])
);

async function removePage() {
        const res = await pageExist(getEventsEnvDetails(mode), clientId, contentId)
 }

const conscentMessage = async (message) => {
        if (message == 'GoogleLoginClick') {
            googleSignIn();
        }
}

const googleSignIn = async () => {
        try {
            await GoogleSignin.hasPlayServices();
            const userInfo = await GoogleSignin.signIn();

            const email = userInfo.user.email;

            const data = await genrateTempToken(email, mode);
            
            const tempToken = data?.tempAuthToken;
  
            await autoLoginView(tempToken, clientId, email, phoneNumber, currentStackScreenName, props.navigation, mode); // phoneNumber optional(pass empty string)



        } catch (error) {
            console.log('got error: ', error.message);
        }
}

async function onStatusChange(result) {
        if (result?.successMessage == 'METERBANNER') {
            setShowPaywall(true);
            setShowContent(true);
        }
        else if (result?.successMessage == 'PAYWALL') {
            setShowPaywall(true);
            setShowContent(false);
        }
        else if (result?.successMessage == 'UNLOCK') {
            setShowPaywall(false);
            setShowContent(true);
        }
}

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

return (
        &#x3C;SafeAreaView style={styles.container}>
            &#x3C;ScrollView
                onScroll={(e) => {
                    setScrollY(e.nativeEvent.contentOffset.y)

                    // call this method when user do any activity on screen
                    onTouchListener();
                }}>
                {
                    showContent ?
                        &#x3C;Text>{ showContent your full content }&#x3C;/Text> : &#x3C;Text>{ showContent your locked content }&#x3C;/Text>
                }
            &#x3C;/ScrollView>
            {userAgent &#x26;&#x26; showPaywall &#x26;&#x26;
                &#x3C;PayWall
                    ref={paywallRef}
                    clientId={clientId}
                    contentId={contentId}
                    environment={mode}
                    userAgent={userAgent}
                    conscentMessage={conscentMessage}
                    onPaywallStatus={(result) => {
                        onStatusChange(result)
                    }}
                    onErrorMessage={(error) => {
                        console.log('Error', error)
                    }}
                    navigation={props?.navigation}
                    scrollY={scrollY}
                    goBack={() => {
                        goBack()
                    }} />
            }
            &#x3C;PopUp
                environment={mode}
                currentStackName={'Your_current_stack_name'}
                navigation={props?.navigation}
                scrollY={scrollY}
            />

        &#x3C;/SafeAreaView >
    )
</code></pre>

{% hint style="warning" %}
call removePage() in useFocusEffect

call onTouchListener() : when the user does any activity on the screen
{% endhint %}

### Paywall Listener

Implement the onStatusChange method in your component

* METERBANNER: when receiving it then unlock content and show the paywall
* PAYWALL: when receiving it then lock the content and show the paywall
* UNLOCK: when receiving it then unlock the content and don't show the paywall

<details>

<summary>Login Functionality</summary>

The client can use his Login System using this functionality:

Generate token API is a post API that gets email, and phone number as a body parameter and generates an auto login token.

* username: API Key gets from conscent dashboard
* password: API Secret gets from conscent dashboard
* getEnvDetails: call it to get the base URL of conscent api

```javascript
import { getEnvDetails, getLoginChallengeId, getServiceEnvDetails } from 'csc-react-native-sdk';
import base64 from 'react-native-base64'

export const generateTempToken = async (email, mode) => {

    const username = "J1EFAQR-H0N4921-QCXKVNH-6W9ZYY9"; // API Key get from conscent dashboard
    const password = "CFR472795Q42TTQJFV84M37A5G4SJ1EFAQRH0N4921QCXKVNH6W9ZYY9"; //API Secret get from conscent dashboard

    //function for Fetching data from API
    const API_BASE_URL = getEnvDetails(mode);
    const url = `${API_BASE_URL}/client/generate-temp-token`;
    const body = JSON.stringify({
        "email": email
    });
    console.log(body);
    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
                Authorization: "Basic " + base64.encode(username + ":" + password),
            },
            body: body,
        });
        const data = await response.json();

        return data;
    } catch (error) {
        console.error(error);
    } finally {

    }

}
```

**Auto login uses webview to login users into ConsCent's system.**&#x20;

```javascript
import { getEnvDetails, getLoginChallengeId, getServiceEnvDetails } from 'csc-react-native-sdk';

export const autoLoginView = async (tempToken, clientId, email, phoneNumber, currentStackScreenName, navigation, mode) => {

    const API_BASE_URL = getEnvDetails(mode);
    const loginChallengeId = await getLoginChallengeId(API_BASE_URL);
    const FRONT_END_BASE_URL = getServiceEnvDetails(mode);
    const encodeEmail = base64.encode(email)
    try {

        const REDIRECT_URL = `${FRONT_END_BASE_URL}/auto-login-user?id=${tempToken}&clientId=${clientId}&phone=${phoneNumber}&email=${encodeEmail}&loginChallengeId=${loginChallengeId}`


        navigation.navigate('ConscentWebView', {
            REDIRECT_URL: REDIRECT_URL,
            currentStackName: currentStackScreenName,
            mode
        });

        
    } catch (error) {
       console.log(error);
    }

}
```

**Check whether the User is login or not**

```javascript
import { isLogin } from 'csc-react-native-sdk';

    // Call this method to check the user is login or not. It will return boolean value
    const response = await isLogin();
```

**Parameters to pass in autoLoginView**

* tempToken : Gets from generateTempToken api
* clientId: Pass your clientId received from Conscent.ai.
* email: Pass user email gets from your Google login
* phone: Pass the phone number if you are signing in the user using the phone number
* currentStackScreenName: Pass your current stack screen component name
* navigation: Pass your navigation object to the current screen.
* mode: Pass your environment mode
* Mode can be set as : `STAGING` `SANDBOX` `LIVE`

</details>

<details>

<summary>Logout Functionality</summary>

```javascript
import { userLogout, getEnvDetails } from 'csc-react-native-sdk';

    // Call this method to logout
    userLogout(getEnvDetails(mode))
```

</details>

### Demo app [Link](https://github.com/RoshanSharma8245/csc-react-native-demo)
